answer
stringlengths 17
10.2M
|
|---|
package uk.ac.ebi.biosamples.utils.bioschemasrestclient;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Scanner;
import java.util.concurrent.Callable;
import org.apache.commons.io.FileUtils;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
public class BioSchemasRdfGenerator implements Callable<Void> {
private static final String FILE_PATH = "c:\\users\\dgupta\\file_8.ttl";
private static File file;
private static int sampleCount = 0;
private final URL url;
static {
file = new File(FILE_PATH);
}
BioSchemasRdfGenerator(final URL url) {
System.out.println("HANDLING " + url.toString() + " sample count: " + ++sampleCount);
this.url = url;
}
@Override
public Void call() throws Exception {
requestHTTPAndHandle(this.url);
return null;
}
@SuppressWarnings(value = "deprecation")
private static void write(final String sampleData) throws Exception {
FileUtils.writeStringToFile(file, sampleData, true);
}
/**
* @param in a rdf input stream
* @return a string representation
*/
private static String readRdfToString(final InputStream in) {
return graphToString(readRdfToGraph(in));
}
/**
* @param inputStream an Input stream containing rdf data
* @return a Graph representing the rdf in the input stream
*/
private static Collection<Statement> readRdfToGraph(final InputStream inputStream) {
try {
final RDFParser rdfParser = Rio.createParser(RDFFormat.JSONLD);
final StatementCollector collector = new StatementCollector();
rdfParser.setRDFHandler(collector);
rdfParser.parse(inputStream, "");
return collector.getStatements();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* Transforms a graph to a string.
*
* @param myGraph a sesame rdf graph
* @return a rdf string
*/
private static String graphToString(final Collection<Statement> myGraph) {
final StringWriter out = new StringWriter();
//final RDFWriter writer = Rio.createWriter(RDFFormat.TURTLE, out);
final TurtleWriterCustom turtleWriterCustom = new TurtleWriterCustom(out);
return writeRdfTurtle(myGraph, out, turtleWriterCustom);
}
private static String writeRdfTurtle(Collection<Statement> myGraph, StringWriter out, TurtleWriterCustom writer) {
try {
writer.startRDF();
handleNamespaces(writer);
for (Statement st : myGraph) {
if(st.getObject().stringValue().contains("biosample")) {
System.out.println("TRUEE");
}
writer.handleStatement(st);
}
writer.endRDF();
} catch (RDFHandlerException e) {
throw new RuntimeException(e);
}
return out.getBuffer().toString();
}
private static void handleNamespaces(TurtleWriterCustom writer) {
writer.handleNamespace("SCHEMA", "http://schema.org/");
writer.handleNamespace("PURL", "http://purl.obolibrary.org/");
}
private static void requestHTTPAndHandle(final URL url) throws Exception {
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int response = 0;
try {
conn.setRequestMethod("GET");
conn.connect();
response = conn.getResponseCode();
if (response == 200) {
handleSuccessResponses(url);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
conn.disconnect();
}
}
private static void handleSuccessResponses(final URL url) throws IOException, Exception {
try (Scanner sc = new Scanner(url.openStream())) {
final StringBuilder sb = new StringBuilder();
while (sc.hasNext()) {
sb.append(sc.nextLine());
}
try (InputStream in = new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8))) {
String dataAsRdf = readRdfToString(in);
write(dataAsRdf);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
|
package codeine.servlets.api_servlets.angular;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import codeine.ConfigurationManagerServer;
import codeine.jsons.project.ProjectJson;
import codeine.model.Constants;
import codeine.permissions.IUserWithPermissions;
import codeine.permissions.UserPermissionsGetter;
import codeine.plugins.AfterProjectModifyPlugin;
import codeine.plugins.AfterProjectModifyPlugin.StatusChange;
import codeine.servlet.AbstractApiServlet;
import codeine.utils.JsonUtils;
public class ProjectConfigurationApiServlet extends AbstractApiServlet {
private static final Logger log = Logger.getLogger(ProjectConfigurationApiServlet.class);
private static final long serialVersionUID = 1L;
@Inject private ConfigurationManagerServer configurationManager;
@Inject private UserPermissionsGetter permissionsManager;
@Inject private AfterProjectModifyPlugin afterProjectModifyPlugin;
@Override
protected boolean checkPermissions(HttpServletRequest request) {
if (request.getMethod().equals("DELETE")) {
return permissionsManager.user(request).isAdministrator();
}
if (request.getMethod().equals("PUT")) {
return canConfigureProject(request);
}
if (request.getMethod().equals("POST")) {
return canConfigureProject(request);
}
return canReadProject(request);
}
@Override
protected void myGet(HttpServletRequest request, HttpServletResponse response) {
writeResponseJson(response, configurationManager.getProjectForName(getParameter(request, Constants.UrlParameters.PROJECT_NAME)));
}
@Override
protected void myPut(HttpServletRequest request, HttpServletResponse resp) {
ProjectJson projectJson = readBodyJson(request, ProjectJson.class);
log.info("Updating configuration of " + projectJson.name() + ", new configuration is " + projectJson);
boolean exists = configurationManager.updateProject(projectJson);
afterProjectModifyPlugin.call(projectJson, exists ? StatusChange.modify : StatusChange.add);
writeResponseJson(resp,projectJson);
}
@Override
protected void myDelete(HttpServletRequest request, HttpServletResponse response) {
log.info("got delete request");
IUserWithPermissions user = permissionsManager.user(request);
String projectName = getParameter(request, Constants.UrlParameters.PROJECT_NAME);
log.info("project " + projectName + " user " + user.user().username());
ProjectJson projectToDelete = JsonUtils.cloneJson(configurationManager.getProjectForName(projectName), ProjectJson.class);
configurationManager.deleteProject(projectToDelete);
log.info("Project " + projectToDelete.name() + " was deleted by user " + user);
afterProjectModifyPlugin.call(projectToDelete, StatusChange.remove);
getWriter(response).write("{}");
}
@Override
protected void myPost(HttpServletRequest request, HttpServletResponse response) {
log.info("got post (reload) request");
IUserWithPermissions user = permissionsManager.user(request);
String projectName = getParameter(request, Constants.UrlParameters.PROJECT_NAME);
log.info("reloading project " + projectName + " user " + user.user().username());
configurationManager.reloadProject(projectName);
}
}
|
package jade.core;
import java.io.Serializable;
import java.io.Writer; // FIXME: This must go away
import java.io.IOException; // FIXME: This must go away
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.Enumeration;
/**
This class represents a JADE Agent Identifier. JADE internal agent
tables use this class to record agent names and addresses.
*/
public class AID implements Cloneable, Comparable, Serializable {
private String name = new String();
private List addresses = new ArrayList();
private List resolvers = new ArrayList();
private Properties userDefSlots = new Properties();
/**
* Constructs an Agent-Identifier whose slot name is set to an empty string
*/
public AID() {
this("");
}
/** constructor for an Agent-identifier
* @param guid is the Globally Unique identifer for the agent. The slot name
* assumes that value in the constructed object.
*/
public AID(String guid) {
name =guid;
}
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void addAddresses(String url) {
addresses.add(url);
}
public boolean removeAddresses(String url) {
return addresses.remove(url);
}
public void clearAllAddresses(){
addresses.clear();
}
public Iterator getAllAddresses(){
return addresses.iterator();
}
public void addResolvers(AID aid){
resolvers.add(aid);
}
public boolean removeResolvers(AID aid){
return resolvers.remove(aid);
}
public void clearAllResolvers(){
resolvers.clear();
}
public Iterator getAllResolvers() {
return resolvers.iterator();
}
public void addUserDefinedSlot(String key, String value){
userDefSlots.setProperty(key, value);
}
/**
* @return all the user-defined slots as a <code>java.util.Properties</code> java Object.
*/
public Properties getAllUserDefinedSlot(){
return userDefSlots;
}
/**
* This method is called from ACLMessage in order to create
* the String encoding of an ACLMessage.
*/
public void toText(Writer w) {
try {
w.write("( agent-identifier ");
if ((name!=null)&&(name.length()>0))
w.write(":name "+name);
if (addresses.size()>0)
w.write(":addresses (sequence ");
for (int i=0; i<addresses.size(); i++)
try {
w.write((String)addresses.get(i) + " ");
} catch (IndexOutOfBoundsException e) {e.printStackTrace();}
if (addresses.size()>0)
w.write(")");
if (resolvers.size()>0)
w.write(":resolvers (sequence ");
for (int i=0; i<resolvers.size(); i++) {
try {
((AID)resolvers.get(i)).toText(w);
} catch (IndexOutOfBoundsException e) {e.printStackTrace();}
w.write(" ");
}
if (resolvers.size()>0)
w.write(")");
Enumeration e = userDefSlots.propertyNames();
String tmp;
while (e.hasMoreElements()) {
tmp = (String)e.nextElement();
w.write(" " + tmp + " " + userDefSlots.getProperty(tmp));
}
w.write(")");
w.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public String toString() {
return name;
}
public synchronized Object clone() {
AID result;
try {
result = (AID)super.clone();
}
catch(CloneNotSupportedException cnse) {
result = new AID();
// throw new InternalError(); // This should never happen
}
return result;
}
/**
Equality operation. This method compares an <code>AID</code> object with
another or with a Java <code>String</code>. The comparison is case
insensitive.
@param o The Java object to compare this <code>AID</code> to.
@return <code>true</code> if one of the following holds:
<ul>
<li> The argument <code>o</code> is an <code>AID</code> object
with the same <em>GUID</em> in its name slot (apart from
differences in case).
<li> The argument <code>o</code> is a <code>String</code> that is
equal to the <em>GUID</em> contained in the name slot of this
Agent ID (apart from differences in case).
</ul>
*/
public boolean equals(Object o) {
if(o instanceof String) {
return name.equalsIgnoreCase((String)o);
}
try {
AID id = (AID)o;
return name.equalsIgnoreCase(id.name);
}
catch(ClassCastException cce) {
return false;
}
}
/**
Comparison operation. This operation imposes a total order
relationship over Agent IDs.
@param o Another <code>AID</code> object, that will be compared
with the current <code>AID</code>.
@return -1, 0 or 1 according to the lexicographical order of the
<em>GUID</em> of the two agent IDs, apart from differences in
case.
*/
public int compareTo(Object o) {
AID id = (AID)o;
return name.compareToIgnoreCase(id.name);
}
/**
Hash code. This method returns an hash code in such a way that two
<code>AID</code> objects with equal names or with names differing
only in case have the same hash code.
@return The hash code for this <code>AID</code> object.
*/
public int hashCode() {
return name.toLowerCase().hashCode();
}
String getLocalName() {
int atPos = name.lastIndexOf('@');
if(atPos == -1)
return name;
else
return name.substring(0, atPos);
}
String getHap() {
int atPos = name.lastIndexOf('@');
if(atPos == -1)
return name;
else
return name.substring(atPos + 1);
}
}
|
package br.eti.rslemos.nlp.tagger.gate;
import gate.Document;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import br.eti.rslemos.tagger.Sentence;
import br.eti.rslemos.tagger.SentenceIndexOutOfBoundsException;
import br.eti.rslemos.tagger.Token;
public class LowMemoryFootprintDocument extends AbstractList<Sentence> {
private final String[] featureNames;
private final Object[][] features;
private final int[] sentencesEnd;
public LowMemoryFootprintDocument(Document doc, String annotationSetName, String... featureNames) {
this(new LightDocument(doc, annotationSetName), featureNames);
}
public LowMemoryFootprintDocument(List<Sentence> doc, String... featureNames) {
this.featureNames = new String[featureNames.length + 1];
System.arraycopy(featureNames, 0, this.featureNames, 0, featureNames.length);
for (int i = 0; i < featureNames.length; i++) {
this.featureNames[i] = this.featureNames[i].intern();
}
this.featureNames[featureNames.length] = Token.WORD;
Arrays.sort(this.featureNames);
final int idxWORD = Arrays.binarySearch(this.featureNames, Token.WORD);
// build sentences as token offsets (and compute feature matrix size)
sentencesEnd = new int[doc.size()];
int i = 0;
Iterator<Sentence> sentenceIt = doc.iterator();
while (sentenceIt.hasNext()) {
Sentence sentence = sentenceIt.next();
sentencesEnd[i] = getSentenceStart(i) + sentence.size();
i++;
}
// build token matrix
features = new Object[sentencesEnd[doc.size()-1]][this.featureNames.length];
int j = 0;
for (Sentence sentence : doc) {
for (Token token : sentence) {
Map<String, Object> featureMap = token.getFeatures();
for (int k = 0; k < this.featureNames.length; k++) {
features[j][k] = featureMap.get(this.featureNames[k]);
if (k != idxWORD)
features[j][k] = internalize(features[j][k]);
}
j++;
}
}
}
@Override
public Sentence get(int index) {
return new LowMemoryFootprintSentence(index);
}
@Override
public int size() {
return sentencesEnd.length;
}
private static Object internalize(Object o) {
if (o instanceof String)
return ((String)o).intern();
if (o instanceof Boolean)
return Boolean.valueOf((Boolean)o);
if (o instanceof Integer)
return Integer.valueOf((Integer)o);
if (o instanceof Long)
return Long.valueOf((Long)o);
if (o instanceof Character)
return Character.valueOf((Character)o);
if (o instanceof Short)
return Short.valueOf((Short)o);
if (o instanceof Byte)
return Byte.valueOf((Byte)o);
return o;
}
private int getSentenceStart(int index) {
return index > 0 ? sentencesEnd[index-1] : 0;
}
private final class LowMemoryFootprintSentence implements Sentence {
private final int index;
private LowMemoryFootprintSentence(int index) {
this.index = index;
}
@Override
public int size() {
return sentencesEnd[index] - getSentenceStart(index);
}
@Override
public Token get(int i) throws SentenceIndexOutOfBoundsException {
return new LowMemoryFootprintToken(index, i);
}
@Override
public Iterator<Token> iterator() {
throw new UnsupportedOperationException();
}
}
private final class LowMemoryFootprintToken implements Token {
private final int i;
private final int index;
private LowMemoryFootprintToken(int index, int i) {
this.index = index;
this.i = i;
}
@Override
public Object getFeature(String name) {
return getFeatures().get(name);
}
@Override
public Map<String, Object> getFeatures() {
return new FeatureMap();
}
@Override
public Token setFeature(String name, Object value) {
throw new UnsupportedOperationException();
}
private final class FeatureMap extends AbstractMap<String, Object> {
@Override
public Set<Entry<String, Object>> entrySet() {
return new FeatureSet();
}
}
private final class FeatureSet extends AbstractSet<Entry<String, Object>> {
@Override
public Iterator<Entry<String, Object>> iterator() {
return new FeatureSetIterator();
}
@Override
public int size() {
return featureNames.length;
}
}
private final class FeatureSetIterator implements Iterator<Entry<String, Object>> {
int j = 0;
@Override
public boolean hasNext() {
return j < featureNames.length;
}
@Override
public Entry<String, Object> next() {
try {
return new SimpleEntry<String, Object>(featureNames[j], features[i + getSentenceStart(index)][j]);
} finally {
j++;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
}
|
/*
*@author Avinash Koshal
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Test { //main class of the program
private Frame myFrame;
private Label topLabel;
private Label bottomLabel1;
private Label bottomlabel2;
private Label errorMessage;
private Label message;
private Panel panel1;
private Panel panel2;
public Test(){ //constructor of the test class
makeGui();
}
public void makeGui(){ //definition of GUI function
myFrame = new Frame("Assn");
myFrame.setBackground(Color.CYAN);
myFrame.setSize(600,500);
myFrame.setLayout(new GridLayout(8,1));
myFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){ //closes the window on pressing the cross button
System.exit(0);
}
});
topLabel = new Label();
topLabel.setAlignment(Label.CENTER);
message = new Label();
message.setAlignment(Label.CENTER);
errorMessage = new Label();
errorMessage.setAlignment(Label.CENTER);
bottomLabel1 = new Label();
bottomLabel1.setAlignment(Label.CENTER);
bottomlabel2 = new Label();
bottomlabel2.setAlignment(Label.CENTER);
panel1 = new Panel();
panel1.setLayout(new FlowLayout());
panel2 = new Panel();
panel2.setLayout(new FlowLayout());
myFrame.add(topLabel);
myFrame.add(panel1);
myFrame.add(bottomLabel1);
myFrame.add(bottomlabel2);
myFrame.add(message);
myFrame.add(errorMessage);
myFrame.add(panel2);
myFrame.setVisible(true);
topLabel.setText("click to browse files");
}
public static String checkOS() { //check for the OS type
String store = "";
String OS = System.getProperty("os.name").toLowerCase();
if(OS.indexOf("win") >= 0){
store = "/root/Desktop/";
} else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
store = "/home/";
} else if(OS.indexOf("mac") >= 0){
store = "/home/";
} else{
return null;
}
return store;
}
public static String getExtension(String fileName){ //return the filename selected by the user
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);// to get part of string substring() is used. Here (i+1) is the begining index of the substring.
}
return extension;
}
private void action() {
Button button1 = new Button("BROWSE"); //creation of button1
myFrame.add(button1);
panel1.add(button1);
Button button2 = new Button("SAVED FILES");
myFrame.add(button2);
panel2.add(button2);
FileDialog fileDialog = new FileDialog(myFrame);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
//storing path of selected file in fileName
String fileName = fileDialog.getDirectory() + fileDialog.getFile();
//splitting of files
try {
split(fileName);
} catch (IOException e1) {
e1.printStackTrace();
}
File file = new File(fileName);
bottomLabel1.setText("You have selected the file:-> " + fileDialog.getFile()
+ " , from Directory :-> " + fileDialog.getDirectory() );
bottomlabel2.setText( "The length of file is "+ file.length() + " Bytes"
+ " ( " + (file.length()/1024) + " kB ) and the extension (type of file) is " + getExtension(fileName));
//Here first, the write protection of directory is checked and the the file is saved to that location
if(file.canWrite()){
Path sourceFile = Paths.get(fileName);
Path targetFile = Paths.get(checkOS() + "CopyOf-"+fileDialog.getFile()+"." + getExtension(fileName));//accepts sitable path from checkOS function
try {
Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
errorMessage.setText("I/O Error when copying file. Check write protections.");
}
}
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setDirectory(checkOS());
fileDialog.setVisible(true);
}
});
}
public static void split(String fileName) throws IOException {
RandomAccessFile raf = new RandomAccessFile(fileName, "r");
long numSplits = 10;
long sourceSize = raf.length();
long bytesPerSplit = sourceSize / numSplits;
long remainingBytes = sourceSize % numSplits;
int maxReadBufferSize = 8 * 1024; //8KB
for (int destIx = 1; destIx <= numSplits; destIx++) {
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(checkOS() + "split." + destIx + "." + getExtension(fileName)));//getting path by checkOS()
if (bytesPerSplit > maxReadBufferSize) {
long numReads = bytesPerSplit / maxReadBufferSize;
long numRemainingRead = bytesPerSplit % maxReadBufferSize;
for (int i = 0; i < numReads; i++) {
readWrite(raf, bw, maxReadBufferSize);
}
if (numRemainingRead > 0) {
readWrite(raf, bw, numRemainingRead);
}
} else {
readWrite(raf, bw, bytesPerSplit);
}
bw.close();
}
if (remainingBytes > 0)
{
//BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(checkOS() + "RemainingSplit." + (numSplits + 1)));
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(checkOS() + "RemainingSplit." + getExtension(fileName)));
readWrite(raf, bw, remainingBytes);
bw.close();
}
raf.close();
}
public static void readWrite(RandomAccessFile raf, BufferedOutputStream bw, long numBytes) throws IOException {
byte[] buf = new byte[(int) numBytes];
int val = raf.read(buf);
if (val != -1) {
bw.write(buf);
}
}
public static void main(String[] args) throws IOException {
Test test = new Test(); //obect of the Test class
// awt.checkOS();
test.action();
}
}
|
package lukazitnik.jshint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.LinkedList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import sun.org.mozilla.javascript.Context;
import sun.org.mozilla.javascript.Function;
import sun.org.mozilla.javascript.NativeArray;
import sun.org.mozilla.javascript.NativeObject;
import sun.org.mozilla.javascript.Scriptable;
/**
*
* @author luka
*/
public class JSHint {
public JSHint() {
}
public LinkedList<JSHintError> lint(FileObject fo) {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
LinkedList<JSHintError> result = new LinkedList<JSHintError>();
try {
Function jshint = getJSHint(cx, scope);
Scriptable config = jsonToScriptable(cx, scope, getConfig(fo));
Object args[] = {fo.asText(), config};
jshint.call(cx, scope, scope, args);
NativeArray errors = (NativeArray) jshint.get("errors", null);
for (Object error : errors) {
if (error == null) {
// I don't know what null means
// I believe it follows js files with "Too many errors."
continue;
}
result.push(new JSHintError((NativeObject) error));
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
} finally {
Context.exit();
}
return result;
}
private JSONObject getConfig(FileObject fo) throws IOException, ParseException {
JSONParser parser = new JSONParser();
FileObject config = findConfig(fo);
if (config == null) {
return (JSONObject) parser.parse("{}");
}
return (JSONObject) parser.parse(config.asText());
}
private FileObject findConfig(FileObject fo) {
return findFile(".jshintrc", fo.getParent());
}
public static FileObject findFile(String name, FileObject folder) {
FileObject fo = folder.getFileObject(name, "");
if (fo != null && fo.isData()) {
return fo;
}
if (folder.isRoot()) {
return null;
}
return findFile(name, folder.getParent());
}
private Scriptable jsonToScriptable(Context cx, Scriptable scope, JSONObject obj) {
Scriptable scriptable = cx.newObject(scope);
for (Object key : obj.keySet()) {
scriptable.put(key.toString(), scriptable, obj.get(key).toString());
}
return scriptable;
}
private Function getJSHint(Context cx, Scriptable scope) throws IOException {
Reader in = getReader();
cx.evaluateReader(scope, in, "jshint.js", 1, null);
return (Function) scope.get("JSHINT", scope);
}
private Reader getReader() throws IOException {
// jshint.js is the web bundle of the JSHint, downloaded from
InputStream stream = getClass().getResourceAsStream("jshint.js");
return new BufferedReader(new InputStreamReader(stream));
}
}
|
package magefortress.core;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import magefortress.channel.MFChannelFactory;
import magefortress.channel.MFCommunicationChannel;
import magefortress.creatures.MFCreature;
import magefortress.creatures.behavior.MFEJob;
import magefortress.creatures.behavior.MFEMovementType;
import magefortress.graphics.MFImageLibrary;
import magefortress.gui.MFScreen;
import magefortress.jobs.MFConstructionSite;
import magefortress.jobs.MFJobFactory;
import magefortress.map.MFMap;
import magefortress.map.MFNavigationMap;
import magefortress.map.MFPathFinder;
import magefortress.map.MFTile;
import magefortress.storage.MFDaoFactory;
/**
* Single place for all game data.
*/
public class MFGame
{
public static MFGame loadGame(int _mapId, MFImageLibrary _imgLib, MFDaoFactory _daoFactory)
{
final MFMap map = MFMap.loadMap(_mapId, _daoFactory);
final MFGame result = new MFGame(map, _imgLib, _daoFactory);
return result;
}
public MFGame(MFMap _map, MFImageLibrary _imgLib, MFDaoFactory _daoFactory)
{
if (_map == null) {
String msg = this.getClass().getSimpleName() + ": Cannot create game " +
"without a map.";
logger.severe(msg);
throw new IllegalArgumentException(msg);
}
if (_daoFactory == null) {
String msg = this.getClass().getSimpleName() + ": Cannot create game " +
"without a DAO factory.";
logger.severe(msg);
throw new IllegalArgumentException(msg);
}
this.map = _map;
this.daoFactory = _daoFactory;
this.jobFactory = new MFJobFactory(this);
this.gameObjectFactory = new MFGameObjectFactory(_imgLib, this.jobFactory, _map);
this.channels = new LinkedList<MFCommunicationChannel>();
initCommunicationChannels();
this.creatures = new LinkedList<MFCreature>();
this.constructionSites = new LinkedList<MFConstructionSite>();
this.garbageConstructionSites = new LinkedList<MFConstructionSite>();
this.pathFinder = this.gameObjectFactory.createPathFinder();
this.naviMap = new MFNavigationMap(this.map);
initPathFinder();
}
public void update()
{
removeMarkedConstructionSites();
processCommunicationChannels();
processCreatures();
processConstructionSites();
processPathFinder();
}
public void paint(Graphics2D _g, int _currentLevel, Rectangle _clippingRect)
{
this.map.paint(_g, _currentLevel, _clippingRect);
final MFLocation start = this.map.getVisibleStart(_currentLevel, _clippingRect);
final MFLocation end = this.map.getVisibleEnd(_currentLevel, _clippingRect);
paintCreatures(_currentLevel, start, end, _g, _clippingRect);
paintConstructionSites(_currentLevel, start, end, _g, _clippingRect);
}
/**
* The size of a map tile
* @return The size of a map tile
*/
public int getTileSize()
{
return MFTile.TILESIZE;
}
/**
* The currently active map
* @return The map
*/
public MFMap getMap()
{
return this.map;
}
/**
* The game object producer
* @return The game object factory
*/
public MFGameObjectFactory getGameObjectFactory()
{
return this.gameObjectFactory;
}
/**
* Important! Set this after you've initialized the view.
* @param _screen The view of the game
*/
public void setScreen(MFScreen _screen)
{
this.screen = _screen;
}
/**
* Removes the newest screen from the screens stack, which should be an
* instance of this game's game screen.
*/
public void quit()
{
if (this.screen == null) {
String msg = "Game: Can't call close() without a screen. Set it!";
logger.log(Level.SEVERE, msg);
throw new NullPointerException(msg);
}
this.screen.close();
}
/**
* Adds a creature to the game. It does not have to be placed on the map.
* It will be processed regardless.
* @param _creature The creature to add.
*/
public void addCreature(MFCreature _creature)
{
this.creatures.add(_creature);
}
/**
* Adds a construction site. Does not check if there's already a site at
* the position of the new construction site.
* @param _constructionSite The construction site to add
*/
public void addConstructionSite(MFConstructionSite _constructionSite)
{
this.constructionSites.add(_constructionSite);
}
/**
* Marks a construction site for removal. Removing will take place at the
* beginning of the next game update.
* @param _location The location of the site to remove.
*/
public void removeConstructionSite(MFLocation _location)
{
for (MFConstructionSite site : this.constructionSites) {
if (site.getLocation().equals(_location)) {
// mark for removal
this.garbageConstructionSites.add(site);
}
}
}
/**
* Iterates over all construction site. Do not try to remove sites directly,
* but use {@link #removeConstructionSite}.
* @return An iterator over all construction sites
*/
public Iterable<MFConstructionSite> getConstructionSites()
{
return Collections.unmodifiableList(this.constructionSites);
}
/** The view on the game */
private MFScreen screen;
/** The map */
private MFMap map;
/** Communications channels*/
private final List<MFCommunicationChannel> channels;
/** Relevant creatures */
private final List<MFCreature> creatures;
/** Construction sites */
private final List<MFConstructionSite> constructionSites;
private final List<MFConstructionSite> garbageConstructionSites;
/** Factory for all game object like creatures, items, plants */
private final MFGameObjectFactory gameObjectFactory;
/** DAO factory */
private final MFDaoFactory daoFactory;
/** Job factory */
private final MFJobFactory jobFactory;
/** Navigation map containing pathfinding information */
private final MFNavigationMap naviMap;
/** Holds a queue of path searches */
private final MFPathFinder pathFinder;
/** The logger */
private static final Logger logger = Logger.getLogger(MFGame.class.getName());
private final void initCommunicationChannels()
{
MFChannelFactory channelFactory = this.gameObjectFactory.createChannelFactory();
for (MFEJob channelType : MFEJob.values()) {
this.channels.add(channelFactory.getChannel(channelType));
}
}
private final void initPathFinder()
{
this.naviMap.updateClearanceValues(MFEMovementType.WALK);
this.naviMap.updateAllEntrances();
}
private void processCommunicationChannels()
{
// process channels
for (MFCommunicationChannel channel : this.channels) {
channel.update();
}
}
private void processCreatures()
{
for (MFCreature creature : this.creatures) {
creature.update();
}
}
private void processConstructionSites()
{
for (MFConstructionSite site: this.constructionSites) {
site.update();
}
}
private void processPathFinder()
{
this.pathFinder.update();
}
private void paintCreatures(int _currentLevel, MFLocation _start,
MFLocation _end, Graphics2D _g, Rectangle _clippingRect)
{
for (MFCreature creature : this.creatures) {
MFLocation location = creature.getLocation();
if (location.z == _currentLevel &&
_start.x <= location.x && location.x <= _end.x &&
_start.y <= location.y && location.y <= _end.y) {
creature.paint(_g, _clippingRect.x, _clippingRect.y);
}
}
}
private void paintConstructionSites(int _currentLevel, MFLocation _start,
MFLocation _end, Graphics2D _g, Rectangle _clippingRect)
{
for (MFConstructionSite site : this.constructionSites) {
MFLocation location = site.getLocation();
if (location.z == _currentLevel &&
_start.x <= location.x && location.x <= _end.x &&
_start.y <= location.y && location.y <= _end.y) {
site.paint(_g, _clippingRect.x, _clippingRect.y);
}
}
}
private void removeMarkedConstructionSites()
{
this.constructionSites.removeAll(this.garbageConstructionSites);
}
}
|
package jade.core;
//#APIDOC_EXCLUDE_FILE
import jade.util.leap.Map;
import jade.util.leap.HashMap;
import jade.util.leap.Serializable;
import jade.util.Logger;
/**
This class provides a partial implementation of the
<code>Node</code> interface. Concrete IMTPs will have to provide a
full implementation of the <code>Node</code> interface, possibly by
subclassing this class.
@author Giovanni Rimassa - FRAMeTech s.r.l.
*/
public abstract class BaseNode implements Node, Serializable {
private Logger myLogger;
public BaseNode(String name, boolean hasPM) {
myName = name;
hasLocalPM = hasPM;
localSlices = new HashMap(5);
myLogger = Logger.getMyLogger(getClass().getName());
}
public void setName(String name) {
myName = name;
}
public String getName() {
return myName;
}
public boolean hasPlatformManager() {
return hasLocalPM;
}
public void exportSlice(String serviceName, Service.Slice localSlice) {
localSlices.put(serviceName, localSlice);
}
public void unexportSlice(String serviceName) {
localSlices.remove(serviceName);
}
protected Service.Slice getSlice(String serviceName) {
return (Service.Slice)localSlices.get(serviceName);
}
/**
Provides an IMTP independent implementation for the
horizontal command serving mechanism. IMTP dependent implementations
of the accept() method should invoke this method.
@param cmd The horizontal command to process.
@return The object that is the result of processing the command.
@throws ServiceException If the service the command belongs to
is not present on this node.
*/
public Object serveHorizontalCommand(HorizontalCommand cmd) throws ServiceException {
String serviceName = cmd.getService();
String commandName = cmd.getName();
Object[] commandParams = cmd.getParams();
if (myLogger.isLoggable(Logger.FINE)) {
myLogger.log(Logger.FINE, "Node "+myName+" serving incoming H-Command "+commandName+" of Service "+serviceName);
}
// Look up in the local slices table and find the slice to dispatch to
Service.Slice slice = getSlice(serviceName);
if(slice != null) {
Object ret = null;
VerticalCommand vCmd = slice.serve(cmd);
if(vCmd != null) {
vCmd.setPrincipal(cmd.getPrincipal());
vCmd.setCredentials(cmd.getCredentials());
// Hand it to the command processor
if (myLogger.isLoggable(Logger.FINE)) {
myLogger.log(Logger.FINE, "Node "+myName+" issuing incoming V-Command "+vCmd.getName()+" of Service "+vCmd.getService());
}
serveVerticalCommand(vCmd);
ret = vCmd.getReturnValue();
}
else {
ret = cmd.getReturnValue();
}
if (ret != null) {
if (myLogger.isLoggable(Logger.FINE)) {
myLogger.log(Logger.FINE, "Node "+myName+" return value for incoming H-Command "+commandName+" of Service "+serviceName+" = "+ret);
}
}
return ret;
}
else {
String s = new String("Node "+myName+": Service "+serviceName+" Unknown. Command = "+commandName);
throw new ServiceException("
}
}
public void setCommandProcessor(CommandProcessor cp) {
processor = cp;
}
public void setServiceManager(ServiceManager mgr) {
myServiceManager = mgr;
}
public void platformManagerDead(String deadPMAddr, String notifyingPMAddr) throws IMTPException {
myServiceManager.addAddress(notifyingPMAddr);
myServiceManager.removeAddress(deadPMAddr);
}
/**
Serves an incoming vertical command, locally. This method is
invoked if a new <code>VerticalCommand</code> object is
generated by a slice targetted by a former
<code>HorizontalCommand</code>, which happens if the
<code>Slice.serve()</code> yields a non-null result.
This method makes it so that the newly created vertical command
is handed to the command processor to first pass through all
incoming filters and then to be dispatched to its proper
incoming command sink.
@param cmd The vertical command to process.
@return The object that is the result of processing the command.
@throws ServiceException If some problem occurs.
*/
private Object serveVerticalCommand(VerticalCommand cmd) throws ServiceException {
if(processor == null) {
throw new ServiceException("No command processor for node <" + getName() + ">");
}
return processor.processIncoming(cmd);
}
protected transient ServiceManager myServiceManager;
private transient CommandProcessor processor;
// The name of this node
private String myName;
// True if a local copy of the Platform Manager is deployed at this Node
private boolean hasLocalPM = false;
// A map, indexed by service name, of all the local slices of this
// node. This map is used to dispatch incoming commands to the
// service they belong to.
private transient Map localSlices;
}
|
package de.espend.idea.php.annotation.tests;
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase;
import com.intellij.codeInsight.completion.CompletionProgressIndicator;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.codeInsight.daemon.LineMarkerProviders;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.codeInspection.*;
import com.intellij.navigation.GotoRelatedItem;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementVisitor;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndexImpl;
import com.intellij.util.indexing.ID;
import com.intellij.util.ui.UIUtil;
import com.jetbrains.php.lang.psi.elements.Function;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpReference;
import de.espend.idea.php.annotation.Settings;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.*;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*
* Copy of SymfonyLightCodeInsightFixtureTestCase;
* TODO: Its time for a test framework extraction
*/
public abstract class AnnotationLightCodeInsightFixtureTestCase extends LightCodeInsightFixtureTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
}
public void assertCompletionContains(LanguageFileType languageFileType, String configureByText, String... lookupStrings) {
myFixture.configureByText(languageFileType, configureByText);
myFixture.completeBasic();
checkContainsCompletion(lookupStrings);
}
public void assertAtTextCompletionContains(String findByText, String... lookupStrings) {
final PsiElement element = myFixture.findElementByText(findByText, PsiElement.class);
assert element != null : "No element found by text: " + findByText;
myFixture.getEditor().getCaretModel().moveToOffset(element.getTextOffset() + 1);
myFixture.completeBasic();
checkContainsCompletion(lookupStrings);
}
public void assertCompletionNotContains(String text, String configureByText, String... lookupStrings) {
myFixture.configureByText(text, configureByText);
myFixture.completeBasic();
assertFalse(myFixture.getLookupElementStrings().containsAll(Arrays.asList(lookupStrings)));
}
public void assertCompletionNotContains(LanguageFileType languageFileType, String configureByText, String... lookupStrings) {
myFixture.configureByText(languageFileType, configureByText);
myFixture.completeBasic();
assertFalse(myFixture.getLookupElementStrings().containsAll(Arrays.asList(lookupStrings)));
}
public void assertCompletionContains(String filename, String configureByText, String... lookupStrings) {
myFixture.configureByText(filename, configureByText);
myFixture.completeBasic();
completionContainsAssert(lookupStrings);
}
private void completionContainsAssert(String[] lookupStrings) {
List<String> lookupElements = myFixture.getLookupElementStrings();
if(lookupElements == null) {
fail(String.format("failed that empty completion contains %s", Arrays.toString(lookupStrings)));
}
for (String s : Arrays.asList(lookupStrings)) {
if(!lookupElements.contains(s)) {
fail(String.format("failed that completion contains %s in %s", s, lookupElements.toString()));
}
}
}
public void assertNavigationContains(LanguageFileType languageFileType, String configureByText, String targetShortcut) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
assertNavigationContains(psiElement, targetShortcut);
}
public void assertNavigationContains(PsiElement psiElement, String targetShortcut) {
if(!targetShortcut.startsWith("\\")) {
targetShortcut = "\\" + targetShortcut;
}
Set<String> classTargets = new HashSet<String>();
for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
if(gotoDeclarationTargets != null && gotoDeclarationTargets.length > 0) {
for (PsiElement gotoDeclarationTarget : gotoDeclarationTargets) {
if(gotoDeclarationTarget instanceof Method) {
String meName = ((Method) gotoDeclarationTarget).getName();
String clName = ((Method) gotoDeclarationTarget).getContainingClass().getPresentableFQN();
if(!clName.startsWith("\\")) {
clName = "\\" + clName;
}
classTargets.add(clName + "::" + meName);
} else if(gotoDeclarationTarget instanceof Function) {
classTargets.add("\\" + ((Function) gotoDeclarationTarget).getName());
}
}
}
}
if(!classTargets.contains(targetShortcut)) {
fail(String.format("failed that PsiElement (%s) navigate to %s on %s", psiElement.toString(), targetShortcut, classTargets.toString()));
}
}
public void assertNavigationMatchWithParent(LanguageFileType languageFileType, String configureByText, IElementType iElementType) {
assertNavigationMatch(languageFileType, configureByText, PlatformPatterns.psiElement().withParent(PlatformPatterns.psiElement(iElementType)));
}
public void assertNavigationMatch(String filename, String configureByText, ElementPattern<?> pattern) {
myFixture.configureByText(filename, configureByText);
assertNavigationMatch(pattern);
}
public void assertNavigationMatch(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
myFixture.configureByText(languageFileType, configureByText);
assertNavigationMatch(pattern);
}
public void assertNavigationMatch(LanguageFileType languageFileType, String configureByText) {
myFixture.configureByText(languageFileType, configureByText);
assertNavigationMatch(PlatformPatterns.psiElement());
}
public void assertNavigationMatch(String filename, String configureByText) {
myFixture.configureByText(filename, configureByText);
assertNavigationMatch(PlatformPatterns.psiElement());
}
public void assertNavigationIsEmpty(LanguageFileType languageFileType, String configureByText) {
myFixture.configureByText(languageFileType, configureByText);
assertNavigationIsEmpty();
}
public void assertNavigationIsEmpty(String content, String configureByText) {
myFixture.configureByText(content, configureByText);
assertNavigationIsEmpty();
}
private void assertNavigationIsEmpty() {
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
if(gotoDeclarationTargets != null && gotoDeclarationTargets.length > 0) {
fail(String.format("failed that PsiElement (%s) navigate is empty; found target in '%s'", psiElement.toString(), gotoDeclarationHandler.getClass()));
}
}
}
private void assertNavigationMatch(ElementPattern<?> pattern) {
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
Set<String> targetStrings = new HashSet<String>();
for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
if(gotoDeclarationTargets == null || gotoDeclarationTargets.length == 0) {
continue;
}
for (PsiElement gotoDeclarationTarget : gotoDeclarationTargets) {
targetStrings.add(gotoDeclarationTarget.toString());
if(pattern.accepts(gotoDeclarationTarget)) {
return;
}
}
}
fail(String.format("failed that PsiElement (%s) navigate matches one of %s", psiElement.toString(), targetStrings.toString()));
}
public void assertNavigationContainsFile(LanguageFileType languageFileType, String configureByText, String targetShortcut) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
Set<String> targets = new HashSet<String>();
for (GotoDeclarationHandler gotoDeclarationHandler : Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
PsiElement[] gotoDeclarationTargets = gotoDeclarationHandler.getGotoDeclarationTargets(psiElement, 0, myFixture.getEditor());
if (gotoDeclarationTargets != null && gotoDeclarationTargets.length > 0) {
for (PsiElement gotoDeclarationTarget : gotoDeclarationTargets) {
if(gotoDeclarationTarget instanceof PsiFile) {
targets.add(((PsiFile) gotoDeclarationTarget).getVirtualFile().getUrl());
}
}
}
}
// its possible to have memory fields,
// so simple check for ending conditions
// temp:///src/interchange.en.xlf
for (String target : targets) {
if(target.endsWith(targetShortcut)) {
return;
}
}
fail(String.format("failed that PsiElement (%s) navigate to file %s", psiElement.toString(), targetShortcut));
}
public void assertCompletionLookupTailEquals(LanguageFileType languageFileType, String configureByText, String lookupString, String tailText) {
myFixture.configureByText(languageFileType, configureByText);
myFixture.completeBasic();
for (LookupElement lookupElement : myFixture.getLookupElements()) {
if(!lookupElement.getLookupString().equals(lookupString)) {
continue;
}
LookupElementPresentation presentation = new LookupElementPresentation();
lookupElement.renderElement(presentation);
if(presentation.getTailText() == null) {
fail(String.format("failed to check '%s'", lookupString));
}
if(!presentation.getTailText().equals(tailText)) {
fail(String.format("failed that on '%s' '%s' is equal '%s'", lookupString, tailText, presentation.getTailText()));
}
return;
}
fail(String.format("failed to check '%s' because it's unknown", lookupString));
}
public void assertPhpReferenceResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
if (psiElement == null) {
fail("Element is not PhpReference.");
}
assertTrue(pattern.accepts(((PhpReference) psiElement).resolve()));
}
public void assertPhpReferenceNotResolveTo(LanguageFileType languageFileType, String configureByText, ElementPattern<?> pattern) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
if (psiElement == null) {
fail("Element is not PhpReference.");
}
assertFalse(pattern.accepts(((PhpReference) psiElement).resolve()));
}
public void assertPhpReferenceSignatureEquals(LanguageFileType languageFileType, String configureByText, String typeSignature) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
psiElement = PsiTreeUtil.getParentOfType(psiElement, PhpReference.class);
if (!(psiElement instanceof PhpReference)) {
fail("Element is not PhpReference.");
}
assertEquals(typeSignature, ((PhpReference) psiElement).getSignature());
}
public void assertCompletionResultEquals(String filename, String complete, String result) {
myFixture.configureByText(filename, complete);
myFixture.completeBasic();
myFixture.checkResult(result);
}
public void assertCompletionResultEquals(LanguageFileType languageFileType, String complete, String result) {
myFixture.configureByText(languageFileType, complete);
myFixture.completeBasic();
myFixture.checkResult(result);
}
public void assertCheckHighlighting(String filename, String result) {
myFixture.configureByText(filename, result);
myFixture.checkHighlighting();
}
public void assertIndexContains(@NotNull ID<String, ?> id, @NotNull String... keys) {
assertIndex(id, false, keys);
}
public void assertIndexNotContains(@NotNull ID<String, ?> id, @NotNull String... keys) {
assertIndex(id, true, keys);
}
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
for (String key : keys) {
final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();
FileBasedIndexImpl.getInstance().getFilesWithKey(id, new HashSet<String>(Arrays.asList(key)), new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile virtualFile) {
virtualFiles.add(virtualFile);
return true;
}
}, GlobalSearchScope.allScope(getProject()));
if(notCondition && virtualFiles.size() > 0) {
fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
} else if(!notCondition && virtualFiles.size() == 0) {
fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
}
}
}
public void assertIndexContainsKeyWithValue(@NotNull ID<String, String> id, @NotNull String key, @NotNull String value) {
assertContainsElements(FileBasedIndexImpl.getInstance().getValues(id, key, GlobalSearchScope.allScope(getProject())), value);
}
public <T> void assertIndexContainsKeyWithValue(@NotNull ID<String, T> id, @NotNull String key, @NotNull IndexValue.Assert<T> tAssert) {
List<T> values = FileBasedIndexImpl.getInstance().getValues(id, key, GlobalSearchScope.allScope(getProject()));
for (T t : values) {
if(tAssert.match(t)) {
return;
}
}
fail(String.format("Fail that Key '%s' matches on of '%s' values", key, values.size()));
}
public void assertLocalInspectionContains(String filename, String content, String contains) {
Set<String> matches = new HashSet<String>();
Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
TextRange textRange = result.getPsiElement().getTextRange();
if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
return;
}
matches.add(result.toString());
}
fail(String.format("Fail matches '%s' with one of %s", contains, matches));
}
public void assertIntentionIsAvailable(LanguageFileType languageFileType, String configureByText, String intentionText) {
myFixture.configureByText(languageFileType, configureByText);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
if(intentionAction.isAvailable(getProject(), getEditor(), psiElement.getContainingFile()) && intentionAction.getText().equals(intentionText)) {
return;
}
}
fail(String.format("Fail intention action '%s' is available in element '%s'", intentionText, psiElement.getText()));
}
public void assertLocalInspectionContainsNotContains(String filename, String content, String contains) {
Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
TextRange textRange = result.getPsiElement().getTextRange();
if (textRange.contains(localInspectionsAtCaret.getSecond())) {
fail(String.format("Fail inspection not contains '%s'", contains));
}
}
}
private Pair<List<ProblemDescriptor>, Integer> getLocalInspectionsAtCaret(String filename, String content) {
PsiElement psiFile = myFixture.configureByText(filename, content);
int caretOffset = myFixture.getCaretOffset();
if(caretOffset <= 0) {
fail("Please provide <caret> tag");
}
ProblemsHolder problemsHolder = new ProblemsHolder(InspectionManager.getInstance(getProject()), psiFile.getContainingFile(), false);
for (LocalInspectionEP localInspectionEP : LocalInspectionEP.LOCAL_INSPECTION.getExtensions()) {
Object object = localInspectionEP.getInstance();
if(!(object instanceof LocalInspectionTool)) {
continue;
}
((LocalInspectionTool) object).buildVisitor(problemsHolder, false);
}
return new Pair<List<ProblemDescriptor>, Integer>(problemsHolder.getResults(), caretOffset);
}
protected void assertLocalInspectionIsEmpty(String filename, String content) {
Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
TextRange textRange = result.getPsiElement().getTextRange();
if (textRange.contains(localInspectionsAtCaret.getSecond())) {
fail("Fail that matches is empty");
}
}
}
protected void createDummyFiles(String... files) throws Exception {
for (String file : files) {
String path = myFixture.getProject().getBaseDir().getPath() + "/" + file;
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
}
}
private void checkContainsCompletion(String[] lookupStrings) {
completionContainsAssert(lookupStrings);
}
public void assertLineMarker(@NotNull PsiElement psiElement, @NotNull LineMarker.Assert assertMatch) {
final List<PsiElement> elements = collectPsiElementsRecursive(psiElement);
for (LineMarkerProvider lineMarkerProvider : LineMarkerProviders.INSTANCE.allForLanguage(psiElement.getLanguage())) {
Collection<LineMarkerInfo> lineMarkerInfos = new ArrayList<LineMarkerInfo>();
lineMarkerProvider.collectSlowLineMarkers(elements, lineMarkerInfos);
if(lineMarkerInfos.size() == 0) {
continue;
}
for (LineMarkerInfo lineMarkerInfo : lineMarkerInfos) {
if(assertMatch.match(lineMarkerInfo)) {
return;
}
}
}
fail(String.format("Fail that '%s' matches on of '%s' PsiElements", assertMatch.getClass(), elements.size()));
}
public void assertLineMarkerIsEmpty(@NotNull PsiElement psiElement) {
final List<PsiElement> elements = collectPsiElementsRecursive(psiElement);
for (LineMarkerProvider lineMarkerProvider : LineMarkerProviders.INSTANCE.allForLanguage(psiElement.getLanguage())) {
Collection<LineMarkerInfo> lineMarkerInfos = new ArrayList<LineMarkerInfo>();
lineMarkerProvider.collectSlowLineMarkers(elements, lineMarkerInfos);
if(lineMarkerInfos.size() > 0) {
fail(String.format("Fail that line marker is empty because it matches '%s'", lineMarkerProvider.getClass()));
}
}
}
@NotNull
private List<PsiElement> collectPsiElementsRecursive(@NotNull PsiElement psiElement) {
final List<PsiElement> elements = new ArrayList<PsiElement>();
elements.add(psiElement.getContainingFile());
psiElement.acceptChildren(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(PsiElement element) {
elements.add(element);
super.visitElement(element);
}
});
return elements;
}
public static class IndexValue {
public interface Assert<T> {
boolean match(@NotNull T value);
}
}
public static class LineMarker {
public interface Assert {
boolean match(@NotNull LineMarkerInfo markerInfo);
}
public static class ToolTipEqualsAssert implements Assert {
@NotNull
private final String toolTip;
public ToolTipEqualsAssert(@NotNull String toolTip) {
this.toolTip = toolTip;
}
@Override
public boolean match(@NotNull LineMarkerInfo markerInfo) {
return markerInfo.getLineMarkerTooltip() != null && markerInfo.getLineMarkerTooltip().equals(toolTip);
}
}
public static class TargetAcceptsPattern implements Assert {
@NotNull
private final String toolTip;
@NotNull
private final ElementPattern<? extends PsiElement> pattern;
public TargetAcceptsPattern(@NotNull String toolTip, @NotNull ElementPattern<? extends PsiElement> pattern) {
this.toolTip = toolTip;
this.pattern = pattern;
}
@Override
public boolean match(@NotNull LineMarkerInfo markerInfo) {
if(markerInfo.getLineMarkerTooltip() == null || !markerInfo.getLineMarkerTooltip().equals(toolTip)) {
return false;
}
if(!(markerInfo instanceof RelatedItemLineMarkerInfo)) {
return false;
}
for (Object o : ((RelatedItemLineMarkerInfo) markerInfo).createGotoRelatedItems()) {
if(o instanceof GotoRelatedItem && this.pattern.accepts(((GotoRelatedItem) o).getElement())) {
return true;
}
}
return false;
}
}
}
public void assertCompletionResultEquals(@NotNull FileType fileType, @NotNull String contents, @NotNull String result, @NotNull LookupElementInsert.Assert assertion) {
myFixture.configureByText(fileType, contents);
UIUtil.invokeAndWaitIfNeeded(new MyLookupElementConditionalInsertRunnable(assertion));
myFixture.checkResult(result);
}
public static class LookupElementInsert {
public interface Assert {
boolean match(@NotNull LookupElement lookupElement);
}
}
private class MyLookupElementConditionalInsertRunnable implements Runnable {
@NotNull
private final LookupElementInsert.Assert insert;
public MyLookupElementConditionalInsertRunnable(@NotNull LookupElementInsert.Assert insert) {
this.insert = insert;
}
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(CompletionType.BASIC) {
@Override
protected void completionFinished(final CompletionProgressIndicator indicator, boolean hasModifiers) {
// find our lookup element
final LookupElement lookupElement = ContainerUtil.find(indicator.getLookup().getItems(), new Condition<LookupElement>() {
@Override
public boolean value(LookupElement lookupElement) {
return insert.match(lookupElement);
}
});
if(lookupElement == null) {
fail("No matching lookup element found");
}
// overwrite behavior and force completion + insertHandler
CommandProcessor.getInstance().executeCommand(indicator.getProject(), new Runnable() {
@Override
public void run() {
indicator.setMergeCommand();
indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, lookupElement);
}
}, "Autocompletion", null);
}
};
Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(getEditor(), getFile());
handler.invokeCompletion(getProject(), editor);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
}
}, null, null);
}
}
}
|
package org.formulachess.engine.tests;
import static org.formulachess.engine.Turn.WHITE_TURN;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.formulachess.engine.ChessEngine;
import org.formulachess.engine.MateNode;
import org.formulachess.engine.MateSearch;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestMateSearch extends TestCase {
private static final Logger MyLogger = Logger.getLogger(TestMateSearch.class.getCanonicalName());
static int counter = 1;
private static final boolean DEBUG = true;
public static final String LINE_SEPARATOR = System.getProperty("line.separator");//$NON-NLS-1$
public static final String NEW_PGN_HEADER = "[Site \"?\"]\r\n" + //$NON-NLS-1$
"[Date \"????.??.??\"]\n" + //$NON-NLS-1$
"[Round \"?\"]\n" + //$NON-NLS-1$
"[White \"?\"]\n" + //$NON-NLS-1$
"[Black \"?\"]"; //$NON-NLS-1$
static String display(int i) {
if (i < 10) {
return "00" + i; //$NON-NLS-1$
}
if (i < 100) {
return "0" + i; //$NON-NLS-1$
}
return Integer.toString(i);
}
public static Test suite() {
return new TestSuite(TestMateSearch.class);
}
public TestMateSearch(String name) {
super(name);
}
public void checkMate(String testName, String fenNotation, int maxDepth) {
ChessEngine model = new ChessEngine(Locale.getDefault(), fenNotation);
long time = System.currentTimeMillis();
MateNode root = MateNode.newRoot(model.getTurn());
assertTrue("No mate found", MateSearch.searchMate(model, 1, maxDepth, root)); //$NON-NLS-1$
time = System.currentTimeMillis() - time;
StringBuilder buffer = new StringBuilder();
if (DEBUG) {
buffer.append("spent ").append(time).append(LINE_SEPARATOR); //$NON-NLS-1$
buffer.append(root).append(LINE_SEPARATOR);
}
buffer.append("[Event \"") //$NON-NLS-1$
.append(testName).append("\"]") //$NON-NLS-1$
.append(LINE_SEPARATOR).append(NEW_PGN_HEADER).append(LINE_SEPARATOR).append("[Result "); //$NON-NLS-1$
if (model.getTurn() == WHITE_TURN) {
buffer.append("\"1-0\"]").append(LINE_SEPARATOR); //$NON-NLS-1$
} else {
buffer.append("\"0-1\"]").append(LINE_SEPARATOR); //$NON-NLS-1$
}
buffer.append("[SetUp \"1\"]").append(LINE_SEPARATOR); //$NON-NLS-1$
buffer.append("[FEN \"") //$NON-NLS-1$
.append(fenNotation).append("\"]") //$NON-NLS-1$
.append(LINE_SEPARATOR).append(LINE_SEPARATOR).append(root.generatePGN()).append(LINE_SEPARATOR);
if (model.getTurn() == WHITE_TURN) {
buffer.append("1-0").append(LINE_SEPARATOR); //$NON-NLS-1$
} else {
buffer.append("0-1").append(LINE_SEPARATOR); //$NON-NLS-1$
}
if (DEBUG) {
MyLogger.log(Level.INFO, () -> String.valueOf(buffer));
}
try (PrintWriter writer = new PrintWriter(new FileWriter("solutions2.pgn", true))) { //$NON-NLS-1$
writer.println(String.valueOf(buffer));
writer.flush();
} catch (IOException e) {
MyLogger.log(Level.SEVERE, e, () -> "Could not save mate"); //$NON-NLS-1$
}
}
public void test001() {
checkMate("Position001", "3nkr2/3Rb1pp/p1B1ppn1/1p4P1/7P/6Q1/PPPNq3/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test002() {
checkMate("Position002", "8/5RRp/4k3/1p1Np3/1P2p3/3nP2P/5P1K/1q6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test003() {
checkMate("Position003", "8/8/6pk/3Q4/5K2/8/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test004() {
checkMate("Position004", "3k4/1P6/1KB3r1/2NN1p2/8/8/7b/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test005() {
checkMate("Position005", "r2qr2k/pbpp2pp/1p5N/3Q2b1/2P1P3/P7/1PP2PPP/R4RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test006() {
checkMate("Position006", "r1bq2k1/ppp2r1p/2np1pNQ/2bNpp2/2B1P3/3P4/PPP2PPP/R3K2R w KQ - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test007() {
checkMate("Position007", "r1bk3r/1pp2ppp/pb1p1n2/n2P4/B3P1q1/2Q2N2/PB3PPP/RN3RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test008() {
checkMate("Position008", "r2q1k1r/ppp1n1Np/1bnpB2B/8/1P1pb1P1/2P4P/P4P2/RN1Q1RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test009() {
checkMate("Position009", "r1b2rk1/ppp2p1p/1b1p1B2/5q1Q/2Bp4/2P5/PP3PPP/R3R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test010() {
checkMate("Position010", "1rqk3r/p1p2ppp/2Q1b3/3pN3/3P4/B7/P4PPP/b3R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test011() {
checkMate("Position011", "r2k1b1Q/pppn3p/3p4/1B5n/5pb1/5N2/PPPP1qPP/RNBKR3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test012() {
checkMate("Position012", "r4r2/pQ3ppp/2np4/2bk4/5P2/6P1/PPP5/R1B1KB1q w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test013() {
checkMate("Position013", "rnbqr2k/ppppn1p1/1b5p/6NQ/2BPPB2/8/PPP3PP/RN3K1R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test014() {
checkMate("Position014", "r1bk3b/1pppq3/2n3n1/1p2P1BQ/3P4/8/PPP3P1/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test015() {
checkMate("Position015", "r1bk2nr/p2p1pNp/n2B4/1p1NP2P/6P1/3P1Q2/P1P1K3/q5b1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test016() {
checkMate("Position016", "rnb2k1r/ppp1qBpp/8/4N2Q/8/2n3b1/PPPP2K1/R1B2R2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test017() {
checkMate("Position017", "r1b1kbnr/pp2qp2/1np4p/4P3/2B2BpN/2NQ1pP1/PPP4P/2KR3R w qk - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test018() {
checkMate("Position018", "rnbk3r/ppppb2p/3N1n2/7Q/4P3/2N5/PPPP3P/R1B1KB1q w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test019() {
checkMate("Position019", "r1b2Qnr/p1pk3p/1pnp4/6q1/2BPP3/8/PPP3PP/RN3RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test020() {
checkMate("Position020", "r4b1r/ppp1qb2/2np3p/5R2/3PP2k/4B1NP/PPP3K1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test021() {
checkMate("Position021", "r1b3nr/ppqk1Bb1/2pp4/4P1B1/3n4/3P4/PPP2QPP/R4RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test022() {
checkMate("Position022", "r2k2nr/pp1b1Q1p/2n4b/3N4/3q4/3P4/PPP3PP/4RR1K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test023() {
checkMate("Position023", "rn5r/pp1b2b1/1q1p3p/3nk1p1/314/3Q2P1/PPP1NR2/4R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test024() {
checkMate("Position024", "r2q1k1r/ppp1bB1p/2np4/6N1/3PP1bP/8/PPP5/RNB2RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test025() {
checkMate("Position025", "r1b1qb1r/ppp3k1/2np3p/4P2n/2BP2pB/3Q4/PPP3P1/RN3RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test026() {
checkMate("Position026", "rnb2k1r/ppp1bppp/8/1B4B1/7P/2P1R3/Pq4P1/RN1QK3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test027() {
checkMate("Position027", "r2qk2r/pb4pp/1n2Pb2/2B2Q2/p1p5/2P5/2B2PPP/RN2R1K1 w kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test028() {
checkMate("Position028", "rn3r1k/ppq3pp/2pb1p2/8/3PR2N/1Q6/PPP2PPP/R1B3K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test029() {
checkMate("Position029", "r2k1b1r/pp3ppp/8/1BBp1nq1/8/6P1/PP3P1P/2R1R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test030() {
checkMate("Position030", "r1bq3r/pp1nk2p/n1pNpp2/3pP1p1/3P1N1Q/3B4/PPP2PPP/R3K2R w KQ - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test031() {
checkMate("Position031", "r1bk1bnr/3npppp/pp6/B2N4/2pN4/8/PP2PPPP/R3KB1R w KQ - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test032() {
checkMate("Position032", "2n1r2k/pp5p/6pB/5bN1/2Qb4/1B5P/Pq3PP1/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test033() {
checkMate("Position033", "2kr1b1r/pp2pppp/5nn1/1N6/q1p2B2/5P2/PP1Q1PPP/1KR1R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test034() {
checkMate("Position034", "1n1qbr1k/r4pp1/p1p1pNPp/1p2P2Q/P1p5/4P3/1Pn1KP1P/R1B2BR1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test035() {
checkMate("Position035", "r1b1r1k1/p4Rpp/1ppq4/4N3/3np3/1QN5/PP4PP/3R2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test036() {
checkMate("Position036", "r1bqrk2/pp3ppB/2pn3p/3pN2Q/3P1P2/2N5/PP4PP/R4RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test037() {
checkMate("Position037", "rnb1k2r/p1p2N2/4p2p/bp1qP2Q/2pP3B/2n5/PP3PPP/R3KB1R w KQkq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test038() {
checkMate("Position038", "r1b1r3/ppp4R/3n1kp1/4qNNn/3pP3/P7/BP3PP1/R1Q1K3 w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test039() {
checkMate("Position039", "2r1r2k/1q4pp/1p3p2/p7/P2R1N2/1Q2P1P1/5P1P/3n2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test040() {
checkMate("Position040", "6rk/6pp/5p2/p7/P2Q1N2/4P1P1/2r2n1P/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test041() {
checkMate("Position041", "4k1r1/ppp4p/8/4p3/4P3/2N4n/PPP3rP/3R1R1K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test042() {
checkMate("Position042", "r3r1k1/ppp2ppp/5n2/7q/8/2N3Qb/PPP2P1P/R1BR2K1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test043() {
checkMate("Position043", "r2k1b1r/ppp2pp1/7p/3Pp3/2B1Nn1q/3P1b2/PPPQ1PPP/R1B2RK1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test044() {
checkMate("Position044", "r1b1r1k1/pp3pp1/7p/2Pp4/4n3/1P3Q1P/P1PN1q2/R1BK1R2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test045() {
checkMate("Position045", "r1b1k2r/p4pp1/2p4p/n7/3P2n1/2N3q1/PPPKB1PN/R1BQ3R b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test046() {
checkMate("Position046", "r1b1k2r/pppp1ppp/2n2q2/2b1P3/4P3/2P3P1/PP1PN1Bn/RNBQKR2 b kqQ - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test047() {
checkMate("Position047", "r4r2/ppp1k1pp/8/4p2n/4P3/1B1P1R1P/PPPBK3/R2Q2q1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test048() {
checkMate("Position048", "r2q3r/ppp2k1p/3p2p1/2b1P2n/3nP3/2NP3P/PPP3P1/R1BQ1RK1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test049() {
checkMate("Position049", "rnb2rk1/ppp2ppp/1b6/8/2BPn3/2PK4/PP3qPP/R1B2R2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test050() {
checkMate("Position050", "rn2k1nr/p4ppp/2p5/2b5/B3pPb1/2Pq4/PP1PN1PP/RNBQRK2 b qk - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test051() {
checkMate("Position051", "r1b5/pppp1B2/2n4k/8/4Pp1p/1P6/PBPP1KP1/7R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test052() {
checkMate("Position052", "2k2b1r/ppp2p2/1n1p4/5Pp1/2PP1pQ1/1P4p1/P5P1/RNr2BK1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test053() {
checkMate("Position053", "rn4k1/pppb1ppp/8/3P4/2BP2n1/2N1r3/PP1BNqP1/R2QR2K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test054() {
checkMate("Position054", "2kr4/ppp2p1p/6r1/n2nPb2/3N4/P1P1P2P/2PQ1qP1/R1BK1B1R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test055() {
checkMate("Position055", "7Q/b1qk1ppp/4p3/3pPb2/1n2P3/8/PP3PPP/3K1B1R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test056() {
checkMate("Position056", "r6r/pppk1ppp/8/2b2b2/2P5/2N2N2/PPn1KnPP/1RB2B1R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test057() {
checkMate("Position057", "2kr2nQ/pppb1p1p/8/4P3/1bPp4/3B3q/PPK1N2P/RNB4R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test058() {
checkMate("Position058", "r1bq2k1/pp4pp/2p1p2r/3p1pN1/2PP1Pn1/2N1P1Q1/PP3PBP/R5RK b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test059() {
checkMate("Position059", "r3k2r/ppp2p2/5n1p/1b6/1b1PqP2/6B1/PP3KPP/3Q1BN1 b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test060() {
checkMate("Position060", "r1bqk2r/bppp1ppp/8/PB2N3/3n4/B7/2PPQnPP/RN2K2R w kqKQ - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test061() {
checkMate("Position061", "r4rk1/ppp1qpp1/1bnp1P1p/6NQ/2BPP1b1/4n3/PP4PP/RN3RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test062() {
checkMate("Position062", "r3qk1r/ppp1n1pp/3pQb2/8/4P3/1BpP4/PPP3PP/2B1K2R w K - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test063() {
checkMate("Position063", "r1b1qr2/ppp2p1k/2np2pB/2b1pP1Q/2B1P3/2NP4/PPP3P1/R4K1R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test064() {
checkMate("Position064", "r2qr3/pb1nb1pp/1p2Qnk1/2p2p2/2PP1B2/3B1N2/PP3PPP/R4RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test065() {
checkMate("Position065", "rn1qrn2/pppb1Rpp/2k1P3/4P3/2BP4/2N5/PP4PP/R2Q2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test066() {
checkMate("Position066", "3qr1k1/pbr1bp1p/1pn1p1pB/8/2BP1QN1/2P3P1/P4P1P/2R1R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test067() {
checkMate("Position067", "r6r/pp1R1R2/1k5p/1Bp5/4P3/2N5/PP6/2Kb2Bq w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test068() {
checkMate("Position068", "r3kb1r/pQpbqppp/8/1B6/4n3/1N3n2/PPP2PPP/RNB2K1R b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test069() {
checkMate("Position069", "2k4N/ppp3pp/8/3P4/6n1/3p3P/PP1P1qP1/RNBKR3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test070() {
checkMate("Position070", "1k1r1b1r/p1p2ppp/B7/1P1bp3/Q2P1n1q/6N1/P2P1PPP/RNB2RK1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test071() {
checkMate("Position071", "r2q2k1/ppp2ppp/8/2b2n2/N4Pn1/1P3Q1P/P1P3P1/R1B4K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test072() {
checkMate("Position072", "5r1k/ppp3pb/5q2/7Q/3n1P1b/2P4b/PP1N3P/R5KR b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test073() {
checkMate("Position073", "r1b1k2r/ppp4p/2n5/2b1P1pq/1P3p2/2P2N2/P3N1PP/R1B1QK1R b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test074() {
checkMate("Position074", "rnb1k2r/ppp2p1p/6n1/3B2pq/3PPb2/5NpP/PPP1N1K1/R1BQ3R b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test075() {
checkMate("Position075", "5k1r/pp1r1p1p/1q4p1/1Q3N2/1b6/8/PP3PPP/R3R2K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test076() {
checkMate("Position076", "r2q1r2/pb3p2/1p1bRNpk/2p1N3/2PP4/1P1Q4/P1B2PPP/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test077() {
checkMate("Position077", "3rk2r/pp1b3p/1q2p1p1/1B5Q/8/B3n3/P5PP/5R1K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test078() {
checkMate("Position078", "6q1/p2Rr3/k2N4/b6b/1P4Q1/2n5/r5BK/R5B1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test079() {
checkMate("Position079", "8/8/8/8/2N1p2Q/5k2/8/5K2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test080() {
checkMate("Position080", "8/8/8/3K4/8/4kp1R/7Q/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test081() {
checkMate("Position081", "4R3/2q2p1k/b2p3p/p1pP1p2/r1P5/2Q2N1P/5PP1/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test082() {
checkMate("Position082", "r2qk2r/1pp1n1pp/p1npQp2/3Np3/2B1P3/3PP3/PPP3PP/R4RK1 w kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test083() {
checkMate("Position083", "r1bq1rk1/ppp2pp1/2n5/2bnp1N1/2B1P3/2NP4/PPP2PP1/R2QK2R w KQ - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test084() {
checkMate("Position084", "r1bqk2r/ppppn1np/5pN1/b6Q/2BP4/2P5/P4PPP/RN2R1K1 w kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test085() {
checkMate("Position085", "r1bk2nr/ppp2ppp/3p4/bQ3q2/3p4/B1P5/P3BPPP/RN1KR3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test086() {
checkMate("Position086", "r1b3nr/pppk2qp/1bnp4/4p1BQ/2BPP3/2P5/PP3PPP/RN3RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test087() {
checkMate("Position087", "r1bq2kr/pppp2pp/2n5/b5N1/3P4/B1P5/P4PPP/R2QR1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test088() {
checkMate("Position088", "r1b3kr/pppp1p1p/5n1B/3PR3/4n3/2P2N2/P4PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test089() {
checkMate("Position089", "r2q1rk1/p1pb2p1/3pR3/1p1n1p1Q/7R/8/PP2BPPP/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test090() {
checkMate("Position090", "r1b1qrk1/pppp1p1p/5B2/8/2BQPp2/8/PPP3PP/RN4K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test091() {
checkMate("Position091", "r1bq1r2/pp1kn2p/2pN2p1/3BQ3/3p4/8/PPP2PPP/R3R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test092() {
checkMate("Position092", "r2q2kr/ppp2p1p/1b3p1B/4N3/2ppN3/8/PPP1bPPP/R3R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test093() {
checkMate("Position093", "r5kr/pppN1pp1/1bn1R3/1q1N2Bp/3p2Q1/8/PPP2PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test094() {
checkMate("Position094", "r1bq1k2/ppp1bp1r/2n2Npp/8/3p1Q2/8/PPP2PPP/R1B1R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test095() {
checkMate("Position095", "r3r3/ppp3pp/2n5/7k/3p3q/7Q/PPP2PPP/RNB3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test096() {
checkMate("Position096", "rnbqkbnr/pppp4/6Pp/7Q/4Pp2/8/PPPP2PP/RNB1KBNR w KQkq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test097() {
checkMate("Position097", "r1k1q1r1/1pp2RQp/p2b4/3Np1B1/2B1P3/3P3P/PP4P1/n2K4 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test098() {
checkMate("Position098", "r1bq3r/pppk1B1p/2np2pQ/2b3N1/4PB2/2NP4/PPP3PP/R3K2n w Q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test099() {
checkMate("Position099", "r4r2/ppp2qpk/1b1p4/3NnP2/1PB1PR2/8/P6P/R6K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test100() {
checkMate("Position100", "r1k3nb/ppP2p2/2n1b3/3N4/2BPQB1q/8/PPP3P1/R4K2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test101() {
checkMate("Position101", "rnb1qk1r/ppp1n1p1/3P1b1p/7Q/2BP4/8/PPP4p/RNB2R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test102() {
checkMate("Position102", "r7/pp2bR1p/2n1b2k/3p2r1/8/2P3Q1/PP4P1/5RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test103() {
checkMate("Position103", "r1b1k1nr/ppppbp1p/n7/3NN3/3PP2Q/8/PPP4P/R1B1KB1q w Qqk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test104() {
checkMate("Position104", "r2q3r/ppp1n3/3pBk2/8/4P1Q1/2NP2P1/P1P5/R3K3 w Q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test105() {
checkMate("Position105", "r2q4/ppp5/2npBk2/8/4P1Q1/2NP2P1/P1P2K2/r7 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test106() {
checkMate("Position106", "r2q1r2/p2n1p2/1pb2k2/3p3Q/1b6/6R1/2PP1PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test107() {
checkMate("Position107", "rnbq1b1r/pp4kp/5np1/4p2Q/2BN1R2/4B3/PPPN2PP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test108() {
checkMate("Position108", "r3r2k/pp1b1p1p/2p2Pp1/q3P1Q1/4pR2/B1P5/P1P3PP/R6K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test109() {
checkMate("Position109", "r1b2rk1/1p3p1p/pq2p1p1/4B1RQ/4B3/8/PPP2bPP/R6K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test110() {
checkMate("Position110", "r1bq1r2/pp2n1p1/4p1k1/3pPpN1/1b1n2QP/2N5/PP3PP1/R1B1K2R w QK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test111() {
checkMate("Position111", "2rk2nr/pp3ppp/4p1q1/2Bp4/B5b1/2R5/PP3PPP/3QR1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test112() {
checkMate("Position112", "r1b1k1r1/pp1nb1pp/1qn1p3/3pp3/3N1P2/2PB1N2/PPQ3PP/R1B1K2R w QKq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test113() {
checkMate("Position113", "r1bqrk2/p2n1pp1/1pn1p3/2ppP1PQ/3P1N2/2P5/PP3PP1/R1B1K2R w QK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test114() {
checkMate("Position114", "rnb2rk1/pppqnp1p/3bpB2/8/3P4/3B4/PPP2PPP/R2QK1NR w QK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test115() {
checkMate("Position115", "r1b1r1k1/ppq2p1p/2pbpBp1/3n4/3PR2Q/2PB1N2/PP3PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test116() {
checkMate("Position116", "r2r1k2/p2nqp2/2b1p2P/4B3/2p5/3B4/PPP2P1P/2KR2R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test117() {
checkMate("Position117", "r1bqkb1r/ppp1n3/3p1nNp/4pp1Q/2B1P3/3P4/PPP2PPP/R1B2RK1 w qk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test118() {
checkMate("Position118", "r1b1knr1/pp2bp1p/1q6/5p2/4N3/8/PPPQBPPP/2KRR3 w q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test119() {
checkMate("Position119", "2rr2k1/p1pnqp2/bp2pb2/6N1/3P2P1/2P2N2/PPQ2P2/1K1R3R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test120() {
checkMate("Position120", "r1b5/pp3p1R/4p1p1/2np2N1/5Pk1/2N3P1/PqP5/R3KB2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test121() {
checkMate("Position121", "r1bR2nr/ppp2kpp/2n1p3/qB3pB1/1b2p1Q1/2N2N2/PPP2PPP/2K4R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test122() {
checkMate("Position122", "r2qr1k1/1p1bnpp1/p3p3/n2pP1NQ/P1pP4/2P5/2P2PPP/R1B1K2R w QK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test123() {
checkMate("Position123", "rnbq1knr/ppb4p/3NpPp1/3p4/1P1p1Q2/8/P1PB1PPP/R3KBNR w QK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test124() {
checkMate("Position124", "3r1b1r/pp1kpppp/5nn1/1N1B4/5q2/5P2/PP1Q1PPP/1KR1R3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test125() {
checkMate("Position125", "rn1q1r2/pb2pp2/1p6/3pN1kn/3P4/2NBPQ2/PP4P1/R3K3 w Q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test126() {
checkMate("Position126", "rn1q1b1r/pp2kppp/3np3/1B2NQ2/P2p4/2N5/1P3PPP/R1B1K2R w KQ - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test127() {
checkMate("Position127", "r1b3qr/pp1nb1pp/2p1Nn2/7k/3P4/2NQB3/PP3PPP/R3K2R w QK - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test128() {
checkMate("Position128", "r2n4/pp1R1Pp1/5kr1/6p1/PbB1R1P1/2p2P2/1P5P/2K5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test129() {
checkMate("Position129", "r4rk1/pbq1bp1p/2p1pQp1/4N3/1nP5/4P3/PB3PPP/RB3RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test130() {
checkMate("Position130", "r4rk1/pp2qp2/2nR4/3p2Pp/1Pp5/P3P3/1BQ2PP1/2K2B2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test131() {
checkMate("Position131", "r1bk1r2/pp2R1p1/3p3p/2p3Q1/3N4/8/PpP2PPP/6K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test132() {
checkMate("Position132", "r1b2rk1/pp1n1ppp/4p3/q2N2b1/1p1P3P/4PN2/P1Q2PP1/R3KB1R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test133() {
checkMate("Position133", "r2qkbQ1/pb1n2p1/2p2r2/5N1p/Pp1P3N/4P3/1P3PPP/2R2RK1 w q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test134() {
checkMate("Position134", "r1b1r3/1pqn2pk/p1p2nNp/4P3/2B5/P3P2P/1PQ2PP1/2R2RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test135() {
checkMate("Position135", "r2q1rk1/pp1nbpn1/2p5/3p2p1/3P2b1/2NBP1B1/PPQK1P2/6RR w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test136() {
checkMate("Position136", "r2q2k1/pbp1rpb1/1p6/n7/3P4/2N1P3/PPQ2P2/1BKR3R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test137() {
checkMate("Position137", "r1br2k1/1p3pp1/1q2p2R/p3B3/3p4/8/PP1QN1PP/1B4K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test138() {
checkMate("Position138", "6r1/4r3/b2N3k/1q4pp/4Q3/8/7N/BB2K3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test139() {
checkMate("Position139", "7Q/8/8/5p1p/7k/4b1RP/6PK/2qr4 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test140() {
checkMate("Position140", "6rk/3R1Qpp/1p3p2/p1r5/P4N2/2n1PqP1/5P1P/3R2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test141() {
checkMate("Position141", "r3k2r/ppp2pp1/2np4/2B1p2n/2B1P1Nq/3P4/PPP2PP1/RN1Q1RK1 b qk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test142() {
checkMate("Position142", "r3k3/ppp3Qp/3qp1p1/b4r2/3n4/4B3/P2N1PPP/R4RK1 b q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test143() {
checkMate("Position143", "r1b2rk1/1pp3pp/1p1p4/3Ppq1n/2B3P1/2P4P/PP1N1P1K/R2Q1RN1 b q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test144() {
checkMate("Position144", "r4rk1/ppp3pp/4b3/6K1/8/8/PB3bPP/RN1Q3R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test145() {
checkMate("Position145", "r5k1/ppp3pp/2n5/3p2q1/8/2P2P1b/PP1P1P1P/RNB3QK b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test146() {
checkMate("Position146", "r2Bk3/ppp2pp1/2np4/4p3/2B1P1n1/3P4/PPPNKpP1/RN1r4 b q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test147() {
checkMate("Position147", "r2k3r/ppp2Bp1/8/6p1/4n3/3q2P1/PP1Nb1KP/R1Q5 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test148() {
checkMate("Position148", "r1b1k2r/ppp5/6pp/2bpp1N1/3n2P1/3P4/PPP3PP/RNB2RK1 b kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test149() {
checkMate("Position149", "2k5/ppp3pp/8/2bPp3/1n1nP1P1/2K5/PPPN1qPP/R1BQ3R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test150() {
checkMate("Position150", "r1b1k2N/ppp3pp/8/3pp3/3n1q2/N2K4/PPPP3P/R1B1Q2R b q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test151() {
checkMate("Position151", "r1bk3N/ppp2Bpp/8/3p4/4n3/4qQ2/PPn3KP/RN5R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test152() {
checkMate("Position152", "7N/ppp1k2p/8/3Pp3/3n2pb/2NPB2b/PPP2rPP/R5KR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test153() {
checkMate("Position153", "2k2r1N/ppp3pp/8/3Pp3/3nn1q1/N3Q1P1/PPPP3P/R1B1KR2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test154() {
checkMate("Position154", "r3k3/ppp3p1/8/3Pp2p/2B3n1/2NP1nPK/PPPQbq1P/R1B4R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test155() {
checkMate("Position155", "r4r2/pp2k1pp/1bpp4/4p3/BP1PPnbq/2P5/PB3PPP/RN2QRK1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test156() {
checkMate("Position156", "r4k1N/pp4pp/3p4/6n1/8/6qP/PP1P1Qb1/RNB2BKR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test157() {
checkMate("Position157", "1r3k1r/pPp3p1/3q1n2/2b3p1/4p1b1/1B1P2P1/PPPQ1P1P/RNB2RK1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test158() {
checkMate("Position158", "r5k1/pp3pp1/2b4p/8/3prP2/8/PPPQBqPP/R3R2K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test159() {
checkMate("Position159", "r2qk2r/pp3ppp/n7/3NPb2/2KP1p1N/6nP/PP1B2P1/R2Q3R b kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test160() {
checkMate("Position160", "rnb1k2r/pppp1ppp/8/8/2B1P2q/3P1P2/PPP1Q2n/RNB3KR b kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test161() {
checkMate("Position161", "rnb2r1k/p1B1Q1pp/8/1p4N1/3q4/3P4/PPP3PP/RN3n1K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test162() {
checkMate("Position162", "rn2k1nN/ppp4p/8/3B4/3bP2q/5ppR/P1PP2P1/2Q1RK2 b q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test163() {
checkMate("Position163", "r3k2r/pp3p1p/2nq4/P3nbp1/1bP5/1P2N1PP/3BP3/RN1QKB1R b QKqk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test164() {
checkMate("Position164", "2kr3r/ppp2ppp/8/2Q2b2/2P1q3/PP2PnP1/1B1pKP1P/R4B1R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test165() {
checkMate("Position165", "2kr1b2/pp3p2/2n5/4PnP1/2P4q/1Q1p4/PP1BbPBN/R3R1K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test166() {
checkMate("Position166", "2kr1b1r/pp3ppp/2p5/2n5/P1N2Bb1/2N1PnPP/1P2KP2/R4B1R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test167() {
checkMate("Position167", "r2qk2r/1pp2pp1/p3p3/6Pn/1B1P2PK/1Q2P2P/PP6/R6R b kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test168() {
checkMate("Position168", "r1bq2k1/pp4pp/2p1p2r/3p4/2PPBPp1/2N1P3/PPQ2P1P/R5RK b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test169() {
checkMate("Position169", "r4r1k/1bQ2ppp/pN5q/8/Pp2nP2/2N1B1b1/1PB3P1/R1R3K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test170() {
checkMate("Position170", "r1b2b1r/1pBq2pp/8/p1kN4/4P3/P2p1Q2/BPpK1PPP/2R5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test171() {
checkMate("Position171", "r1q1k1r1/1pp2R2/3p4/p1nPp1p1/2P1P2P/7b/PPBQN2K/5R2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test172() {
checkMate("Position172", "Q7/2pk1p1p/p2pb3/2p5/4n3/4K3/PPq2PPP/RN5R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test173() {
checkMate("Position173", "5r1r/pppkq3/3p1n2/4p1N1/3nP1P1/1BNPK3/PPP3P1/R2Q4 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test174() {
checkMate("Position174", "r3kb1r/p1Q2ppp/4p3/3p1b2/1nPP2n1/5N2/PP2PPPP/R1B1KB1R b kK - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test175() {
checkMate("Position175", "r5k1/1bq3pp/p3p3/1pb5/4B1n1/P4rP1/1P2QP1P/R1B2RK1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test176() {
checkMate("Position176", "N1b4r/pp3ppp/3Rn3/3Rp3/k1p5/2P5/PP3PPP/2K5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test177() {
checkMate("Position177", "r2k3N/pp3Bpp/3p1q2/2n1pb2/1QKb4/2NP4/PP4PP/R1B4R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test178() {
checkMate("Position178", "r2qk2r/p1Q1bppp/2b5/1N6/4nPK1/8/PP4PP/R1B1nBNR b kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test179() {
checkMate("Position179", "1k5r/ppp1q1pp/5n2/r1b2N2/4P3/BPn2N1P/2PP2P1/K1R1QB1R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test180() {
checkMate("Position180", "2rq1bk1/pb3Np1/1pn5/2nN4/8/P2Q4/BP3PPP/4R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test181() {
checkMate("Position181", "r2b2k1/ppn1r3/1qp1pp1Q/4N3/8/8/PPB2PPP/R4R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test182() {
checkMate("Position182", "r1bk2nr/ppp2ppp/1b6/n5N1/3P4/2NB3P/P4PP1/R1BqR1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test183() {
checkMate("Position183", "r1bq2kr/pppp2pp/2n5/2b1P1N1/3p4/2P5/PP3nPP/RNBQK2R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test184() {
checkMate("Position184", "r1nqk3/ppppb3/5p1r/n3N2p/2B5/2PQ4/P4PPP/R3R1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test185() {
checkMate("Position185", "r2q2kr/p1p2p1p/1p3p1B/2b1N3/2ppN3/2P5/PP3PPP/R2bR1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test186() {
checkMate("Position186", "r1b1k2N/ppp3pp/2np4/4p3/2B4q/8/PPPP3P/RNB2QKn w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test187() {
checkMate("Position187", "2k1rb1r/QpB2ppp/2b1qn2/3N4/4p3/8/PPP3PP/2KR1B1R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test188() {
checkMate("Position188", "r2qnrk1/pbppbp1p/1p4pQ/4B3/3P4/1BN5/PPP3PP/R4RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test189() {
checkMate("Position189", "1rb3nr/1p1p3p/p2k3b/3Np3/2B1P3/3P1R2/PPP3PP/5RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test190() {
checkMate("Position190", "r1b2rkq/pppp1pbp/6n1/3N4/2B2Q2/1P6/P1PP2PP/B3RR1K w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test191() {
checkMate("Position191", "r2q3r/ppp1b3/7p/5Q2/2nP2pk/8/PPP3P1/R5K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test192() {
checkMate("Position192", "rn3bkr/p4qpp/1pN1Qp2/1Bp5/3P4/8/PPP3PP/R4RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test193() {
checkMate("Position193", "r1b1kb1r/1p1nnppp/4p3/1N1p2BP/3N4/2P3Q1/P13PP1/R3K2R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test194() {
checkMate("Position194", "rn1q1r1k/pb2pp2/1p3n2/3pN1Q1/3P4/2NBP3/PP4P1/R3K3 w Q - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test195() {
checkMate("Position195", "r2k1r2/pp1n2Qp/3Npp2/3pPb2/1P6/4P3/1q3PPP/2R1KB1R w K - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test196() {
checkMate("Position196", "r2qrk2/1b2bppB/p7/1p1PN3/1n6/8/1B2QPPP/2RR2K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test197() {
checkMate("Position197", "r1bqr3/pp1nbkp1/2p1N2p/8/3PP3/1Q6/PP3PPP/R1B2RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test198() {
checkMate("Position198", "r2q1r2/1b3pk1/4p2R/p2n2N1/PpB3Q1/4n3/NP4PP/R5K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test199() {
checkMate("Position199", "r1b3qr/pp1nb1pp/2p1Nn2/7k/3P4/2NQB3/PP3PPP/R3K2R w QK - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test200() {
checkMate("Position200", "3nkb1r/2p1p2p/2b1P1p1/5p2/2QP3q/2P1B3/4BPPP/R5K1 w k - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test201() {
checkMate("Position201", "rnb4Q/pp1qn1p1/2p1p1k1/3pP1N1/2P2p2/2N5/PP3PPP/R3K2R w QK - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test202() {
checkMate("Position202", "1n3rk1/5ppp/4p3/1p2Nb2/1P2N3/3R4/5P1P/r2BK1R1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test203() {
checkMate("Position203", "r1b5/pPR5/5kpp/3pN2r/3Pp2q/P3P3/2Q2PPP/5RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test204() {
checkMate("Position204", "bq2rrk1/7p/2n5/4Q2B/1b1N4/2B5/5RP1/4KR2 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test205() {
checkMate("Position205", "1r3q1k/7p/2p2bp1/P3p3/2B3N1/5P2/2K3P1/3Q3R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test206() {
checkMate("Position206", "r5k1/pNp3pp/3pp2r/4p3/4P2q/3P1P2/PPP2P1P/R2QR1K1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test207() {
checkMate("Position207", "r2k3r/ppp5/2np2q1/2bNp3/4P1b1/1B6/PPPP1PPP/R1B1QRK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test208() {
checkMate("Position208", "4rk1r/pPp3p1/3q1n2/2b3p1/4p3/1B3bP1/PPPPNP1P/R1B1QRK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test209() {
checkMate("Position209", "r1b1r1k1/p4pp1/2p4p/n7/2PP4/2N2Nq1/PPQKBnP1/R1B3R1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test210() {
checkMate("Position210", "rnb1r3/ppp2kpp/8/3P1p2/1Q3P1q/5N2/PPPNB2P/R1BK3n b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test211() {
checkMate("Position211", "rnbkr3/ppp2Bpp/5b2/7q/2Q2p2/3P1N2/PPP3PP/R1B2K1R b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test212() {
checkMate("Position212", "2kr3r/ppp5/4p3/2NpP1bn/3Q1pbq/P7/1PP3PP/R1B1NRK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test213() {
checkMate("Position213", "4r3/p4pkp/q7/3Bbb2/P2P1ppP/2N3n1/1PP2KPR/R1BQ4 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test214() {
checkMate("Position214", "r3r1k1/pp3ppp/2p3b1/q2pP3/n4B2/1KP1Q1PB/P1P1RP1P/3R4 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test215() {
checkMate("Position215", "7k/1p4pp/5q2/pP1Qp3/2N1n1P1/2P1P2P/1P3r2/R5K1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test216() {
checkMate("Position216", "3rk2r/p1pqbppp/2B5/1P6/2P3b1/P5P1/2Q1nP1P/RN3R1K b k - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test217() {
checkMate("Position217", "rnbB1rk1/ppp3pp/8/3Pp3/1b2n3/3B4/PP2KPPP/R2Q2NR b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test218() {
checkMate("Position218", "r4n1k/pp3p1p/2p4r/3p2p1/3P1N1q/3BPbPP/PPQ2P1K/1R3R2 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test219() {
checkMate("Position219", "r3k1r1/pb3p1p/3bpp2/1P2n3/3N4/3B3P/1P2QPP1/R1B2RK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test220() {
checkMate("Position220", "r4nk1/pp3ppp/4r3/1N1p4/3Pp1nq/BP2P3/P3QPP1/R1R2NK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test221() {
checkMate("Position221", "r1b2rk1/pppp1Np1/7p/3qP2Q/8/8/P5PP/b1B2R1K w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test222() {
checkMate("Position222", "r3r1k1/pp3Rpp/2pp4/8/2P1P2B/5Q2/P1q3PP/5R1K w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test223() {
checkMate("Position223", "r4b1r/pppq2pp/2n1b1k1/3n4/2Bp4/5Q2/PPP2PPP/RNB1R1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test224() {
checkMate("Position224", "r1bk1r2/pp2R1p1/3p3p/2p3Q1/3N4/8/PpP2PPP/6K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test225() {
checkMate("Position225", "rq1r2k1/1bp2p1p/pp3Bp1/2p1P3/P4PQ1/3B4/6PP/5RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test226() {
checkMate("Position226", "2rqrb2/p2nk3/bp2pnQp/4B1p1/3P4/P1N5/1P3PPP/1B1RR1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test227() {
checkMate("Position227", "6br/3Np1bk/8/6P1/8/8/1Qp5/KB3r2 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test228() {
checkMate("Position228", "2k2r1N/ppp3pp/8/3Pp3/4n1q1/4QnPP/PPPP4/RNBK3R b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test229() {
checkMate("Position229", "r3k2N/ppp3pp/5n2/2qPp3/1PBn2b1/8/P1PP1KPP/RNB2Q1R b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test230() {
checkMate("Position230", "N5nr/pp1k1ppp/2pp4/2b1p3/2BnPP1q/3P1P2/PPPK3P/R1BQ3R b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test231() {
checkMate("Position231", "3rk2r/p1p1bppp/2P5/8/2P5/P4bPK/2Q1nP1P/RN3R2 b k - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test232() {
checkMate("Position232", "5rk1/pp4pp/2p1p2q/1P2P3/2P1R3/P4rPb/1B5P/2RQ2K1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test233() {
checkMate("Position233", "r2k1b1r/pq2npp1/n7/1Np1Q2p/8/3P2PB/PPPB3P/R3K2b w Q - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test234() {
checkMate("Position234", "r2k3r/pq3ppp/1p1B4/1B3p2/8/8/PP3PPP/3RR1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test235() {
checkMate("Position235", "r1bq1b1r/4p1pp/1np2nk1/1p4N1/3P3P/p1N1P3/PP3PP1/R1BQK2R w QK - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test236() {
checkMate("Position236", "1nr2b1r/1q2kppp/4p3/2p5/B1Q1P1b1/B1P2N2/P4PPP/3R2K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test237() {
checkMate("Position237", "r3k2r/ppp2Npp/2n5/3Bp3/4K1bq/8/PPPP3P/RNB1Q2R b kq - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test238() {
checkMate("Position238", "r1bq1rk1/pppp1pp1/2n3P1/2b1N3/2B1P3/2NP4/PPP3P1/R2nK2R w KQ - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test239() {
checkMate("Position239", "r6k/pp2q1pp/2ppb1P1/2bBpp2/4P3/P2P4/1PP2PP1/R2QK2R w KQ - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test240() {
checkMate("Position240", "5Q2/6pk/1p5p/8/1P1Pp3/q5P1/P4KBP/8 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test241() {
checkMate("Position241", "8/4Npk1/6p1/P7/1nnP4/5BP1/5r1P/RK2R3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test242() {
checkMate("Position242", "3r1r1k/1b3q2/1p3p1B/8/1P1p3Q/P2B4/5PP1/3R2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test243() {
checkMate("Position243", "2Q3r1/4k1q1/p7/1p1pN3/3P4/2P1N3/PP2bPPR/2K5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test244() {
checkMate("Position244", "4k2r/p3b2p/2r1Q3/2N3q1/1P3pp1/8/6PP/3R2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test245() {
checkMate("Position245", "8/8/8/N2Q4/p7/b1k2p2/2P3q1/3K4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test246() {
checkMate("Position246", "5r2/2Qn1p1k/p3p2r/1p6/4q3/PP6/2P3RR/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test247() {
checkMate("Position247", "6k1/5p2/6p1/pN6/P2bqP2/5RPp/3p3P/3Q3K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test248() {
checkMate("Position248", "4r1k1/5pp1/p2p1q2/P1bP4/2P5/1QN2PPp/1P5P/5R1K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test249() {
checkMate("Position249", "8/3p4/b2P4/1rp1pR2/1p2P2k/1N2P3/5K2/8 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test250() {
checkMate("Position250", "rk5r/p2R2pp/Bpp1Np2/8/1q6/8/8/2K5 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test251() {
checkMate("Position251", "6K1/6P1/2q1k3/8/8/8/8/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test252() {
checkMate("Position252", "r3r2k/2Q1R3/2p2p1p/3p4/p2q4/PP4R1/2P1K1PP/8 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test253() {
checkMate("Position253", "2b2k1r/1p3pp1/5N2/q3N3/8/7P/1P2Q1P1/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test254() {
checkMate("Position254", "2rr1k2/3q1p2/4p1R1/1p6/1P6/3P1QR1/6PK/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test255() {
checkMate("Position255", "2Rr3k/2R4p/4p3/q2rp3/8/7P/1PP4Q/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test256() {
checkMate("Position256", "3R2rk/7p/r4p1P/8/1p6/5P2/2P4K/4R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test257() {
checkMate("Position257", "6k1/p5p1/1p4P1/2pr4/5R1R/4P3/PP2KP2/6r1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test258() {
checkMate("Position258", "2k2bnr/Qpp2ppp/q7/8/8/2N1Bn2/PP3PPP/2KR4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test259() {
checkMate("Position259", "2r4k/1p3Bb1/6Qp/3N4/8/q1P5/5PK1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test260() {
checkMate("Position260", "4rk2/6p1/1q1p1b1p/1p6/7Q/1B6/PP5P/5R1K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test261() {
checkMate("Position261", "3r1r2/1R6/pN2q1nk/P2p2pp/1P2pp2/4P1PP/4QP1K/3R4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test262() {
checkMate("Position262", "2r2r2/p4p1k/1p2pP1p/n2pPR2/q5PN/2Pp4/2PQ3P/4R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test263() {
checkMate("Position263", "3r4/3P3p/8/5Kp1/7k/2p5/1bR3P1/3R4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test264() {
checkMate("Position264", "2r3r1/8/1p6/7p/1P1P1p1P/2nk1N1K/6R1/4R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test265() {
checkMate("Position265", "8/3R4/4kp2/r4p2/1r3P2/8/5PK1/7R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test266() {
checkMate("Position266", "4rk2/5pp1/1p6/b2R2B1/1q6/8/P3QPP1/5K2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test267() {
checkMate("Position267", "4B3/6pk/4R2p/8/8/7P/2rr2PK/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test268() {
checkMate("Position268", "R4bk1/5p1p/5rp1/8/8/4B3/1PP2P2/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test269() {
checkMate("Position269", "r1b3k1/pp1p3p/3p2pB/8/q1P5/1P6/P5PP/4R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test270() {
checkMate("Position270", "q2br1k1/1b4pp/3Bp3/p6n/1p3R2/3B1N2/PP2QPPP/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test271() {
checkMate("Position271", "8/1p3p1k/2b2Bpr/8/8/P6R/1Pq3P1/4Q2K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test272() {
checkMate("Position272", "8/p2q1r1k/2b2B1p/5P2/8/P7/R2Q4/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test273() {
checkMate("Position273", "b3q1rk/5p1p/2n4B/4N3/3P4/2P5/8/1Q2K2R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test274() {
checkMate("Position274", "6r1/5pk1/2r2p2/1p3P2/1P6/2P4R/3B4/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test275() {
checkMate("Position275", "r4Br1/p1q2p1k/1p1R2p1/3pP2b/7Q/2p5/P1P1NPPP/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test276() {
checkMate("Position276", "q5rk/4pRrp/3p2B1/2n5/2P4Q/7P/6p1/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test277() {
checkMate("Position277", "2R5/p1R3b1/1q5k/4n1p1/4B3/6P1/1P5P/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test278() {
checkMate("Position278", "br3r2/2qnb2p/p5p1/2pBk3/2Pp3P/3P1QP1/P4P2/R5K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test279() {
checkMate("Position279", "r7/2q4p/2Np1k1B/2pP1b1P/2n3R1/2P4K/8/1Q6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test280() {
checkMate("Position280", "2B5/8/8/6bp/3Q1q1k/5P2/6P1/4K3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test281() {
checkMate("Position281", "8/8/q3b1r1/4k3/1p2N3/8/P5P1/1KBQ4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test282() {
checkMate("Position282", "5kr1/6p1/q2b2B1/4n1B1/8/8/5P2/2RQ2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test283() {
checkMate("Position283", "3qk3/1p1n1p2/p3b3/8/3P4/B1PB4/4Q1P1/4K3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test284() {
checkMate("Position284", "4qk2/6p1/1pbPQn2/2p3B1/8/1B6/1P4P1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test285() {
checkMate("Position285", "q2k2r1/6p1/1p3n2/1B1b2Q1/7B/8/1P4P1/2R3K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test286() {
checkMate("Position286", "3qkb2/2pp1pp1/8/4P3/8/1B6/2P3PP/2Bn1RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test287() {
checkMate("Position287", "1r2k3/3pbRp1/b1n1p3/p5B1/7P/1P6/2B5/5R1K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test288() {
checkMate("Position288", "5rk1/1b2b2p/2q2n2/5QN1/2p5/2B5/1P4P1/1B2R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test289() {
checkMate("Position289", "3qkb2/3pp2p/6p1/8/8/2P5/1PQ2PP1/1B2K3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test290() {
checkMate("Position290", "3qkb2/3pp3/7r/7p/8/3B4/1P3PP1/R2QK3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test291() {
checkMate("Position291", "q7/1p6/3B4/6pp/7k/p6P/6P1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test292() {
checkMate("Position292", "3N4/8/6k1/8/B2B3K/8/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test293() {
checkMate("Position293", "6rk/2p4p/3b1n2/3pNpN1/3P1B2/6P1/1P3PKP/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test294() {
checkMate("Position294", "1q3bk1/5p1r/7P/8/n5N1/2Q5/1B6/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test295() {
checkMate("Position295", "2rkr3/R7/3Bb3/2p1N1p1/8/8/1P4P1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test296() {
checkMate("Position296", "rk1n1n1r/pp2R2p/2p3p1/2N5/1PP3B1/8/P5PP/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test297() {
checkMate("Position297", "3q2kr/1p3p1p/5b1B/3N4/2P5/8/5KP1/4Q3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test298() {
checkMate("Position298", "1nk5/3b2b1/3p4/B2N1n2/2P1N1p1/6P1/6B1/4K3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test299() {
checkMate("Position299", "2r1r1k1/qp3p1p/4b1N1/8/p1n5/Q1B1PB2/P5PP/1R4K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test300() {
checkMate("Position300", "2qr1rk1/5ppb/p1n1p2p/1p3N2/4P3/2B5/PP1Q1PPP/2R1R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test301() {
checkMate("Position301", "r3r2k/p2b1Rp1/1pp2Np1/3q4/3n4/4Q3/PP4PP/3R2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test302() {
checkMate("Position302", "6rk/Q6p/4N1p1/3b4/R7/2q4P/6P1/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test303() {
checkMate("Position303", "8/5pkr/R2N4/8/8/8/8/2K5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test304() {
checkMate("Position304", "4r1k1/1p3pp1/p1b3q1/5N2/1Q2P3/2P5/PP3P2/1K5R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test305() {
checkMate("Position305", "4bkr1/6p1/1q5P/4N3/8/4R3/Q7/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test306() {
checkMate("Position306", "4kn2/r4p2/8/3N4/q6Q/8/1P6/1K1R4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test307() {
checkMate("Position307", "5nnk/RQ5p/4bb2/3qN3/3P4/8/5PP1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test308() {
checkMate("Position308", "4Q3/8/5pqp/7k/8/7K/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test309() {
checkMate("Position309", "kr1q4/1p4Q1/pP6/3n4/6p1/7P/5PB1/R5K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test310() {
checkMate("Position310", "2r5/p2b4/7R/bkqQ1p2/3p4/2P5/P1P2PP1/4K3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test311() {
checkMate("Position311", "6k1/pp2q2p/2b4Q/6N1/8/8/PP1r2PP/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test312() {
checkMate("Position312", "4rk2/4q1p1/2p5/3P4/7Q/2B5/1P6/2K5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test313() {
checkMate("Position313", "6kn/1p3q1p/2n2p1Q/2B5/6P1/3B4/P3P3/K7 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test314() {
checkMate("Position314", "b1r1r3/pk3ppp/1p1Q4/8/4q3/4B3/1KP2PPP/R2R4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test315() {
checkMate("Position315", "r3k1r1/pp1b1p1p/4p3/6pq/2P5/Q3PN1P/PB3PP1/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test316() {
checkMate("Position316", "r4rk1/1p4p1/4q3/4P3/8/3Q4/1P6/1K4RR w q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test317() {
checkMate("Position317", "8/8/2N4p/2r1p2k/3p3P/3P2K1/4N3/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test318() {
checkMate("Position318", "3r3k/pp3Qpp/2nbB3/6N1/8/8/PqP2PPP/R5K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test319() {
checkMate("Position319", "4r1nk/p5pp/1p4b1/2p3N1/2P4Q/1P6/PB2qPPP/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test320() {
checkMate("Position320", "kr1q4/nb1N4/8/8/8/6Q1/PP6/1K5R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test321() {
checkMate("Position321", "2k5/1pp2rp1/n1N5/Q2N1q2/8/8/2P3PP/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test322() {
checkMate("Position322", "2b5/5N2/3n2r1/7k/5R1p/3N1K2/1P6/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test323() {
checkMate("Position323", "6k1/1b1npr1p/p4nNQ/P4N2/4p3/1qp2P2/6P1/K2R3R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test324() {
checkMate("Position324", "4N3/1q6/6b1/2pk1n2/2N5/4P3/2Q1K3/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test325() {
checkMate("Position325", "4rr1k/pp2p2p/5b2/n3N2N/3P4/1B6/PP5P/6RK w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test326() {
checkMate("Position326", "8/R3Pr2/2nk4/8/3PK3/8/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test327() {
checkMate("Position327", "2q2k1r/5np1/1p3P2/2b5/2BQ4/8/1P4P1/4R1K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test328() {
checkMate("Position328", "7k/4qp1P/p5pQ/1p6/8/8/PPP1r3/2K4R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test329() {
checkMate("Position329", "3b4/R7/4p2k/r3P3/8/5K2/p1B4P/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test330() {
checkMate("Position330", "6R1/7p/6bk/7p/q5P1/8/1P6/2K4Q w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test331() {
checkMate("Position331", "8/8/8/R5pr/6qk/4Q3/6P1/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test332() {
checkMate("Position332", "Q7/6R1/pk1p3p/1p5r/3P1P2/P7/1PP2K2/3q4 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test333() {
checkMate("Position333", "R4rk1/2p2pp1/1b6/2qQP3/8/1B6/2P3P1/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test334() {
checkMate("Position334", "r4r2/pbR3pk/1p2pp1p/3q4/3P1Q2/4B2P/PP3PP1/5RK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test335() {
checkMate("Position335", "5rk1/b1Q2ppp/8/3B4/3q4/8/5PPP/2R3K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test336() {
checkMate("Position336", "6rk/p1n3pp/3N2b1/3rP3/1P6/3R3R/5P2/1B4K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test337() {
checkMate("Position337", "2q3rk/6p1/2p1p2p/1p1pB3/1P1P4/4P2P/2Q2PPK/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test338() {
checkMate("Position338", "8/2prp1N1/2bk4/8/2K2P2/8/8/7R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test339() {
checkMate("Position339", "8/1p4Q1/p6p/5q1k/5PR1/4r1PK/7P/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test340() {
checkMate("Position340", "6k1/pr3p1p/8/4P1B1/8/2n5/P5RP/K7 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test341() {
checkMate("Position341", "r1b1r1k1/p4Rpp/1ppq4/4N3/3np3/1Q6/PP4PP/3R2K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test342() {
checkMate("Position342", "4qrk1/1p4p1/b1p3Q1/5p1B/8/P5P1/1P3P1R/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test343() {
checkMate("Position343", "1r3rk1/2q2p1p/5RpQ/7P/8/8/1BP5/2K5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test344() {
checkMate("Position344", "2kr4/1rpbQ2p/3p4/1q1P2R1/7B/6PB/1P6/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test345() {
checkMate("Position345", "8/8/8/8/kp1Q4/1p6/1KP5/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test346() {
checkMate("Position346", "3r4/3r4/1pb3p1/2pp1p2/p3k2p/PB2P3/1PP2PPP/4RNK1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test347() {
checkMate("Position347", "2N2k2/8/1rpR2B1/1P4K1/q2p4/8/8/8 w - - 0 1 ", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test348() {
checkMate("Position348", "4rr2/8/5b1R/2PKB3/k7/8/8/4R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test349() {
checkMate("Position349", "2r5/5r1p/8/3p1p2/2P5/2PNk3/1K4PP/7R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test350() {
checkMate("Position350", "6bk/2p4p/q2p2pQ/8/8/2P1N3/6PK/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test351() {
checkMate("Position351", "1B6/2pp4/3k4/1P6/2K5/8/8/4R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test352() {
checkMate("Position352", "3r4/8/3k4/5P2/B2K4/8/8/7R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test353() {
checkMate("Position353", "k1b5/p7/BPP5/7p/5q2/8/3P2KB/7Q b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test354() {
checkMate("Position354", "8/6Bq/8/b4bKB/4k3/8/8/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test355() {
checkMate("Position355", "8/kp3p1R/2p3p1/2b3B1/2r1p3/4P3/P4PPP/K7 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test356() {
checkMate("Position356", "8/kp1b2r1/p7/5P1P/5R1K/4P1r2/PPRP4/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test357() {
checkMate("Position357", "7k/5r2/7b/1Q6/n3q1b1/N1p4n/2B1N2R/3KR3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test358() {
checkMate("Position358", "8/2p3k1/1q2b3/8/1r3pP1/3Q1K2/2P1B1R1/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test359() {
checkMate("Position359", "1r4k1/r5p1/8/3n4/8/6B1/N7/K5Q1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test360() {
checkMate("Position360", "4r1k1/b1R2ppp/pq6/1p2Q3/1P2n3/16N/1B4BP/7K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test361() {
checkMate("Position361", "R2b3k/Qpp3p1/2p4p/6BK/6PP/8/8/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test362() {
checkMate("Position362", "8/8/b7/6k1/8/1p2K1n1/8/q7 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test363() {
checkMate("Position363", "6k1/8/q3b3/1p6/1p6/1P1P4/1PK1B3/2B1Q3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test364() {
checkMate("Position364", "3r3k/4R2p/5N2/pp6/1b6/RP6/PKPp2PP/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test365() {
checkMate("Position365", "6k1/4p2p/p1N3p1/1P3r2/N1pb4/8/PP4PP/2R2n1K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test366() {
checkMate("Position366", "8/3k2p1/r5p1/1pKpB2p/3Pb2P/2P1P3/r5P1/3R2R1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test367() {
checkMate("Position367", "1b6/7k/5Bp1/7q/3p3Q/1p1P4/1P1KRP2/r7 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test368() {
checkMate("Position368", "8/8/8/4PKP1/5n2/6k1/8/q7 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test369() {
checkMate("Position369", "r2Bk3/1p3ppr/p1pQ4/1q2P3/5n2/8/P1P2PP1/3RR1K1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test370() {
checkMate("Position370", "7k/q4pp1/5p2/2n3Pb/3Qn3/3p4/BP3B2/2K4R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test371() {
checkMate("Position371", "8/8/5b2/8/1p6/2k5/2P5/KB6 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test372() {
checkMate("Position372", "q7/8/4k2b/8/2K5/1nP5/8/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test373() {
checkMate("Position373", "1k3b1R/1p6/4q3/8/Kn6/B1Q5/8/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test374() {
checkMate("Position374", "8/1kp3p1/1p4b1/3pp2p/KB6/1P3PP1/P1nrBN2/4R2R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test375() {
checkMate("Position375", "8/5p2/2R5/3K4/1N2n1k1/3B1r2/1b6/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test376() {
checkMate("Position376", "q5k1/8/8/8/8/7b/5Q1P/r4BKR b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test377() {
checkMate("Position377", "8/8/8/8/5b2/8/5Kp1/r2k2rR b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test378() {
checkMate("Position378", "1k5r/pp1b1ppp/4p3/q3P3/1n3P2/bPB2N2/2PP2PP/1KR1Q2R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test379() {
checkMate("Position379", "r3r1k1/1p3p2/p7/3P1Q2/P5np/5B2/1P3NPq/R1B2K2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test380() {
checkMate("Position380", "8/pk6/1p6/8/KQR5/PP6/8/r3q3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test381() {
checkMate("Position381", "8/8/8/5n2/2N5/3n4/4N2k/5K2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test382() {
checkMate("Position382", "6q1/n3b3/1NR2p2/1B2rp2/p2K1n1k/N1RP2rP/Q7/5b2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test383() {
checkMate("Position383", "k7/3q1p2/2p5/1b6/P2n1P2/4b1p1/4N1P1/1R1QRK2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test384() {
checkMate("Position384", "8/8/8/2P2R2/1Pp5/P7/K1k5/1Nb5 b - b3 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test385() {
checkMate("Position385", "1k5r/1p6/8/2q5/5p2/7P/6PK/2Q4R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test386() {
checkMate("Position386", "k7/pp4p1/6b1/8/q2n4/2B1N3/1PP3P1/1K2Q3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test387() {
checkMate("Position387", "k4r2/pp6/3p4/1b6/4PnPp/P7/1P2Rp1P/R2B1K2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test388() {
checkMate("Position388", "k7/1p6/p1n3q1/8/8/4B2p/1Pb1KP1P/2R1Q3 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test389() {
checkMate("Position389", "3nrq2/2k5/2p2p2/p1Np4/P2K1PP1/1Q1P4/8/1R6 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test390() {
checkMate("Position390", "1k2r3/1b6/8/8/N3R2R/7n/5r2/2B4K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test391() {
checkMate("Position391", "8/8/8/1k3p2/p4P2/K1pN4/P2b4/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test392() {
checkMate("Position392", "Q7/2N1p3/qn1bBN2/2R3n1/1pPKP3/5p2/8/1k2rb2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test393() {
checkMate("Position393", "7k/8/b3q3/8/8/4p3/2B4N/2R1K1n1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test394() {
checkMate("Position394", "6k1/2R1Q1p1/5n1p/1p1qpp2/1P1p4/3P2P1/4PP1P/r4BK1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test395() {
checkMate("Position395", "8/kp4bp/p5p1/r1p1p3/P2pP2N/1r1P4/K1Pq2PP/2R1QR2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test396() {
checkMate("Position396", "2kr4/4P1p1/p7/1p1r4/3PRKQq/3R1P2/P7/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test397() {
checkMate("Position397", "2q3k1/5p2/8/1b2Q1pp/3B4/5PP1/5PKP/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test398() {
checkMate("Position398", "1k1r4/pppq2p1/8/2B1p1N1/7p/4KP1P/PP1r4/1Q3R1R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test399() {
checkMate("Position399", "8/kr4r1/1p6/2b5/4Qn2/6Rq/5N1P/5RKN b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test400() {
checkMate("Position400", "1q5k/8/p7/8/3r3p/P3PB2/P1b5/K1R4Q b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test401() {
checkMate("Position401", "1k6/1p1r4/8/8/q4p1Q/2N1bP2/2n3P1/1RB2K2 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test402() {
checkMate("Position402", "3N4/6pk/Qpq5/P7/8/b4r2/P1P5/RK6 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test403() {
checkMate("Position403", "8/r1q2p1k/5P2/8/8/7N/R6R/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test404() {
checkMate("Position404", "6rk/pb5p/1p3p1Q/2p2p2/3q4/8/PPP3RP/4R2K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test405() {
checkMate("Position405", "4Rrk1/1b4pp/8/1rp2N2/2n4B/2P1R3/1P5P/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test406() {
checkMate("Position406", "2Rr3k/2R4p/1q1r1p2/8/1p4P1/7P/PQ5K/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test407() {
checkMate("Position407", "r1b2rk1/p4ppp/8/8/4NQq1/8/P5PP/3R1RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test408() {
checkMate("Position408", "2n2r1k/5Pp1/4p1Pp/2ppP2P/3p3Q/2qP4/p1P5/5R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test409() {
checkMate("Position409", "5rk1/p4Npp/1p6/3n1R2/3PR3/8/P4KPP/2r5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test410() {
checkMate("Position410", "r1b1rqk1/5p2/5Pp1/ppp1B1Q1/8/1P1P3R/P5PP/5RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test411() {
checkMate("Position411", "1brr2k1/pp3pp1/7p/8/5q1Q/8/PP2RPPP/1B2R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test412() {
checkMate("Position412", "6n1/2p2kpp/1r2R3/p4PP1/P1P1R3/2Pr4/5K2/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test413() {
checkMate("Position413", "8/1b3pkp/6p1/8/p4N2/Pq2Q1P1/2r4P/3R2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test414() {
checkMate("Position414", "8/6Q1/8/8/8/8/pp1K1PP1/1k6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test415() {
checkMate("Position415", "1k2r3/1pR2ppp/1P6/4N3/3P4/2P1P3/1K6/7b w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test416() {
checkMate("Position416", "2r2qrk/1p3ppp/p2p1b2/3NpP1Q/2P1R1R1/1P6/P5PP/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test417() {
checkMate("Position417", "6rk/r1q3pp/8/4ppN1/4P2N/2b5/B4PP1/Q6K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test418() {
checkMate("Position418", "3q4/p3NQpk/3r2pb/8/6P1/P4P2/8/6KR w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test419() {
checkMate("Position419", "2r4k/2p3R1/r1b4p/8/4p3/P7/B7/2K3R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test420() {
checkMate("Position420", "5rk1/RR6/5np1/2p5/2P1b3/6qP/1Q4P1/7K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test421() {
checkMate("Position421", "4r2k/2r3pp/4B3/q3P3/1n6/1R5Q/4R2P/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test422() {
checkMate("Position422", "3qrk2/1p1b1pp1/4p3/4P3/5N1Q/6P1/1P4K1/2R5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test423() {
checkMate("Position423", "5rk1/1pq2p2/5p2/8/3B1b2/7R/1P3PP1/3Q2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test424() {
checkMate("Position424", "5rk1/2q2p2/6pQ/4R2n/8/1P6/PB6/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test425() {
checkMate("Position425", "1k1r4/n1p1N3/1p1b3q/8/1Q6/7P/6B1/1R5K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test426() {
checkMate("Position426", "5rk1/1b3p1p/p5p1/3q4/8/Q3B3/1P3PPP/4R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test427() {
checkMate("Position427", "r1br1bk1/1p3p1p/p3p2B/4Qp2/2P5/8/2q2PPP/1R1R2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test428() {
checkMate("Position428", "1r4k1/bp3Rpp/p1n5/8/3P3N/1BP3P1/7P/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test429() {
checkMate("Position429", "8/1p3R2/4B3/b5k1/8/1n4PP/3p2K1/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test430() {
checkMate("Position430", "4r2r/1p2bpkp/2n3p1/4P3/8/2P5/B2B3Q/4K3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test431() {
checkMate("Position431", "2q1b3/2p1kp2/4Pp2/8/8/8/5Q2/1B5K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test432() {
checkMate("Position432", "3q1k2/2pn4/6Q1/3n1N2/8/8/4K3/1B6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test433() {
checkMate("Position433", "r4r1k/6p1/7p/6N1/1n6/8/B7/K1B4R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test434() {
checkMate("Position434", "1b6/k1p2r2/2B5/KP2p3/7B/8/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test435() {
checkMate("Position435", "3q4/1p4pk/1np2nNp/8/3P4/2P5/B5PP/1Q4K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test436() {
checkMate("Position436", "r1b5/4B3/1p6/1p6/2p1N1Pp/P4P1k/7P/4K3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test437() {
checkMate("Position437", "5k2/3r1p2/5p2/8/3N4/8/B6q/K3R1R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test438() {
checkMate("Position438", "8/R1N5/5pkp/3K2pp/6P1/6P1/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test439() {
checkMate("Position439", "6n1/r4p1k/7p/q3N3/5Q2/8/1PP5/1K3R2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test440() {
checkMate("Position440", "6r1/1p4pk/7n/1q3P2/4N3/8/1P1Q4/1K4R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test441() {
checkMate("Position441", "2k5/1ppN4/3p3p/5Q2/8/bP5P/P1Pq2r1/1K3R2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test442() {
checkMate("Position442", "5rk1/2p2ppp/2N5/8/R7/7P/1PQ1n1PK/5q2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test443() {
checkMate("Position443", "q4r2/p4ppk/2R1n3/5N2/8/2Q3P1/1P3P2/5K2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test444() {
checkMate("Position444", "r1b2rk1/pp3ppp/8/q1nNP3/2BRQ3/8/PP3PPP/2K4R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test445() {
checkMate("Position445", "3qrk2/p1r2pp1/1p2pb2/nP1bN2Q/3PN3/P6R/5PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test446() {
checkMate("Position446", "2r2rk1/5pp1/p3pbP1/1p6/3q4/1B6/PPP1Q3/2K4R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test447() {
checkMate("Position447", "1kr1q3/1p4Q1/1Pp5/8/4p3/6P1/8/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test448() {
checkMate("Position448", "3r3k/R7/5P1p/2q5/8/8/Q7/7K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test449() {
checkMate("Position449", "1r3rk1/5pp1/6Qp/p1q1pPb1/7P/1B6/PPP5/K2R2R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test450() {
checkMate("Position450", "4rk2/5p2/3q1P2/6R1/8/1p6/1P6/1KQ5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test451() {
checkMate("Position451", "3Q4/kp2n3/2p2q2/1P4p1/1P6/4N1P1/7K/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test452() {
checkMate("Position452", "7R/4bQ2/pn4p1/1pqP2kp/6P1/5B2/5PKP/1b6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test453() {
checkMate("Position453", "8/1p6/1P2q3/8/1P2k3/2Pp2P1/5Q2/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test454() {
checkMate("Position454", "r3rk2/2pR1p2/p3p1q1/6PQ/2p2P2/4P3/5PKP/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test455() {
checkMate("Position455", "3q2rk/5p1p/1p5Q/3b1N2/8/P5P1/8/4R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test456() {
checkMate("Position456", "4kbr1/4n1p1/4Q3/1p6/2q4B/5B2/1P4P1/5R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test457() {
checkMate("Position457", "k1r5/8/pp4p1/q2PQb2/8/4B2P/6PK/2R5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test458() {
checkMate("Position458", "5k2/5p2/1p2bB2/1P2P3/2q5/8/8/2Q4K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test459() {
checkMate("Position459", "r3kb1r/1b1n2pp/pq1pN3/1p1Q2B1/4P3/8/PPP2PPP/R4RK1 w q - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test460() {
checkMate("Position460", "1qb3rk/2p2p1p/6pQ/1p6/1R6/B7/1P3PP1/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test461() {
checkMate("Position461", "1q1r1k2/2R5/8/6K1/8/8/8/2Q5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test462() {
checkMate("Position462", "5k2/b4pq1/3p3Q/1prP4/8/3B4/1P5P/4R2K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test463() {
checkMate("Position463", "Q7/2q3bk/6Np/5p2/2p5/Pp6/1PP1r2P/1K4R1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test464() {
checkMate("Position464", "8/q1r3p1/1pp4k/6pp/8/P5P1/1PQ1B1PK/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test465() {
checkMate("Position465", "5nk1/3b2pp/3qp3/1p2N2Q/8/8/1P4PP/1B5K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test466() {
checkMate("Position466", "2q4k/p4Q1p/2n5/8/3b2N1/P6P/5B2/7K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test467() {
checkMate("Position467", "8/8/8/2K5/kp6/p6p/P2N4/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test468() {
checkMate("Position468", "8/8/8/8/3N4/p7/k1K5/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test469() {
checkMate("Position469", "8/8/8/8/6p1/1R6/7N/5K1k w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test470() {
checkMate("Position470", "r1b2nrk/pp3ppp/1q2p3/2bpn1N1/5N2/2PQ4/PPB2PPP/R1B2RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test471() {
checkMate("Position471", "r1b1k2r/2ppnN1p/5n2/pp5Q/4P3/1Bq5/P1P2KP1/R1B4R w qk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test472() {
checkMate("Position472", "kr6/bpQ3pp/p2N4/3N4/3p4/P2b1P2/1P2q1PP/2R3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test473() {
checkMate("Position473", "k1K5/1p6/pP6/R1P5/8/8/P1p5/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test474() {
checkMate("Position474", "5q2/p6R/1p5r/1k1pN3/1P3n2/2P5/P4P2/3Q1K2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test475() {
checkMate("Position475", "5nk1/R4N1p/5P1Q/8/2p1q3/8/KP6/6r1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test476() {
checkMate("Position476", "1Q6/5pkp/6p1/p2qP3/3n3P/4B1PK/1P6/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test477() {
checkMate("Position477", "1r4rb/1R6/4R3/k7/6p1/3N4/1P6/3K4 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test478() {
checkMate("Position478", "8/2r2bn1/5Ppk/8/5PP1/R7/2B5/2K5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test479() {
checkMate("Position479", "7r/4K1kp/5N1p/5PP1/8/8/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test480() {
checkMate("Position480", "2qk3r/2p1nQp1/3p4/3BP3/8/1P5P/6K1/5R2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test481() {
checkMate("Position481", "r3r1k1/4qpp1/5R2/1p6/6Q1/bP6/1BP3P1/1K5R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test482() {
checkMate("Position482", "4R3/1p1r1ppk/2q3b1/8/7P/2B1Q3/1P3P2/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test483() {
checkMate("Position483", "1k1rr3/1ppq1ppp/1b6/8/8/2P3P1/4QPBP/RR4K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test484() {
checkMate("Position484", "3Q1Q2/7k/6p1/4q2p/7P/6P1/7K/q7 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test485() {
checkMate("Position485", "2R2n2/3n1prk/5b1p/4qP2/p1p4B/2P4R/K1PQ4/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test486() {
checkMate("Position486", "3rkr1R/5p2/4p3/4P2Q/3q4/8/bPB5/2K4R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test487() {
checkMate("Position487", "2r2rk1/pp2qp1p/3b1Qp1/4N3/8/2B5/PP3PPP/5RK1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test488() {
checkMate("Position488", "Q7/p2rkrb1/8/8/4N2q/8/1P2R1PB/7K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test489() {
checkMate("Position489", "6r1/1R3Nbk/6p1/8/8/2q1Q3/2P5/1K6 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test490() {
checkMate("Position490", "3n1k2/5pp1/8/p7/Q3BP2/1P4P1/3q3r/4R1K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test491() {
checkMate("Position491", "Q7/2rk1pp1/3b4/5q2/8/8/4BP2/4RK2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test492() {
checkMate("Position492", "r1b1k2r/ppp3pp/1qp1P3/2b2p2/3Qn3/2N2N2/PPPB1PPP/3RK2R w Kk - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test493() {
checkMate("Position493", "3r1n1k/3P3p/pp3q2/2pQp3/P1P3B1/3b2R1/1P5P/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test494() {
checkMate("Position494", "5rk1/1b2bppp/1p2rB2/4P3/8/5P2/1P5K/R5R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test495() {
checkMate("Position495", "r3r2k/1p4Rp/2b2Rp1/4B3/3P4/6P1/1P6/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test496() {
checkMate("Position496", "8/8/8/5N2/4n3/1K6/p7/k7 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test497() {
checkMate("Position497", "8/2p5/2pP4/2NkpK2/2p1N3/2P5/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test498() {
checkMate("Position498", "3Q4/8/2ppp3/3k4/3N4/8/3K4/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test499() {
checkMate("Position499", "8/8/8/p7/B7/kP6/8/1K2B3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test500() {
checkMate("Position500", "k7/Pp6/1K6/5p2/4p2p/7P/6B1/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test501() {
checkMate("Position501", "8/8/3p4/pN2R3/k2p4/P2P4/K1P5/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test502() {
checkMate("Position502", "7r/7p/7P/8/2Q5/PB2p3/PpN1N3/1K2k3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test503() {
checkMate("Position503", "k4r2/8/p5Pp/3P3Q/4r1R1/1p2q3/1P6/1KR5 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test504() {
checkMate("Position504", "1Q2n3/8/K1kpp3/8/8/2q1P3/5P2/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test505() {
checkMate("Position505", "8/kpp2Q2/1q5p/P7/1P3p1r/4RPb1/3Bb1P1/RN4K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test506() {
checkMate("Position506", "1q4k1/8/r5p1/4b1N1/b7/2Pn3Q/RP6/K1R5 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test507() {
checkMate("Position507", "1k1r4/1p4pp/4B3/8/1nQN4/1qn5/1P4PP/K4R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test508() {
checkMate("Position508", "r3r1k1/pp3pbp/3p2p1/2pP3b/2P1P3/2N4q/PP2BP1P/R3QR1K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test509() {
checkMate("Position509", "7k/7p/5q2/8/4Q3/1P1B4/P2p4/1KR5 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test510() {
checkMate("Position510", "6r1/5p2/7k/5p1P/5PpK/6P1/8/7R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test511() {
checkMate("Position511", "r4rk1/pp3ppp/1bb1p3/3n4/8/1NP3Pq/PP3PBP/R1BQ1RK1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test512() {
checkMate("Position512", "1kr5/1p3p2/p2Kp3/2pn4/b7/8/P4P2/R3Q3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test513() {
checkMate("Position513", "2r3k1/5pb1/q5p1/8/3B4/2P4Q/r5PR/5RK1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test514() {
checkMate("Position514", "4r1r1/8/6n1/5p2/5P2/5KN1/3R3R/6k1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test515() {
checkMate("Position515", "k3q3/b6b/8/3pP2p/8/P2P4/P2B4/R2KQ3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test516() {
checkMate("Position516", "1k1r4/6p1/5b2/1p6/2n1B3/2r2P2/P7/1KR3NR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test517() {
checkMate("Position517", "r1r3k1/1Q3ppp/p3p3/8/4n3/8/P3qPPP/2R1B1KR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test518() {
checkMate("Position518", "r5k1/pp2bp1p/2p3p1/2P1R3/5n2/2P3Pq/PP1N1PbN/R2Q2K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test519() {
checkMate("Position519", "k3r3/pRR4p/5bp1/8/5Bb1/6PN/4pPKP/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test520() {
checkMate("Position520", "6k1/pbR2p1p/1p1p2pQ/8/6qP/6N1/P4PPK/4r3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test521() {
checkMate("Position521", "2k3r1/1bp1qp2/pb6/4p2p/4n3/2P2N2/1PB1QP1P/RN3R1K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test522() {
checkMate("Position522", "8/1pk3p1/p7/3p1b2/8/2P1K3/2q1PP1P/2B1Q3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test523() {
checkMate("Position523", "2r4k/5q1p/8/p3N3/5P2/1n6/KPRQ4/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test524() {
checkMate("Position524", "7Q/2p5/pp4k1/2pPp3/P2q2r1/KP5P/5RP1/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test525() {
checkMate("Position525", "q5bk/7p/7P/pp2p3/1P1bP2B/P7/2N5/1KR4R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test526() {
checkMate("Position526", "5k2/4r1p1/1p6/b6P/3p1N2/2nP4/2PK4/2B3R1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test527() {
checkMate("Position527", "k7/1p5q/p2B3p/4p1pR/1PPpBP1R/3Pn3/r5PP/4K3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test528() {
checkMate("Position528", "r5k1/r4qp1/4p3/3b4/1p6/1P3N2/1BP5/1KRQ1R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test529() {
checkMate("Position529", "8/2b5/4b1k1/B7/4p1PK/Q5PP/4p3/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test530() {
checkMate("Position530", "1r5q/8/2b5/8/3Q2R1/k4P2/4P3/K7 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test531() {
checkMate("Position531", "3b2k1/1p5p/1P5K/7P/4n2P/8/8/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test532() {
checkMate("Position532", "2k5/Bp3p2/8/2Kp2P1/3P2n1/6Q1/1P2qP2/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test533() {
checkMate("Position533", "2r3k1/6p1/8/P7/2q5/4P3/PK6/R3Q3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test534() {
checkMate("Position534", "1k3r2/5P2/8/5N2/1p6/1Pb5/K1P5/5R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test535() {
checkMate("Position535", "k7/pp3p1q/8/2b5/2P1nPQ1/1P2B3/4R3/1K6 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test536() {
checkMate("Position536", "4q3/6k1/r6p/2p3b1/3nB3/1P1P3R/P4N2/1K5Q b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test537() {
checkMate("Position537", "1k1r4/pp2Q3/8/5p2/2P2P2/1P3n2/2K5/q1R2N2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test538() {
checkMate("Position538", "5rk1/ppp2ppp/1q6/8/n2n4/P2P4/KPP1BQPP/3N1R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test539() {
checkMate("Position539", "1r3k2/p1p2pp1/2r2Pp1/3Qb3/3P4/1p2P2P/PP1q4/KR3B1R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test540() {
checkMate("Position540", "4r2k/pQ2P2p/P7/2pqb3/3p1p2/8/3B2rP/4RR1K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test541() {
checkMate("Position541", "k1r5/p4p2/2r3p1/3p3p/b2P3P/q2B1Q2/PpP1R1P1/1K3R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test542() {
checkMate("Position542", "4rk2/p3b3/4qpp1/R2Q3p/1PpPB3/2Pb1PP1/6KP/3n2BR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test543() {
checkMate("Position543", "r7/1kp4b/5n1p/1p2p3/6p1/BP3rR1/KPq1N2P/3Q3R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test544() {
checkMate("Position544", "1kr5/ppp3p1/1q2p3/1B1pP3/3P2P1/1P5r/K1P1Q2P/1Rb4R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test545() {
checkMate("Position545", "1kr5/1p4p1/8/4p3/q5b1/3B2P1/1PPK4/2B1Q2R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test546() {
checkMate("Position546", "1k2rq2/pp4pp/8/4N3/3n2P1/2n2PQ1/PPr4P/K1BR3R b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test547() {
checkMate("Position547", "1r4k1/6p1/q3b1P1/8/8/bP6/2P1N2Q/RK3R2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test548() {
checkMate("Position548", "1R5K/8/6r1/8/1P6/6k1/7p/7b b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test549() {
checkMate("Position549", "6k1/1p2r1P1/2p5/2N5/1n1r4/2K5/1P6/6RR b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test550() {
checkMate("Position550", "r2k4/7b/8/8/3n4/8/PPPB4/K2R4 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test551() {
checkMate("Position551", "1k6/5n2/1P6/2K5/2P5/5b2/1q6/8 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test552() {
checkMate("Position552", "2k2r2/2p5/1pq5/p1p1n3/P1P4B/1R4Pp/2Q1R3/6K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test553() {
checkMate("Position553", "1b6/4R3/2B2p2/p4k2/P7/5K2/3r3P/8 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test554() {
checkMate("Position554", "k4rr1/p6R/P7/1R3q2/8/8/5p1P/1Q5K w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test555() {
checkMate("Position555", "r2q1rb1/4b1kp/2n2pP1/2n1pP1Q/p3P2P/3p2N1/PPp2RBN/R5K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test556() {
checkMate("Position556", "2r3k1/Q6R/3p1q1p1/3Pp1N1/pp1n4/7P/P4PP1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test557() {
checkMate("Position557", "8/4nr1p/4p1k1/3qP1p1/R7/3p1P2/3Q2K1/7R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test558() {
checkMate("Position558", "6k1/1R6/2pN2pb/2P5/6K1/5P1P/2N1r3/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test559() {
checkMate("Position559", "3r1r1k/1R5p/7R/N5p1/1p3nP1/1P6/P1P5/1K6 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test560() {
checkMate("Position560", "8/3K1PQ1/2p2P1B/2Rbk3/1P6/4N3/2B1Rr2/5n2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test561() {
checkMate("Position561", "QBN5/2p4P/B3p3/1P1p4/3k1p2/1Pp3N1/8/R3K3 w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test562() {
checkMate("Position562", "5RK1/7N/6pk/7P/4p1P1/1p6/5B2/1q3n2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test563() {
checkMate("Position563", "5b2/4p1p1/5N2/3p1N2/3p1B1p/2pk2p1/4R3/1R1B2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test564() {
checkMate("Position564", "6k1/3Q2p1/p3N2p/1p5P/1P6/2q2PP1/3n2K1/8 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test565() {
checkMate("Position565", "2b1k2r/1ppNbppp/3P4/1B6/8/2P2qP1/1P3P2/4R1K1 w k - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test566() {
checkMate("Position566", "6Q1/8/3p3k/5q1p/7K/4P1nP/R7/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test567() {
checkMate("Position567", "1r2r3/3b3p/8/1p2p3/4P1k1/P7/3Q2KP/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test568() {
checkMate("Position568", "6kr/1p2qp1p/p1n3pB/8/2P1N3/6P1/4QP2/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test569() {
checkMate("Position569", "6k1/pp3ppp/1b6/3Q2Pb/P3PN2/2p3P1/2P3qP/4KR2 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test570() {
checkMate("Position570", "r2r4/p2n1k1B/1p1q1p1Q/2pPp3/2P5/8/PP3PPP/2R3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test571() {
checkMate("Position571", "r4bkr/pp1q2pp/8/6N1/8/2P2Q2/1PN2PPP/2K1R3 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test572() {
checkMate("Position572", "6K1/8/4Q1bk/6p1/6B1/8/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test573() {
checkMate("Position573", "8/4R1pk/2pN2r1/2Pb4/3B3P/7K/4R3/3r4 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test574() {
checkMate("Position574", "6k1/2p3p1/1p2p2p/1n6/2N5/1P1QP3/r3q1PP/5R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test575() {
checkMate("Position575", "2B3K1/8/3N1p1p/6pk/5P1P/6P1/7r/5r2 w - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test576() {
checkMate("Position576", "r4b1r/pppQ4/2n1R2p/q7/5P1k/8/PPP3PP/R5K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test577() {
checkMate("Position577", "r2bk3/pp4q1/3Q2Np/8/6B1/6K1/P7/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test578() {
checkMate("Position578", "7k/1pp5/p2n4/4p1Nn/2q4P/5Q2/PPP5/2K5 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test579() {
checkMate("Position579", "8/1N4r1/3p2p1/p2k4/P2P4/3K4/6N1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test580() {
checkMate("Position580", "7K/2p5/n1P3bk/3p2pp/Q5P1/3rB3/5P1P/6r1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test581() {
checkMate("Position581", "8/8/ppq3n1/2pRQ3/8/4Pk2/PPb2P2/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test582() {
checkMate("Position582", "8/2n2pp1/2pp3p/5P1k/p2BP2P/P2P1K2/1rP3P1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test583() {
checkMate("Position583", "r6r/4ppk1/2bp1R2/6N1/p2pP1PQ/3P3P/PPq5/3R3K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test584() {
checkMate("Position584", "8/6K1/2Q2B2/5pn1/2N3pk/1P5n/4qP2/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test585() {
checkMate("Position585", "1r3k2/Q2n1p2/5p2/3q1N2/1p2p1P1/3p4/PP4P1/2R3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test586() {
checkMate("Position586", "k1n5/pR6/PP1bp3/3pNp2/8/1K2P3/3B3r/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test587() {
checkMate("Position587", "5rr1/7k/p1p3Rp/1p1q3P/1P2Q3/5NP1/5PK1/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test588() {
checkMate("Position588", "KB1b4/4p3/B4p2/p5p1/7p/3p3k/2R5/3q4 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test589() {
checkMate("Position589", "7K/8/5ppk/6p1/5BPP/8/7r/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test590() {
checkMate("Position590", "6k1/6p1/p3p1Kp/P3p3/4Pr2/2PPN3/1P2nPPN/R5R1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test591() {
checkMate("Position591", "2r4k/5q1n/2bp1P1R/p7/3B4/1P1Q2N1/1PP3rP/5K2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test592() {
checkMate("Position592", "rnbq1r2/pppp2kp/1b3N2/4N1pQ/2BP4/6p1/PPP4P/R4K1R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test593() {
checkMate("Position593", "r1b1qrk1/ppppnNp1/2n4p/2b1p2Q/2B1P3/3P4/PPP2PPP/RNB1K2R w KQ - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test594() {
checkMate("Position594", "r1b1k2r/ppp2ppp/2p5/8/3Qn1q1/8/PPPB2PP/2KR1B1R w kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test595() {
checkMate("Position595", "rnb1kb1r/pp3ppp/2p5/4q3/4n3/3Q4/PPPB1PPP/2KR1BNR w kq - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test596() {
checkMate("Position596", "2kr1bnr/Qp1bpppp/2n5/3q4/8/2P5/PP3PPP/RNB1KB1R b KQ - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test597() {
checkMate("Position597", "r1b1k2r/ppp3pp/1qp5/2b1Pp2/3Qn3/5N2/PPPBNPPP/3RK2R w Kkq - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test598() {
checkMate("Position598", "4r3/p4pkp/q7/3Bbb2/P2P1ppP/2N3n1/1PP2KPR/R1BQ4 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test599() {
checkMate("Position599", "k6r/rb3R1p/NQ4p1/2p2n2/1p6/8/PPn3PP/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test600() {
checkMate("Position600", "6k1/6p1/p3p1Kp/P3p3/4Pr2/2PPN3/1P2nPPN/R5R1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test601() {
checkMate("Position601", "2r4k/5q1n/2bp1P1R/p7/3B4/1P1Q2N1/1PP3rP/5K2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test602() {
checkMate("Position602", "rnbq1r2/pppp2kp/1b3N2/4N1pQ/2BP4/6p1/PPP4P/R4K1R w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test603() {
checkMate("Position603", "6k1/Q5p1/7p/P3B2K/4q3/8/7P/8 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test604() {
checkMate("Position604", "1r1r1k2/2R2p1p/8/4P3/3PnN2/8/1q3PQ1/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test605() {
checkMate("Position605", "Q4b1r/3knn1p/4pPp1/B2pP3/8/8/6PP/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test606() {
checkMate("Position606", "RQ6/5bkp/1pp5/4p2q/1P2Pp2/3P3P/2PN1br1/5K2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test607() {
checkMate("Position607", "3r2k1/4R2p/6p1/2Q5/2P5/1R3q2/P2r3P/5BK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test608() {
checkMate("Position608", "2r2r1k/3bqpp1/3ppN1p/1p6/p2P3R/2R3Q1/PP4PP/6K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test609() {
checkMate("Position609", "2r1b2k/p3p2p/3p1pp1/1p1Q4/2q1P3/5P2/PPr3P1/1KBR3R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test610() {
checkMate("Position610", "3R4/r4p2/2b1np2/4N3/6Pk/4P3/5K2/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test611() {
checkMate("Position611", "3rr2Q/pq3k2/1p2p2p/2p1P1b1/8/8/PKP1B1PP/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test612() {
checkMate("Position612", "8/6p1/p3Q3/1kpn2q1/2N5/2P2P2/1K4P1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test613() {
checkMate("Position613", "4Rrk1/2q2p2/3p2p1/7p/3Q4/5P2/PPr3P1/1K1R4 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test614() {
checkMate("Position614", "8/1r2bp2/3p2p1/p5k1/1n2R3/2BP4/5PKP/5N2 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test615() {
checkMate("Position615", "4r1k1/p2Q2p1/1q5p/8/5n2/1P3P2/1B1p2PP/R4K2 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test616() {
checkMate("Position616", "3Q4/1k6/8/1P6/8/8/1P4K1/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test617() {
checkMate("Position617", "8/1r3Q1R/r2k4/p7/5p2/1PPp4/5qPK/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test618() {
checkMate("Position618", "5r2/6Q1/2p5/2kqP3/2p5/2P2p2/P7/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test619() {
checkMate("Position619", "8/3Q4/1k6/8/1P3K2/8/8/3N4 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test620() {
checkMate("Position620", "4r3/2pNqk2/p1Pp3Q/6pb/4P3/P5P1/5PK1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test621() {
checkMate("Position621", "4rb2/3r3p/p7/5p2/2n4k/2Qqp3/PPP4P/1K4R1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test622() {
checkMate("Position622", "r5k1/p3Qpbp/2p3p1/1p6/q3bN2/6PP/PP3P2/K2RR3 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test623() {
checkMate("Position623", "2r1nr1k/pp1q1p1p/3bpp2/5P2/1P1Q4/P3P3/1B3P1P/R3K1R1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test624() {
checkMate("Position624", "4N1QB/1K2k1P1/4N3/8/8/8/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test625() {
checkMate("Position625", "8/2P1P1P1/3PkP2/8/4K3/8/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test626() {
checkMate("Position626", "6R1/8/4N3/8/8/7k/8/5K2 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test627() {
checkMate("Position627", "3R3K/8/5Q2/8/5N2/1B6/2PB4/1qbk4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test628() {
checkMate("Position628", "8/5p2/4pQ2/4Rb2/6k1/3P4/6PK/6R1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test629() {
checkMate("Position629", "2B5/8/8/1n6/1P1k2N1/8/P2B4/2K3NQ w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test630() {
checkMate("Position630", "1r5r/kp3p2/6pn/pP1N1b1p/1n2pB2/2R3P1/P6P/3R2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test631() {
checkMate("Position631", "r5rk/pp1b1p1p/1qn2PpQ/5nPP/5P2/1PP5/2B5/R1B1K2R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test632() {
checkMate("Position632", "1r5k/b1pR1B2/p6p/Pp2NP2/8/2P4P/1r2n3/R6K w - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test633() {
checkMate("Position633", "8/8/7p/4N1kb/3nPRN1/6Q1/8/3K4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test634() {
checkMate("Position634", "8/8/3n4/QpR5/3p4/1k1B4/p7/K2b4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test635() {
checkMate("Position635", "5Br1/2N1NkP1/7Q/8/5n2/3n4/7K/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test636() {
checkMate("Position636", "4RQ2/8/4bB2/4N3/3k4/2N5/1P4n1/6K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test637() {
checkMate("Position637", "8/1B6/8/3q3r/6N1/4p3/4R2B/R3K2k w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test638() {
checkMate("Position638", "1Nb1r3/7Q/2NkP3/R7/8/2K4B/8/8 w Q - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test639() {
checkMate("Position639", "1N2R3/5n2/1K1k4/3ppp2/2p5/8/5R2/7Q w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test640() {
checkMate("Position640", "7r/6p1/8/6R1/r6k/5P2/3p3K/4b1Q1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test641() {
checkMate("Position641", "2b5/6R1/4Nk2/8/3P2Pb/1Q5B/K5n1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test642() {
checkMate("Position642", "5b2/1Q6/1P4R1/3rkP2/8/5R1K/5N2/6B1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test643() {
checkMate("Position643", "6nN/1Q6/3pk2n/4p2N/7P/3B4/8/5K2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test644() {
checkMate("Position644", "6K1/8/8/8/1R6/1N6/2kp4/QbN2B2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test645() {
checkMate("Position645", "rn3rk1/pbppq1pp/1p2pb2/4N2Q/3PN3/3B4/PPP2PPP/R3K2R w QK - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test646() {
checkMate("Position646", "2q1rb1k/prp3pp/1pn1p3/5p1N/2PP3Q/6R1/PP3PPP/R5K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test647() {
checkMate("Position647", "8/pb4qk/1p5p/4r1PR/2B1p3/4Qr2/PPP5/1K4R1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test648() {
checkMate("Position648", "r1b2r2/3pNpkp/3pn1p1/2pN3P/2PnP3/q3QP2/4BKP1/1R5R w - - 0 1", 9); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test650() {
checkMate("Position650", "6rk/1p3ppp/q7/pn2QN2/8/PP2P1P1/5P1P/2R3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test651() {
checkMate("Position651", "r6k/ppp4q/2nb1prB/3Bp2Q/4P3/2P4R/PP3PP1/4R1K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test652() {
checkMate("Position652", "3rkb1r/1bq2ppp/p3p3/1p2PP2/5P2/P1N1p3/1PP1BB1P/R3QRK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test653() {
checkMate("Position653", "6k1/2P3pp/8/4rp2/P4n2/7q/2R1PK2/6Q1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test654() {
checkMate("Position654", "r2qrk2/ppp3pQ/5p2/3Np1b1/2B1P1P1/P2P4/1PP5/1K5R w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test655() {
checkMate("Position655", "r1b1k1nr/1p1n1pbp/p1pQ2p1/4p3/2B1PB2/2q2N2/P1P2PPP/1R1R2K1 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test656() {
checkMate("Position656", "6k1/4p2p/7B/3K4/8/8/8/8 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test657() {
checkMate("Position657", "6k1/pp3pp1/1b5p/5q2/2br4/Q1N3P1/PP3PBP/4R1K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test658() {
checkMate("Position658", "r1bq3r/pp3pp1/2n1p1k1/2pp2P1/3P1BQ1/2P1P3/PP1N1PP1/R3K2R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test659() {
checkMate("Position659", "q5rk/6rp/1p2Pb2/1B3P2/PP6/4QR2/7P/3R3K b - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test660() {
checkMate("Position660", "4R3/Q4Bpk/7p/7b/Pq6/6P1/3r1P1P/6K1 b - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test662() {
checkMate("Position662", "8/8/4p2Q/2K1p3/4k3/2p2r2/5RRp/7B w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test663() {
checkMate("Position663", "R7/4k3/2n2N2/7Q/8/4B2B/1K6/4R3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test664() {
checkMate("Position664", "r3r1k1/pp1n2Bp/5P2/2Q5/3pb3/3q2P1/P5BP/R4R1K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test665() {
checkMate("Position665", "8/7K/2Rn1N2/6k1/6N1/2n4p/8/4QR2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test666() {
// checkMate("Position666", "3r3k/4Qp1p/p3p3/1pR5/3qb2P/P5R1/1P3PP1/6K1 w - - 0
// 1", 8); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test667() {
checkMate("Position667", "3Rn2K/8/Q4N2/4k3/4B3/6P1/b6B/b4r2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test668() {
checkMate("Position668", "4Q3/1R6/3p4/3k1NK1/1P6/3p4/3P4/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test669() {
checkMate("Position669", "1nq2rk1/r4p1p/4RRp1/2p5/2B5/8/P5PP/5Q1K w - - 0 1", 8); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test670() {
checkMate("Position670", "n1k1n2r/Qb1r2q1/1p1p1p2/1PpPpPp1/2P1P1P1/6R1/3B1KB1/R1N5 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test671() {
checkMate("Position671", "7k/p2R4/2p2p1P/5K2/1PP5/8/r2B2pb/8 w - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test672() {
checkMate("Position672", "2k4r/B1p2pp1/1p4n1/1P6/P1P3q1/4PNbr/2Q2R1P/6RK b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test673() {
checkMate("Position673", "r4rk1/1p3pp1/2ppbq2/p1b5/2P5/PPN1P1Q1/1B3PPP/R3K2R w QK - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test674() {
checkMate("Position674", "b2r4/5Rbk/6pp/qPp1p3/2B2n1N/6NP/5PP1/1Q4K1 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test675() {
checkMate("Position675", "2r2nk1/1b1r2p1/p3p1p1/1p2P1N1/7Q/7P/qPP2RP1/4R1K1 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test676() {
checkMate("Position676", "r1bk2r1/1p1nR2p/p2Q1pqB/2pp1N2/3P4/P7/5PPP/2R3K1 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test677() {
checkMate("Position677", "3rr3/1qb1kp1P/2p1pp2/ppPn4/3P1pQ1/1N4P1/PP4B1/2R1R1K1 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test678() {
checkMate("Position678", "r1b2r2/1p1nq1b1/1np1p1kp/p7/3PN3/1P2B3/2Q1BPPP/2RR2K1 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test679() {
checkMate("Position679", "1qB3k1/5pp1/1Bb4p/2P4n/1P1p4/P4n2/1N2Q1PP/2R2N1K b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test680() {
checkMate("Position680", "2b1rk2/r3bppB/p2Q4/2N5/1qP5/8/6PP/5RBK w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test681() {
checkMate("Position681", "3rk1r1/1q3p1p/pn6/1pb1PN2/1Pp5/8/R3Q1PP/1NB4K b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test682() {
checkMate("Position682", "r3rbnk/p2bq1np/2p1p2B/6N1/PppPPN1Q/8/1P4BP/3R2RK w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test683() {
checkMate("Position683", "3b1rk1/1pqb1p2/6p1/1P2p3/5R2/2NP2Q2/6PP/5R1K w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test684() {
checkMate("Position684", "8/4KR2/4p3/1N6/2b1kB2/3R4/4np2/Q3n3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test685() {
checkMate("Position685", "r3k3/pB1pp1K1/N3r1p1/3Qp3/8/8/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test686() {
checkMate("Position686", "2KBB3/8/p7/1n3Q2/k1p5/P2R1p2/6b1/R1N1b3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test687() {
checkMate("Position687", "1Kb5/1p6/R5Bp/3N1nk1/2r1pR1N/B6P/7b/2Q5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test688() {
checkMate("Position688", "8/p7/Q4pN1/K3p3/2r5/3k1B2/2p1N3/2B5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test689() {
checkMate("Position689", "8/1n6/1n6/3p4/1k2p3/8/8/RNBQKB2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test690() {
checkMate("Position690", "6b1/3B2N1/4P1p1/8/6kB/8/K6Q/6Nn w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test691() {
checkMate("Position691", "3r4/1p6/7b/8/Q7/3R1R1P/3Bk1N1/1K6 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test692() {
checkMate("Position692", "N1K5/3pQ3/n7/kP1R4/b2N4/1p6/1P6/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test693() {
checkMate("Position693", "3r3k/p1R1R3/1p3qrp/5p2/7n/P7/1P2QP1P/7K b - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test694() {
checkMate("Position694", "5rk1/Q4p2/1Rr1p2p/2P5/3P1qn1/P2B2pP/3R2P1/2B3K1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test695() {
checkMate("Position695", "2kr3r/1b1p2p1/p1qBpp2/6p1/8/1Q1B3P/P1P2PP1/1R4K1 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test696() {
checkMate("Position696", "q4r1k/5p1p/3pp2Q/1p2b3/8/p4R2/7P/6RK w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test697() {
checkMate("Position697", "8/p7/rp6/kp6/1p6/1P6/1P2N3/1K3n2 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test698() {
checkMate("Position698", "8/3P4/8/8/8/1KN1k1B1/4P3/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test699() {
checkMate("Position699", "4rb1k/1b1n2pp/p7/q7/1pB1pN2/1P2Q3/PB4PP/2R3K1 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test700() {
checkMate("Position700", "2nrkb1r/2q2p1p/p2p1p2/1p1QpN1B/4P3/2P5/PP3PPP/R2R2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void _test701() {
checkMate("Position701", "4r1k1/5pp1/p6p/3n4/Pp2r3/8/1qQB2PP/2NK1B1R b - - 0 1", 8); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test702() {
checkMate("Position702", "5r1k/1R4b1/4BqPp/5P2/3p1Q2/6PK/P7/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test703() {
checkMate("Position703", "6rk/5p1p/4qb2/p1n1pNr1/PpPpPp2/1P3R1Q/3N2PP/3R3K w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test704() {
checkMate("Position704", "1r3nk1/p5N1/4p1PQ/1n1p4/2p2PP1/q2B4/Pp5R/1K1R4 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test705() {
checkMate("Position705", "6rk/1p3ppp/q7/pn2QN2/8/PP2P1P1/5P1P/2R3K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test707() {
checkMate("Position707", "8/1K6/4R1Bk/4Bpp1/7n/8/8/7Q w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test708() {
checkMate("Position708", "KQ2nrrq/2p5/3p4/8/2p5/2k1B2R/2BR4/n7 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test709() {
checkMate("Position709", "8/4b2N/3p4/R2prk1B/Q4N2/3Kp3/8/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test710() {
checkMate("Position710", "4r1k1/3b1p2/5qp1/1BPpn2p/7n/r3P1N1/2Q1RPPP/1R3NK1 b - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test711() {
checkMate("Position711", "4r3/pp3Bpk/2pB1n1p/2P5/1P2p2r/5bNq/PQ6/R3R1K1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test712() {
checkMate("Position712", "8/1K6/NQ6/1N6/k6b/1rp5/pqB5/2B5 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test713() {
checkMate("Position713", "8/8/6B1/5R2/1bN5/p3p3/2k1p2R/Q6K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test714() {
checkMate("Position714", "1Q1BRK2/8/3p1R1N/2q2N2/5k1P/8/6P1/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test715() {
checkMate("Position715", "KQ6/8/2R5/3p2p1/3k4/4n2r/1P3N2/4N3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test716() {
checkMate("Position716", "2b5/B1kq3R/8/3QR3/8/8/8/K7 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test717() {
checkMate("Position717", "8/3R1K2/2B1N2p/4k1P1/q2p1pQ1/2n4r/4PN2/2b2r2 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test718() {
checkMate("Position718", "8/5p2/3Q3b/3B1k1b/5P2/7P/5K2/8 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test719() {
checkMate("Position719", "1r1r4/8/1n6/2p5/2P5/1NK5/R6R/1k6 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test720() {
checkMate("Position720", "2kr3r/pR3pp1/B1nq1b1p/5P2/4pBPP/8/PP3P2/2R1K3 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test721() {
checkMate("Position721", "r1rR4/5kpp/p7/5p2/q2NpB2/4P3/5PPP/3Q2K1 w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test722() {
checkMate("Position722", "8/4n3/3p1nk1/1RpPprNp/2P4P/Q5B1/6P1/7K b - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test723() {
checkMate("Position723", "8/4pkPp/7B/3K4/8/8/8/8 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test724() {
checkMate("Position724", "1k6/p3qp1p/PB2p3/3bb3/2R1nP2/1Q6/1P4r1/5R1K b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test725() {
checkMate("Position725", "1B6/8/6b1/R2p4/2pkN1Q1/8/2P2P2/b2K4 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test726() {
checkMate("Position726", "4Qbk1/2qnpp1p/3p2pB/2pP4/4N3/7P/r4PPK/4R3 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test727() {
checkMate("Position727", "k7/pb6/1p1Q4/N4q2/5pr1/8/6PP/3R3K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test728() {
checkMate("Position728", "7r/pp1qrpk1/2p2Rp1/8/P2pP1PQ/1P1P1R2/2P5/6K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test729() {
checkMate("Position729", "8/4n3/3p1nk1/1RpPprNp/2P4P/Q5B1/6P1/7K b - - 0 1", 7); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test730() {
checkMate("Position730", "r3k2r/p1qp1ppp/b1pbp3/8/4P1n1/2N2N1P/PPP2PP1/R1BQR1K1 b kq - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test731() {
checkMate("Position731", "k7/Pp6/1p6/1p3B2/1p3K2/1p6/8/R7 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test732() {
checkMate("Position732", "q4r1k/5p1p/3pp2Q/1p2b3/8/p4R2/7P/6RK w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test733() {
checkMate("Position733", "8/2N4n/4R3/3p1K1k/7p/5p1R/6P1/4n1q1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test734() {
checkMate("Position734", "8/p7/rp6/kp6/1p6/1P6/1P2N3/1K3n2 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test735() {
checkMate("Position735", "5rk1/1p1b2pp/pq6/3pP3/3N4/P5PP/1P1BKbB1/R2Q3R b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test736() {
checkMate("Position736", "6rk/pp1b4/3p3p/3P1p2/2P2Q1P/7K/PP2BR2/6q1 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test737() {
checkMate("Position737", "r4rk1/pp3pB1/5b2/2p1nN1P/6Q1/2Pq4/PP3PP1/K6R w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test738() {
checkMate("Position738", "6rk/5p1p/4qb2/p1n1pNr1/PpPpPp2/1P3R1Q/3N2PP/3R3K w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test739() {
checkMate("Position739", "6k1/2P3pp/8/4rp2/P4n2/7q/2R1PK2/6Q1 b - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test740() {
checkMate("Position740", "1Q6/1N3ppk/7p/8/5nqP/1P6/P2R4/7K b - - 0 1", 8); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test741() {
checkMate("Position741", "r1b1r1k1/ppq2p1p/3b1p1Q/2n4p/8/3B4/PPP2PPP/R1B2RK1 w - - 0 1", 6); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test742() {
checkMate("Position742", "2R5/4bppk/1p1p4/5R1P/4PQ2/5P2/r4q1P/7K w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test745() {
checkMate("Position745", "r1b1k1nr/1p1n1pbp/p1pQ2p1/4p3/2B1PB2/2q2N2/P1P2PPP/1R1R2K1 w - - 0 1", 5); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test746() {
checkMate("Position746", "1nq2rk1/r4p1p/4RRp1/2p5/2B5/8/P5PP/5Q1K w - - 0 1", 9); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test747() {
checkMate("Position747", "2q5/2pp4/3pr3/4pb2/K1p2pn1/2bn1kp1/3pr1R1/6BB w - - 0 1", 12); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test748() {
checkMate("Position748", "1q2r1k1/2p1bpp1/8/1r6/8/1B6/1B6/1K2Q2R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test749() {
checkMate("Position749", "3r2k1/1b3p1p/p4PpQ/2q1P3/2p5/8/P1r2RPP/5RK1 b - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test750() {
checkMate("Position750", "2r4k/p5p1/3Qq2p/4N3/Pp3n2/6P1/PK5P/3R4 b - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test751() {
checkMate("Position751", "k1r5/p6r/1b6/1N3n2/5Qp1/3B1pBq/5P2/R5K1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test752() {
checkMate("Position752", "5rk1/ppp2ppp/2nr4/5Q2/2B5/5N2/PqPB1PPP/2RKR3 w - - 0 1", 2); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test753() {
checkMate("Position753", "1q2r1k1/2p1bpp1/8/1r6/8/1B6/1B6/1K2Q2R w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test754() {
checkMate("Position754", "5rk1/4Rp1p/5QpB/q4n2/8/1P7/r5PP/3R3K w - - 0 1", 3); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test755() {
checkMate("Position755", "8/6B1/8/4p3/3P4/PKP5/1PB5/k7 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
public void test756() {
checkMate("Position756", "2r1kbr1/p4p1p/1qN1pB2/1Q2P1p1/3P4/4P3/PP4PP/2R2RK1 w - - 0 1", 4); //$NON-NLS-1$ //$NON-NLS-2$
}
// public void test757() {
// checkMate("Position757", "k7/P7/P7/P7/P7/P7/P7/R3K3 w Q - 0 1", 8); //$NON-NLS-1$ //$NON-NLS-2$
}
|
package nxt;
import nxt.util.Logger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
final class DbVersion {
static void init() {
try (Connection con = Db.getConnection(); Statement stmt = con.createStatement()) {
int nextUpdate = 1;
try {
ResultSet rs = stmt.executeQuery("SELECT next_update FROM version");
if (! rs.next()) {
throw new RuntimeException("Invalid version table");
}
nextUpdate = rs.getInt("next_update");
if (! rs.isLast()) {
throw new RuntimeException("Invalid version table");
}
rs.close();
Logger.logMessage("Database update may take a while if needed, current db version " + (nextUpdate - 1) + "...");
} catch (SQLException e) {
Logger.logMessage("Initializing an empty database");
stmt.executeUpdate("CREATE TABLE version (next_update INT NOT NULL)");
stmt.executeUpdate("INSERT INTO version VALUES (1)");
con.commit();
}
update(nextUpdate);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private static void apply(String sql) {
try (Connection con = Db.getConnection(); Statement stmt = con.createStatement()) {
try {
if (sql != null) {
Logger.logDebugMessage("Will apply sql:\n" + sql);
stmt.executeUpdate(sql);
}
stmt.executeUpdate("UPDATE version SET next_update = (SELECT next_update + 1 FROM version)");
con.commit();
} catch (SQLException e) {
con.rollback();
throw e;
}
} catch (SQLException e) {
throw new RuntimeException("Database error executing " + sql, e);
}
}
private static void update(int nextUpdate) {
switch (nextUpdate) {
case 1:
apply("CREATE TABLE IF NOT EXISTS block (db_id INT IDENTITY, id BIGINT NOT NULL, version INT NOT NULL, "
+ "timestamp INT NOT NULL, previous_block_id BIGINT, "
+ "FOREIGN KEY (previous_block_id) REFERENCES block (id) ON DELETE CASCADE, total_amount INT NOT NULL, "
+ "total_fee INT NOT NULL, payload_length INT NOT NULL, generator_public_key BINARY(32) NOT NULL, "
+ "previous_block_hash BINARY(32), cumulative_difficulty VARBINARY NOT NULL, base_target BIGINT NOT NULL, "
+ "next_block_id BIGINT, FOREIGN KEY (next_block_id) REFERENCES block (id) ON DELETE SET NULL, "
+ "index INT NOT NULL, height INT NOT NULL, generation_signature BINARY(64) NOT NULL, "
+ "block_signature BINARY(64) NOT NULL, payload_hash BINARY(32) NOT NULL, generator_account_id BIGINT NOT NULL)");
case 2:
apply("CREATE UNIQUE INDEX IF NOT EXISTS block_id_idx ON block (id)");
case 3:
apply("CREATE TABLE IF NOT EXISTS transaction (db_id INT IDENTITY, id BIGINT NOT NULL, "
+ "deadline SMALLINT NOT NULL, sender_public_key BINARY(32) NOT NULL, recipient_id BIGINT NOT NULL, "
+ "amount INT NOT NULL, fee INT NOT NULL, referenced_transaction_id BIGINT, index INT NOT NULL, "
+ "height INT NOT NULL, block_id BIGINT NOT NULL, FOREIGN KEY (block_id) REFERENCES block (id) ON DELETE CASCADE, "
+ "signature BINARY(64) NOT NULL, timestamp INT NOT NULL, type TINYINT NOT NULL, subtype TINYINT NOT NULL, "
+ "sender_account_id BIGINT NOT NULL, attachment OTHER)");
case 4:
apply("CREATE UNIQUE INDEX IF NOT EXISTS transaction_id_idx ON transaction (id)");
case 5:
apply("CREATE UNIQUE INDEX IF NOT EXISTS block_height_idx ON block (height)");
case 6:
apply("CREATE INDEX IF NOT EXISTS transaction_timestamp_idx ON transaction (timestamp)");
case 7:
apply("CREATE INDEX IF NOT EXISTS block_generator_account_id_idx ON block (generator_account_id)");
case 8:
apply("CREATE INDEX IF NOT EXISTS transaction_sender_account_id_idx ON transaction (sender_account_id)");
case 9:
apply("CREATE INDEX IF NOT EXISTS transaction_recipient_id_idx ON transaction (recipient_id)");
case 10:
apply("ALTER TABLE block ALTER COLUMN generator_account_id RENAME TO generator_id");
case 11:
apply("ALTER TABLE transaction ALTER COLUMN sender_account_id RENAME TO sender_id");
case 12:
apply("ALTER INDEX block_generator_account_id_idx RENAME TO block_generator_id_idx");
case 13:
apply("ALTER INDEX transaction_sender_account_id_idx RENAME TO transaction_sender_id_idx");
case 14:
apply("ALTER TABLE block DROP COLUMN IF EXISTS index");
case 15:
apply("ALTER TABLE transaction DROP COLUMN IF EXISTS index");
case 16:
apply("ALTER TABLE transaction ADD COLUMN IF NOT EXISTS block_timestamp INT");
case 17:
apply(null);
case 18:
apply("ALTER TABLE transaction ALTER COLUMN block_timestamp SET NOT NULL");
case 19:
apply("ALTER TABLE transaction ADD COLUMN IF NOT EXISTS hash BINARY(32)");
case 20:
apply(null);
case 21:
apply(null);
case 22:
apply("CREATE INDEX IF NOT EXISTS transaction_hash_idx ON transaction (hash)");
case 23:
apply(null);
case 24:
apply("ALTER TABLE block ALTER COLUMN total_amount BIGINT");
case 25:
apply("ALTER TABLE block ALTER COLUMN total_fee BIGINT");
case 26:
apply("ALTER TABLE transaction ALTER COLUMN amount BIGINT");
case 27:
apply("ALTER TABLE transaction ALTER COLUMN fee BIGINT");
case 28:
apply(null);
case 29:
apply(null);
case 30:
apply(null);
case 31:
apply(null);
case 32:
apply(null);
case 33:
apply(null);
case 34:
apply(null);
case 35:
apply(null);
case 36:
apply("CREATE TABLE IF NOT EXISTS peer (address VARCHAR PRIMARY KEY)");
case 37:
if (!Constants.isTestnet) {
apply("INSERT INTO peer (address) VALUES " +
"('77.179.106.9'), ('110.143.228.78'), ('54.72.7.96'), ('54.86.139.231'), " +
"('abctc.vps.nxtcrypto.org'), ('nxt.pucchiwerk.eu'), ('185.4.72.115'), ('vps4.nxtcrypto.org'), " +
"('89.250.240.63'), ('162.243.145.83'), ('85.10.199.79'), ('89.70.254.145'), " +
"('103.224.81.143'), ('85.181.230.69'), ('198.199.85.20'), ('217.17.88.5'), " +
"('109.87.169.253'), ('87.172.190.182'), ('67.149.193.205'), ('31.15.211.201'), " +
"('178.24.158.31'), ('46.4.77.180'), ('188.226.242.50'), ('108.170.40.2'), ('217.117.208.17'), " +
"('89.250.243.150'), ('178.26.207.190'), ('wallet.nxtty.com'), ('nxtnet.fr'), " +
"('188.194.241.72'), ('nxt.alkeron.com'), ('xyzzyx.vps.nxtcrypto.org'), ('69.207.170.32'), " +
"('bitsy02.vps.nxtcrypto.org'), ('83.240.14.35'), ('212.85.38.25'), ('212.85.38.103'), " +
"('vps9.nxtcrypto.org'), ('84.241.44.180'), ('158.195.217.79'), ('89.133.34.109'), " +
"('stakexplorer.com'), ('198.27.64.207'), ('vps5.nxtcrypto.org'), ('185.12.44.108'), " +
"('nxtcoin.ru'), ('vps6.nxtcrypto.org'), ('92.129.239.166'), ('91.69.121.229'), " +
"('nxtpi.zapto.org'), ('92.228.252.60'), ('216.8.180.222'), ('bitsy05.vps.nxtcrypto.org'), " +
"('88.198.142.92'), ('31.19.188.145'), ('54.186.135.231'), ('ankhy.no-ip.biz'), " +
"('94.26.187.66'), ('bitsy01.vps.nxtcrypto.org'), ('bitsy04.vps.nxtcrypto.org'), " +
"('90.188.4.177'), ('88.184.64.208'), ('raspnxt.hopto.org'), ('151.236.29.228'), " +
"('188.138.88.154'), ('nxt.homer.ru'), ('107.170.208.249'), ('31.150.173.6'), " +
"('vps10.nxtcrypto.org'), ('bitsy03.vps.nxtcrypto.org'), ('xeqtorcreed2.vps.nxtcrypto.org'), " +
"('lyynx.vps.nxtcrypto.org'), ('146.185.145.192'), ('37.138.105.143'), ('162.220.167.190'), " +
"('94.74.170.10'), ('vps7.nxtcrypto.org'), ('nxt01.now.im'), ('2.225.88.10'), " +
"('85.214.222.82'), ('vps8.nxtcrypto.org'), ('178.122.5.83'), ('88.160.247.181'), " +
"('85.229.150.2'), ('158.195.19.226'), ('nxt.ravensbloodrealms.com'), ('105.229.251.144'), " +
"('nxt.olxp.in'), ('37.59.47.155'), ('nxtportal.org'), ('87.198.219.221'), ('87.172.180.199'), " +
"('36.74.56.184'), ('nxtx.ru'), ('58.95.145.117'), ('109.230.224.65'), ('www.pagezo.de'), " +
"('allbits.vps.nxtcrypto.org'), ('107.170.3.62'), ('192.157.244.160'), ('vps12.nxtcrypto.org'), " +
"('nacho.damnserver.com'), ('67.212.71.173'), ('vps11.nxtcrypto.org'), ('miasik.no-ip.org'), " +
"('212.85.37.150'), ('217.26.24.27'), ('24.161.110.115'), ('89.70.164.196'), ('46.28.111.249'), " +
"('vps1.nxtcrypto.org'), ('199.195.148.27'), ('176.226.191.152'), " +
"('37.44.107.50'), ('95.143.216.60'), ('62.57.125.237'), ('xeqtorcreed.vps.nxtcrypto.org')");
} else {
apply("INSERT INTO peer (address) VALUES " +
"('109.87.169.253'), ('nxtnet.fr'), ('node10.mynxtcoin.org'), ('50.112.241.97'), " +
"('node9.mynxtcoin.org'), ('2.84.142.149'), ('192.241.223.132'), ('node3.mynxtcoin.org'), " +
"('bug.airdns.org')");
}
case 38:
apply("ALTER TABLE transaction ADD COLUMN IF NOT EXISTS full_hash BINARY(32)");
case 39:
apply("ALTER TABLE transaction ADD COLUMN IF NOT EXISTS referenced_transaction_full_hash BINARY(32)");
case 40:
apply(null);
case 41:
apply("ALTER TABLE transaction ALTER COLUMN full_hash SET NOT NULL");
case 42:
apply("CREATE UNIQUE INDEX IF NOT EXISTS transaction_full_hash_idx ON transaction (full_hash)");
case 43:
apply(null);
case 44:
apply(null);
case 45:
apply(null);
case 46:
apply("ALTER TABLE transaction ADD COLUMN IF NOT EXISTS attachment_bytes VARBINARY");
case 47:
BlockDb.deleteAll();
apply(null);
case 48:
apply("ALTER TABLE transaction DROP COLUMN attachment");
case 49:
apply("UPDATE transaction a SET a.referenced_transaction_full_hash = "
+ "(SELECT full_hash FROM transaction b WHERE b.id = a.referenced_transaction_id) "
+ "WHERE a.referenced_transaction_full_hash IS NULL");
case 50:
apply("ALTER TABLE transaction DROP COLUMN referenced_transaction_id");
case 51:
apply("ALTER TABLE transaction DROP COLUMN hash");
case 52:
return;
default:
throw new RuntimeException("Database inconsistent with code, probably trying to run older code on newer database");
}
}
private DbVersion() {} //never
}
|
package com.emc.mongoose.tests.system.base;
import com.emc.mongoose.api.common.SizeInBytes;
import com.emc.mongoose.api.common.concurrent.Daemon;
import com.emc.mongoose.api.model.data.DataInput;
import com.emc.mongoose.storage.driver.builder.StorageDriverBuilderSvc;
import com.emc.mongoose.storage.driver.service.BasicStorageDriverBuilderSvc;
import com.emc.mongoose.storage.mock.impl.http.StorageMockFactory;
import com.emc.mongoose.ui.config.item.ItemConfig;
import com.emc.mongoose.ui.config.item.data.input.InputConfig;
import com.emc.mongoose.ui.config.item.naming.NamingConfig;
import com.emc.mongoose.ui.config.storage.StorageConfig;
import com.emc.mongoose.ui.config.storage.driver.DriverConfig;
import com.emc.mongoose.ui.config.storage.mock.MockConfig;
import com.emc.mongoose.ui.config.storage.mock.container.ContainerConfig;
import com.emc.mongoose.ui.config.storage.mock.fail.FailConfig;
import com.emc.mongoose.ui.config.storage.net.NetConfig;
import com.emc.mongoose.ui.config.storage.net.node.NodeConfig;
import com.emc.mongoose.ui.config.test.step.StepConfig;
import com.emc.mongoose.ui.log.Loggers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EnvConfiguredTestBase
extends ConfiguredTestBase {
// environment parameter names
public static final String KEY_ENV_STORAGE_DRIVER_TYPE = "STORAGE_DRIVER_TYPE";
public static final String KEY_ENV_STORAGE_DRIVER_COUNT = "STORAGE_DRIVER_COUNT";
public static final String KEY_ENV_STORAGE_DRIVER_CONCURRENCY = "STORAGE_DRIVER_CONCURRENCY";
public static final String KEY_ENV_ITEM_DATA_SIZE = "ITEM_DATA_SIZE";
// parameter values to be set
protected static String STORAGE_DRIVER_TYPE = null;
protected static boolean DISTRIBUTED_MODE_FLAG = false;
protected static int CONCURRENCY = 0;
protected static SizeInBytes ITEM_DATA_SIZE = null;
// test exclusion mechanism
protected static final Map<String, List<Object>> EXCLUDE_PARAMS = new HashMap<>();
protected static boolean SKIP_FLAG = false;
protected static Map<String, Daemon> HTTP_STORAGE_MOCKS = null;
protected static int HTTP_STORAGE_NODE_COUNT = 1;
protected static int STORAGE_DRIVERS_COUNT;
private static List<StorageDriverBuilderSvc> STORAGE_DRIVER_BUILDER_SVCS = null;
protected static final String STORAGE_TYPE_FS = "fs";
protected static final String STORAGE_TYPE_ATMOS = "atmos";
protected static final String STORAGE_TYPE_S3 = "s3";
protected static final String STORAGE_TYPE_SWIFT = "swift";
@BeforeClass
public static void setUpClass()
throws Exception {
ConfiguredTestBase.setUpClass();
final Map<String, String> env = System.getenv();
if(!env.containsKey(KEY_ENV_STORAGE_DRIVER_TYPE)) {
throw new IllegalArgumentException(
"Environment property w/ name \"" + KEY_ENV_STORAGE_DRIVER_TYPE +
"\" is not defined"
);
}
STORAGE_DRIVER_TYPE = System.getenv(KEY_ENV_STORAGE_DRIVER_TYPE);
checkExclusionAndSetFlag(KEY_ENV_STORAGE_DRIVER_TYPE, STORAGE_DRIVER_TYPE);
if(!env.containsKey(KEY_ENV_STORAGE_DRIVER_COUNT)) {
throw new IllegalArgumentException(
"Environment property w/ name \"" + KEY_ENV_STORAGE_DRIVER_COUNT +
"\" is not defined"
);
}
STORAGE_DRIVERS_COUNT = Integer.parseInt(System.getenv(KEY_ENV_STORAGE_DRIVER_COUNT));
DISTRIBUTED_MODE_FLAG = STORAGE_DRIVERS_COUNT > 1;
checkExclusionAndSetFlag(KEY_ENV_STORAGE_DRIVER_COUNT, DISTRIBUTED_MODE_FLAG);
if(!env.containsKey(KEY_ENV_STORAGE_DRIVER_CONCURRENCY)) {
throw new IllegalArgumentException(
"Environment property w/ name \"" + KEY_ENV_STORAGE_DRIVER_CONCURRENCY +
"\" is not defined"
);
}
CONCURRENCY = Integer.parseInt(System.getenv(KEY_ENV_STORAGE_DRIVER_CONCURRENCY));
checkExclusionAndSetFlag(KEY_ENV_STORAGE_DRIVER_CONCURRENCY, CONCURRENCY);
if(!env.containsKey(KEY_ENV_ITEM_DATA_SIZE)) {
throw new IllegalArgumentException(
"Environment property w/ name \"" + KEY_ENV_ITEM_DATA_SIZE + "\" is not defined"
);
}
ITEM_DATA_SIZE = new SizeInBytes(System.getenv(KEY_ENV_ITEM_DATA_SIZE));
checkExclusionAndSetFlag(KEY_ENV_ITEM_DATA_SIZE, ITEM_DATA_SIZE);
Loggers.MSG.info("* Storage type: {}", STORAGE_DRIVER_TYPE);
Loggers.MSG.info("* Distributed mode: {}", DISTRIBUTED_MODE_FLAG);
Loggers.MSG.info("* Concurrency: {}", CONCURRENCY);
Loggers.MSG.info("* Items size: {}", ITEM_DATA_SIZE);
Loggers.MSG.info("* Excluded: {}", SKIP_FLAG);
if(SKIP_FLAG) {
return;
}
setUpStorageMockIfNeeded();
setUpDistributedModeIfNeeded();
setUpConcurrency();
setUpItemDataSize();
}
@AfterClass
public static void tearDownClass()
throws Exception {
if(! SKIP_FLAG) {
tearDownStorageMockIfNeeded();
tearDownDistributedModeIfNeeded();
}
ConfiguredTestBase.tearDownClass();
}
private static void checkExclusionAndSetFlag(final String name, final Object value) {
final List<Object> excludeParams = EXCLUDE_PARAMS.get(name);
SKIP_FLAG = false;
if(excludeParams != null && !excludeParams.isEmpty()) {
for(final Object nextExcludeParam : excludeParams) {
if(nextExcludeParam.equals(value)) {
System.out.println("Test excluded for the " + name + "=" + value);
SKIP_FLAG = true;
break;
}
}
}
}
private static void setUpStorageMockIfNeeded()
throws Exception {
final StorageConfig storageConfig = CONFIG.getStorageConfig();
storageConfig.getDriverConfig().setType(STORAGE_DRIVER_TYPE);
switch(STORAGE_DRIVER_TYPE) {
case STORAGE_TYPE_ATMOS:
case STORAGE_TYPE_S3:
case STORAGE_TYPE_SWIFT:
HTTP_STORAGE_MOCKS = new HashMap<>();
final NodeConfig nodeConfig = storageConfig.getNetConfig().getNodeConfig();
final ItemConfig itemConfig = CONFIG.getItemConfig();
final StepConfig stepConfig = CONFIG.getTestConfig().getStepConfig();
final int port = nodeConfig.getPort();
final List<String> nodeAddrs = new ArrayList<>();
String nextNodeAddr;
Daemon storageMock;
final MockConfig mockConfig = storageConfig.getMockConfig();
final NetConfig netConfig = storageConfig.getNetConfig();
final ContainerConfig containerConfig = mockConfig.getContainerConfig();
final FailConfig failConfig = mockConfig.getFailConfig();
final NamingConfig namingConfig = itemConfig.getNamingConfig();
final InputConfig dataInputConfig = itemConfig.getDataConfig().getInputConfig();
final DataInput dataInput = DataInput.getInstance(
dataInputConfig.getFile(), dataInputConfig.getSeed(),
dataInputConfig.getLayerConfig().getSize(),
dataInputConfig.getLayerConfig().getCache()
);
StorageMockFactory storageMockFactory;
for(int i = 0; i < HTTP_STORAGE_NODE_COUNT; i ++) {
nodeConfig.setPort(port + i);
storageMockFactory = new StorageMockFactory(
itemConfig.getInputConfig().getFile(), mockConfig.getCapacity(),
containerConfig.getCapacity(), containerConfig.getCountLimit(),
(int) CONFIG.getOutputConfig().getMetricsConfig().getAverageConfig().getPeriod(),
failConfig.getConnections(), failConfig.getResponses(), dataInput,
netConfig.getNodeConfig().getPort(), netConfig.getSsl(),
(float) CONFIG.getLoadConfig().getRateConfig().getLimit(),
namingConfig.getPrefix(), namingConfig.getRadix()
);
storageMock = storageMockFactory.newStorageMock();
nextNodeAddr = "127.0.0.1:" + (port + i);
storageMock.start();
HTTP_STORAGE_MOCKS.put(nextNodeAddr, storageMock);
nodeAddrs.add(nextNodeAddr);
}
nodeConfig.setAddrs(nodeAddrs);
nodeConfig.setPort(port);
break;
case STORAGE_TYPE_FS:
break;
}
}
private static void tearDownStorageMockIfNeeded()
throws Exception {
if(HTTP_STORAGE_MOCKS != null) {
for(final Daemon storageMock : HTTP_STORAGE_MOCKS.values()) {
storageMock.close();
}
HTTP_STORAGE_MOCKS.clear();
HTTP_STORAGE_MOCKS = null;
}
}
private static void setUpDistributedModeIfNeeded()
throws Exception {
if(DISTRIBUTED_MODE_FLAG) {
STORAGE_DRIVER_BUILDER_SVCS = new ArrayList<>(STORAGE_DRIVERS_COUNT);
final DriverConfig driverConfig = CONFIG.getStorageConfig().getDriverConfig();
final List<String> storageDriverAddrs = new ArrayList<>(STORAGE_DRIVERS_COUNT);
int nextStorageDriverPort;
StorageDriverBuilderSvc nextStorageDriverBuilder;
for(int i = 0; i < STORAGE_DRIVERS_COUNT; i ++) {
nextStorageDriverPort = driverConfig.getPort() + i;
nextStorageDriverBuilder = new BasicStorageDriverBuilderSvc(nextStorageDriverPort);
nextStorageDriverBuilder.start();
STORAGE_DRIVER_BUILDER_SVCS.add(nextStorageDriverBuilder);
storageDriverAddrs.add("127.0.0.1:" + nextStorageDriverPort);
}
driverConfig.setAddrs(storageDriverAddrs);
driverConfig.setRemote(true);
}
}
private static void tearDownDistributedModeIfNeeded()
throws Exception {
if(DISTRIBUTED_MODE_FLAG && STORAGE_DRIVER_BUILDER_SVCS != null) {
for(final StorageDriverBuilderSvc svc : STORAGE_DRIVER_BUILDER_SVCS) {
svc.close();
}
STORAGE_DRIVER_BUILDER_SVCS.clear();
STORAGE_DRIVER_BUILDER_SVCS = null;
}
}
private static void setUpConcurrency()
throws Exception {
if(CONCURRENCY < 1) {
throw new IllegalArgumentException("Concurrency level should be an integer > 0");
}
CONFIG.getStorageConfig().getDriverConfig().setConcurrency(CONCURRENCY);
}
private static void setUpItemDataSize()
throws Exception {
CONFIG.getItemConfig().getDataConfig().setSize(ITEM_DATA_SIZE);
}
}
|
package me.thekey.android.lib.dialog;
import android.app.Activity;
import me.thekey.android.lib.CodeGrantAsyncTask;
import me.thekey.android.lib.TheKeyImpl;
import me.thekey.android.lib.fragment.DialogFragment;
public final class LoginDialogCodeGrantAsyncTask extends CodeGrantAsyncTask {
final DialogFragment dialog;
public LoginDialogCodeGrantAsyncTask(final DialogFragment dialog, final TheKeyImpl thekey) {
super(thekey);
this.dialog = dialog;
}
@SuppressWarnings("unchecked")
@Override
protected void onPostExecute(final Boolean result) {
super.onPostExecute(result);
final Activity activity = this.dialog.getActivity();
if (activity instanceof LoginDialogListener) {
// trigger the correct callback
if (result) {
((LoginDialogListener<DialogFragment>) activity).onLoginSuccess(dialog, this.thekey.getGuid());
} else {
((LoginDialogListener<DialogFragment>) activity).onLoginFailure(dialog);
}
}
// close the dialog if it is still active (added to the activity)
if (this.dialog.isAdded()) {
this.dialog.dismissAllowingStateLoss();
}
}
}
|
package jfmi.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.MatteBorder;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import jfmi.app.TaggedFile;
import jfmi.app.TaggedFileSorters;
import jfmi.control.JFMIApp;
import jfmi.control.TaggedFileHandler;
import jfmi.control.FileTagHandler;
import jfmi.control.FileTaggingHandler;
/** A JFMIFrame acts as the parent Swing Component for the JFMI application's
GUI. All other graphical components treat a JFMIFrame as their parent.
*/
public class JFMIFrame extends JFrame implements ActionListener {
private static final String FRAME_TITLE = "JFMI";
private static final Dimension FRAME_DIMENSION = new Dimension(800, 600);
private JPanel contentPanel;
private SortOptionsBox fileSortBox;
private SortedSet<String> sortFields;
private SortedSet<String> sortOrders;
// Button related
private Box buttonBox; // Holds buttons
private JButton manageTagsButton;
private JButton addFileButton;
private JButton editFileButton;
private JButton showFileButton;
private JButton deleteFilesButton;
// List related
private JScrollPane taggedFileScroller; // Holds the taggedFileJList
private JList<TaggedFile> taggedFileJList;
private TaggedFileListModel listModel;
// Controller related
private JFMIApp jfmiApp;
/** Constructs a JFMIFrame with the specified JFMIApp as its controller.
@param jfmiApp_ JFMIApp that will act as this instance's controller.
*/
public JFMIFrame(JFMIApp jfmiApp_)
{
// Initialize instance
super(FRAME_TITLE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(FRAME_DIMENSION);
setJFMIApp(jfmiApp_);
// Initialize sorting option sets
sortFields = new TreeSet<String>();
sortFields.add("Name");
sortFields.add("Path");
sortOrders = new TreeSet<String>();
sortOrders.add("Ascending (A-Z)");
sortOrders.add("Descending (Z-A)");
// Initialize child components
initContentPanel();
setContentPane(contentPanel);
initButtonBox();
initTagScroller();
add(buttonBox, BorderLayout.WEST);
add(taggedFileScroller, BorderLayout.CENTER);
// Do not display initially
setVisible(false);
}
/** Prompts a user to confirm an action with the specified message, and
returns the user's decision.
@param confirmMsg the message to display to the user
@return true if the user confirmed
*/
public boolean getConfirmation(String confirmMsg)
{
int choice = JOptionPane.showConfirmDialog(this, confirmMsg,
"Please Provide Confirmation",
JOptionPane.OK_CANCEL_OPTION);
return choice == JOptionPane.OK_OPTION;
}
public void setTaggedFileJListData(Vector<TaggedFile> vector)
{
if (vector == null) {
throw new IllegalArgumentException("vector cannot be null");
}
// Set up the model and apply it to the list
listModel = new TaggedFileListModel(vector);
taggedFileJList.setModel(listModel);
// Sort the list
sortTaggedFileJList(new TaggedFileSorters.FileNameSorter());
}
/** Sorts the displayed list of TaggedFiles using the specified Comparator.
@param c the Comparator to sort the files with
*/
public void sortTaggedFileJList(Comparator<TaggedFile> c)
{
listModel.sort(c);
}
/** Initializes the contentPanel field.
*/
private final void initContentPanel()
{
contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
}
/** Initialize the buttonBox field.
*/
private final void initButtonBox()
{
// Initialize buttons
JLabel tagsLabel = new JLabel("Tag Options");
tagsLabel.setForeground(Color.DARK_GRAY);
tagsLabel.setFont(Styles.SS_PLAIN_16);
tagsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
manageTagsButton = new JButton("Manage Tags..");
manageTagsButton.addActionListener(this);
manageTagsButton.setAlignmentX(Component.CENTER_ALIGNMENT);
Styles.setDefaultJButtonStyles(manageTagsButton);
JLabel filesLabel = new JLabel("File Options");
filesLabel.setForeground(Color.DARK_GRAY);
filesLabel.setFont(Styles.SS_PLAIN_16);
filesLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
addFileButton = new JButton("Add New File");
addFileButton.addActionListener(this);
addFileButton.setAlignmentX(Component.CENTER_ALIGNMENT);
Styles.setDefaultJButtonStyles(addFileButton);
editFileButton = new JButton("Edit File");
editFileButton.addActionListener(this);
editFileButton.setAlignmentX(Component.CENTER_ALIGNMENT);
Styles.setDefaultJButtonStyles(editFileButton);
showFileButton = new JButton("Show In Directory");
showFileButton.addActionListener(this);
showFileButton.setAlignmentX(Component.CENTER_ALIGNMENT);
Styles.setDefaultJButtonStyles(showFileButton);
deleteFilesButton = new JButton("Delete Selected Files");
deleteFilesButton.addActionListener(this);
deleteFilesButton.setAlignmentX(Component.CENTER_ALIGNMENT);
Styles.setDefaultJButtonStyles(deleteFilesButton);
deleteFilesButton.setForeground(Styles.DANGER_COLOR);
// Initialize sorting box
JLabel sortLabel = new JLabel("Sort Options");
sortLabel.setForeground(Color.DARK_GRAY);
sortLabel.setFont(Styles.SS_PLAIN_16);
sortLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
fileSortBox = new SortOptionsBox(sortFields, sortOrders);
fileSortBox.setOpaque(false);
fileSortBox.setAlignmentX(Component.CENTER_ALIGNMENT);
// Initialize buttonBox
buttonBox = new Box(BoxLayout.Y_AXIS);
buttonBox.setBackground(Styles.DEFAULT_BG_COLOR);
buttonBox.setOpaque(true);
buttonBox.add(Box.createVerticalStrut(10));
buttonBox.add(tagsLabel);
buttonBox.add(Box.createVerticalStrut(10));
buttonBox.add(manageTagsButton);
buttonBox.add(Box.createVerticalStrut(50));
buttonBox.add(filesLabel);
buttonBox.add(Box.createVerticalStrut(10));
buttonBox.add(addFileButton);
buttonBox.add(Box.createVerticalStrut(5));
buttonBox.add(editFileButton);
buttonBox.add(Box.createVerticalStrut(5));
buttonBox.add(Box.createVerticalStrut(5));
buttonBox.add(showFileButton);
buttonBox.add(Box.createVerticalStrut(5));
buttonBox.add(deleteFilesButton);
buttonBox.add(Box.createVerticalStrut(50));
buttonBox.add(sortLabel);
buttonBox.add(Box.createVerticalStrut(10));
buttonBox.add(fileSortBox);
}
/** Initialize the scrollPane field.
*/
private final void initTagScroller()
{
// Instantiate the taggedFileJList
listModel = new TaggedFileListModel();
taggedFileJList = new JList<TaggedFile>(listModel);
taggedFileJList.setLayoutOrientation(JList.VERTICAL);
taggedFileJList.setCellRenderer(new TaggedFileJListRenderer());
// Initialize the scroll pane
taggedFileScroller = new JScrollPane(taggedFileJList);
}
/** Mutator for the jfmiApp field.
@param jfmiApp_ JFMIApp instance to set as this instance's controller.
*/
private final void setJFMIApp(JFMIApp jfmiApp_)
{
if (jfmiApp_ == null) {
throw new IllegalArgumentException("jfmiApp field cannot be null");
}
jfmiApp = jfmiApp_;
}
/** Responds to various ActionEvent events.
@param e An ActionEvent generated by the user on some child component of
JFMIFrame.
*/
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == manageTagsButton) {
jfmiApp.getTagHandler().beginManageTags();
} else if (src == addFileButton) {
jfmiApp.getFileHandler().beginAddFile();
} else if (src == editFileButton) {
TaggedFile selectedFile = taggedFileJList.getSelectedValue();
if (selectedFile != null) {
jfmiApp.getFileHandler().beginEditFile(selectedFile);
} else {
GUIUtil.showAlert("No file selected.");
}
} else if (src == showFileButton) {
TaggedFile selectedFile = taggedFileJList.getSelectedValue();
if (selectedFile != null) {
jfmiApp.getFileHandler().beginShowInDirectory(selectedFile);
} else {
GUIUtil.showAlert("No file selected.");
}
} else if (src == deleteFilesButton) {
List<TaggedFile> files = taggedFileJList.getSelectedValuesList();
jfmiApp.getFileHandler().beginDeleteFiles(files);
}
}
}
|
package org.project.openbaton.clients.interfaces;
import org.project.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.project.openbaton.catalogue.nfvo.*;
import org.project.openbaton.clients.exceptions.VimDriverException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
public interface ClientInterfaces {
/**
* This version must match the version of the plugin...
*/
String interfaceVersion = "1.0";
Server launchInstance(VimInstance vimInstance, String name, String image, String flavor, String keypair, Set<String> network, Set<String> secGroup, String userData);
// void init(VimInstance vimInstance);
List<NFVImage> listImages(VimInstance vimInstance);
List<Server> listServer(VimInstance vimInstance);
List<Network> listNetworks(VimInstance vimInstance);
List<DeploymentFlavour> listFlavors(VimInstance vimInstance);
Server launchInstanceAndWait(VimInstance vimInstance, String hostname, String image, String extId, String keyPair, Set<String> networks, Set<String> securityGroups, String s) throws VimDriverException;
void deleteServerByIdAndWait(String id, VimInstance vimInstance);
Network createNetwork(VimInstance vimInstance, Network network);
DeploymentFlavour addFlavor(VimInstance vimInstance, DeploymentFlavour deploymentFlavour);
NFVImage addImage(VimInstance vimInstance, NFVImage image, InputStream inputStream);
NFVImage updateImage(VimInstance vimInstance, NFVImage image);
NFVImage copyImage(VimInstance vimInstance, NFVImage image, InputStream inputStream);
boolean deleteImage(VimInstance vimInstance, NFVImage image);
DeploymentFlavour updateFlavor(VimInstance vimInstance, DeploymentFlavour deploymentFlavour) throws VimDriverException;
boolean deleteFlavor(VimInstance vimInstance, String extId);
Subnet createSubnet(VimInstance vimInstance, Network createdNetwork, Subnet subnet);
Network updateNetwork(VimInstance vimInstance, Network network);
Subnet updateSubnet(VimInstance vimInstance, Network updatedNetwork, Subnet subnet);
List<String> getSubnetsExtIds(VimInstance vimInstance, String network_extId);
boolean deleteSubnet(VimInstance vimInstance, String existingSubnetExtId);
boolean deleteNetwork(VimInstance vimInstance, String extId);
Network getNetworkById(VimInstance vimInstance, String id);
Quota getQuota(VimInstance vimInstance);
String getType(VimInstance vimInstance);
}
|
package edu.northwestern.bioinformatics.studycalendar.web;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.domain.Period;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedCalendar;
import edu.northwestern.bioinformatics.studycalendar.domain.Population;
import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivity;
import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledCalendar;
import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledStudySegment;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment;
import edu.northwestern.bioinformatics.studycalendar.domain.User;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateService;
import edu.northwestern.bioinformatics.studycalendar.tools.FormatTools;
import gov.nih.nci.cabig.ctms.dao.GridIdentifiableDao;
import gov.nih.nci.cabig.ctms.editors.DaoBasedEditor;
import gov.nih.nci.cabig.ctms.editors.GridIdentifiableDaoBasedEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditor;
import java.io.IOException;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class ControllerTools {
private TemplateService templateService;
public PropertyEditor getDateEditor(boolean required) {
// note that date formats are not threadsafe, so we have to create a new one each time
return new DateCustomEditor(FormatTools.getLocal().getDateFormat(), !required);
}
public void registerDomainObjectEditor(ServletRequestDataBinder binder, String field, StudyCalendarDao<?> dao) {
DaoBasedEditor editor;
if (dao instanceof GridIdentifiableDao) {
editor = new GridIdentifiableDaoBasedEditor((GridIdentifiableDao<?>) dao);
} else {
editor = new DaoBasedEditor(dao);
}
binder.registerCustomEditor(dao.domainClass(), field, editor);
}
public void addHierarchyToModel(ScheduledActivity event, Map<String, Object> model) {
model.put("scheduledActivity", event);
if (event != null) {
addHierarchyToModel(event.getPlannedActivity(), model);
addHierarchyToModel(event.getScheduledStudySegment(), model);
}
}
public void addHierarchyToModel(ScheduledStudySegment studySegment, Map<String, Object> model) {
model.put("scheduledStudySegment", studySegment);
if (studySegment != null) {
addHierarchyToModel(studySegment.getStudySegment(), model);
addHierarchyToModel(studySegment.getScheduledCalendar(), model);
}
}
public void addHierarchyToModel(ScheduledCalendar calendar, Map<String, Object> model) {
model.put("scheduledCalendar", calendar);
if (calendar != null) {
addHierarchyToModel(calendar.getAssignment().getStudySite().getStudy().getPlannedCalendar(), model);
addHierarchyToModel(calendar.getAssignment(), model);
}
}
public void addHierarchyToModel(StudySubjectAssignment assignment, Map<String, Object> model) {
model.put("assignment", assignment);
if (assignment != null) {
model.put("subject", assignment.getSubject());
model.put("scheduledCalendar", assignment.getScheduledCalendar());
addToModel(assignment.getStudySite(), model);
}
}
public void addHierarchyToModel(PlannedActivity event, Map<String, Object> model) {
model.put("plannedActivity", event);
if (event != null) addHierarchyToModel(templateService.findParent(event), model);
}
public void addHierarchyToModel(Period period, Map<String, Object> model) {
model.put("period", period);
if (period != null) addHierarchyToModel(templateService.findParent(period), model);
}
public void addHierarchyToModel(StudySegment studySegment, Map<String, Object> model) {
model.put("studySegment", studySegment);
if (studySegment != null) addHierarchyToModel(templateService.findParent(studySegment), model);
}
public void addHierarchyToModel(Epoch epoch, Map<String, Object> model) {
model.put("epoch", epoch);
if (epoch != null) addHierarchyToModel(templateService.findParent(epoch), model);
}
public void addHierarchyToModel(PlannedCalendar plannedCalendar, Map<String, Object> model) {
model.put("plannedCalendar", plannedCalendar);
if (plannedCalendar != null) addHierarchyToModel(plannedCalendar.getStudy(), model);
}
public void addHierarchyToModel(Study study, Map<String, Object> model) {
model.put("study", study);
}
public void addToModel(StudySite studySite, Map<String, Object> model) {
model.put("studySite", studySite);
model.put("study", studySite.getStudy());
model.put("site", studySite.getSite());
}
public void addToModel(Population population, Map<String, Object> model) {
model.put("population", population);
addHierarchyToModel(population.getStudy(), model);
}
public boolean isAjaxRequest(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
return header != null && "XMLHttpRequest".equals(header);
}
public ModelAndView redirectToCalendarTemplate(int studyId) {
return redirectToCalendarTemplate(studyId, null);
}
@SuppressWarnings({ "unchecked" })
public ModelAndView redirectToCalendarTemplate(int studyId, Integer selectedStudySegmentId) {
return redirectToCalendarTemplate(studyId, selectedStudySegmentId, null);
}
@SuppressWarnings({ "unchecked" })
public ModelAndView redirectToCalendarTemplate(int studyId, Integer selectedStudySegmentId, Integer selectedAmendmentId) {
ModelMap model = new ModelMap("study", studyId);
if (selectedStudySegmentId != null) model.put("studySegment", selectedStudySegmentId);
if (selectedAmendmentId != null) model.put("amendment", selectedAmendmentId);
return new ModelAndView("redirectToCalendarTemplate", model);
}
public ModelAndView redirectToSchedule(int assignmentId) {
ModelMap model = new ModelMap("assignment", assignmentId);
return new ModelAndView("redirectToSchedule", model);
}
// note that if you change the error message here, you need to change it in error-console.js, too
public void sendPostOnlyError(HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "POST is the only valid method for this URL");
}
// note that if you change the error message here, you need to change it in error-console.js, too
public void sendGetOnlyError(HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET is the only valid method for this URL");
}
/**
* @see UserInRequestFilter
*/
public User getCurrentUser(HttpServletRequest request) {
return (User) request.getAttribute("currentUser");
}
////// CONFIGURATION
public void setTemplateService(TemplateService templateService) {
this.templateService = templateService;
}
}
|
package org.knowm.xchange.okcoin.v3.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.FundingRecord;
import org.knowm.xchange.dto.account.FundingRecord.Type;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.okcoin.OkexAdaptersV3;
import org.knowm.xchange.okcoin.OkexExchangeV3;
import org.knowm.xchange.okcoin.v3.dto.account.OkexFundingAccountRecord;
import org.knowm.xchange.okcoin.v3.dto.account.OkexSpotAccountRecord;
import org.knowm.xchange.okcoin.v3.dto.account.OkexWithdrawalRequest;
import org.knowm.xchange.okcoin.v3.dto.account.OkexWithdrawalResponse;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.HistoryParamsFundingType;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.WithdrawFundsParams;
public class OkexAccountService extends OkexAccountServiceRaw implements AccountService {
public OkexAccountService(OkexExchangeV3 exchange) {
super(exchange);
}
@Override
public AccountInfo getAccountInfo() throws IOException {
List<OkexFundingAccountRecord> funding = super.fundingAccountInformation();
Collection<Balance> fundingBalances =
funding.stream().map(OkexAdaptersV3::convert).collect(Collectors.toList());
List<OkexSpotAccountRecord> spotTradingAccount = super.spotTradingAccount();
Collection<Balance> tradingBalances =
spotTradingAccount.stream().map(OkexAdaptersV3::convert).collect(Collectors.toList());
/*
* commented out, since using this method we are running into [30014] Too Many Requests
FuturesAccountsResponse futuresAccounts = super.getFuturesAccounts();
Collection<Balance> futuresBalances =
futuresAccounts.getInfo().getAccounts().entrySet().stream()
.map(e -> OkexAdaptersV3.convert(e.getKey(), e.getValue()))
.collect(Collectors.toList());
List<SwapAccountInfo> swapAccounts = super.getSwapAccounts();
Collection<Balance> swapBalances =
swapAccounts.stream().map(OkexAdaptersV3::convert).collect(Collectors.toList());*/
return new AccountInfo(
Wallet.Builder.from(fundingBalances)
.id("Funding")
.features(Stream.of(Wallet.WalletFeature.FUNDING).collect(Collectors.toSet()))
.build(),
Wallet.Builder.from(tradingBalances)
.id("Trading")
.features(Stream.of(Wallet.WalletFeature.TRADING).collect(Collectors.toSet()))
.build());
}
@Override
public String withdrawFunds(WithdrawFundsParams params) throws IOException {
if (params instanceof DefaultWithdrawFundsParams) {
DefaultWithdrawFundsParams p = (DefaultWithdrawFundsParams) params;
return withdrawFunds0(p.currency, p.amount, p.address, p.commission);
}
throw new IllegalStateException("Don't know how to withdraw: " + params);
}
@Override
public String withdrawFunds(Currency currency, BigDecimal amount, String address)
throws IOException {
return withdrawFunds0(currency, amount, address, null);
}
private String withdrawFunds0(
Currency currency, BigDecimal amount, String address, BigDecimal fee) throws IOException {
if (fee == null) {
fee = getStaticFee(currency.getCurrencyCode());
}
OkexWithdrawalRequest req =
OkexWithdrawalRequest.builder()
.currency(currency.getCurrencyCode())
.amount(amount)
.destination("4") // 4:others
.fee(fee)
.toAddress(address)
.tradePwd(tradepwd)
.build();
OkexWithdrawalResponse withdrawal = withdrawal(req);
return withdrawal.getWithdrawalId();
}
public BigDecimal getStaticFee(String currency) {
CurrencyMetaData cmd =
this.exchange.getExchangeMetaData().getCurrencies().get(Currency.getInstance(currency));
if (cmd == null || cmd.getWithdrawalFee() == null) {
throw new IllegalArgumentException("Unsupported withdraw currency " + currency);
}
return cmd.getWithdrawalFee();
}
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException {
boolean withdrawals = true, deposits = true;
if (params instanceof HistoryParamsFundingType) {
HistoryParamsFundingType p = (HistoryParamsFundingType) params;
withdrawals = p.getType() == null || p.getType() == Type.WITHDRAWAL;
deposits = p.getType() == null || p.getType() == Type.DEPOSIT;
}
List<FundingRecord> result = new ArrayList<>();
if (withdrawals) {
result.addAll(
recentWithdrawalHistory().stream()
.map(OkexAdaptersV3::adaptFundingRecord)
.collect(Collectors.toList()));
}
if (deposits) {
result.addAll(
recentDepositHistory().stream()
.map(OkexAdaptersV3::adaptFundingRecord)
.collect(Collectors.toList()));
}
Collections.sort(result, (r1, r2) -> r1.getDate().compareTo(r2.getDate()));
return result;
}
}
|
package com.thoughtworks.xstream.converters.reflection;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.alias.ImplicitCollectionMapper;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ReflectionConverter implements Converter {
private ClassMapper classMapper;
private String classAttributeIdentifier;
private String definedInAttributeIdentifier = "defined-in";
private ReflectionProvider reflectionProvider;
private ImplicitCollectionMapper implicitCollectionMapper;
private InstanceResolver instanceResolver;
private Map writeObjectMethodCache = new HashMap(); // should be soft but Joe told me off - DN
public ReflectionConverter(ClassMapper classMapper, String classAttributeIdentifier, String definedInAttributeIdentifier,
ReflectionProvider reflectionProvider, ImplicitCollectionMapper implicitCollectionMapper) {
this.classMapper = classMapper;
this.classAttributeIdentifier = classAttributeIdentifier;
this.definedInAttributeIdentifier = definedInAttributeIdentifier;
this.reflectionProvider = reflectionProvider;
this.implicitCollectionMapper = implicitCollectionMapper;
instanceResolver = new InstanceResolver();
}
public boolean canConvert(Class type) {
return true;
}
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
if (getMethod(source.getClass(), "writeObject", new Class[]{ObjectOutputStream.class}) != null) {
try {
Method writeObjectMethod = getMethod(source.getClass(), "writeObject", new Class[]{ObjectOutputStream.class});
CustomObjectOutputStream.StreamCallback callback = new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
if (object == null) {
writer.startNode("stream.null");
writer.endNode();
} else {
writer.startNode("stream." + classMapper.lookupName(object.getClass()));
context.convertAnother(object);
writer.endNode();
}
}
public void defaultWriteObject() {
serializeEachField(source, context, writer);
}
};
ObjectOutputStream objectOutputStream = createCustomObjectOutputStream(callback, context);
writeObjectMethod.setAccessible(true);
writeObjectMethod.invoke(source, new Object[]{objectOutputStream});
} catch (IllegalAccessException e) {
throw new ConversionException("Could not call " + source.getClass().getName() + ".writeObject()", e);
} catch (InvocationTargetException e) {
throw new ConversionException("Could not call " + source.getClass().getName() + ".writeObject()", e);
}
} else {
serializeEachField(source, context, writer);
}
}
private Method getMethod(Class cls, String name, Class[] parameterTypes) {
Method result = null;
String key = cls + "." + name;
if (writeObjectMethodCache.containsKey(key)) {
return (Method) writeObjectMethodCache.get(key);
} else {
try {
result = cls.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
result = null;
}
writeObjectMethodCache.put(key, result);
}
return result;
}
private ObjectOutputStream createCustomObjectOutputStream(CustomObjectOutputStream.StreamCallback callback, final MarshallingContext context) {
final String key = "Cached CustomObjectOutputStream";
CustomObjectOutputStream objectOutputStream = (CustomObjectOutputStream) context.get(key);
if (objectOutputStream == null) {
objectOutputStream = CustomObjectOutputStream.create(callback);
context.put(key, objectOutputStream);
} else {
objectOutputStream.setCallback(callback);
}
return objectOutputStream;
}
private void serializeEachField(final Object source, final MarshallingContext context, final HierarchicalStreamWriter writer) {
final Set seenFields = new HashSet();
reflectionProvider.visitSerializableFields(source, new ReflectionProvider.Visitor() {
public void visit(String fieldName, Class fieldType, Class definedIn, Object newObj) {
if (newObj != null) {
if (implicitCollectionMapper.isImplicitCollectionField(definedIn, fieldName)) {
context.convertAnother(newObj);
} else {
writer.startNode(classMapper.mapNameToXML(fieldName));
Class actualType = newObj.getClass();
Class defaultType = classMapper.lookupDefaultType(fieldType);
if (!actualType.equals(defaultType)) {
writer.addAttribute(classAttributeIdentifier, classMapper.lookupName(actualType));
}
if (seenFields.contains(fieldName)) {
writer.addAttribute(definedInAttributeIdentifier, classMapper.lookupName(definedIn));
}
context.convertAnother(newObj);
writer.endNode();
seenFields.add(fieldName);
}
}
}
});
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Object result = instantiateNewInstance(context);
deserializeEachField(reader, result, context);
return instanceResolver.resolve(result);
}
private void deserializeEachField(HierarchicalStreamReader reader, Object result, UnmarshallingContext context) {
SeenFields seenFields = new SeenFields();
Map implicitCollectionsForCurrentObject = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
String fieldName = classMapper.mapNameFromXML(reader.getNodeName());
Class classDefiningField = determineWhichClassDefinesField(reader);
boolean fieldExistsInClass = reflectionProvider.fieldDefinedInClass(fieldName, result.getClass());
Class type = determineType(reader, fieldExistsInClass, result, fieldName, classDefiningField);
Object value = context.convertAnother(result, type);
if (fieldExistsInClass) {
reflectionProvider.writeField(result, fieldName, value, classDefiningField);
seenFields.add(classDefiningField, fieldName);
} else {
implicitCollectionsForCurrentObject = writeValueToImplicitCollection(context, value, implicitCollectionsForCurrentObject, result);
}
reader.moveUp();
}
}
private Map writeValueToImplicitCollection(UnmarshallingContext context, Object value, Map implicitCollections, Object result) {
String fieldName = implicitCollectionMapper.implicitCollectionFieldForType(context.getRequiredType(), value.getClass());
if (fieldName != null) {
if (implicitCollections == null) {
implicitCollections = new HashMap(); // lazy instantiation
}
Collection collection = (Collection) implicitCollections.get(fieldName);
if (collection == null) {
collection = new ArrayList();
reflectionProvider.writeField(result, fieldName, collection, null);
implicitCollections.put(fieldName, collection);
}
collection.add(value);
}
return implicitCollections;
}
private Class determineWhichClassDefinesField(HierarchicalStreamReader reader) {
String definedIn = reader.getAttribute(definedInAttributeIdentifier);
return definedIn == null ? null : classMapper.lookupType(definedIn);
}
private Object instantiateNewInstance(UnmarshallingContext context) {
Object result = context.currentObject();
if (result == null) {
result = reflectionProvider.newInstance(context.getRequiredType());
}
return result;
}
private static class SeenFields {
private Set seen = new HashSet();
public void add(Class definedInCls, String fieldName) {
String uniqueKey = fieldName;
if (definedInCls != null) {
uniqueKey += " [" + definedInCls.getName() + "]";
}
if (seen.contains(uniqueKey)) {
throw new DuplicateFieldException(uniqueKey);
} else {
seen.add(uniqueKey);
}
}
}
private Class determineType(HierarchicalStreamReader reader, boolean validField, Object result, String fieldName, Class definedInCls) {
String classAttribute = reader.getAttribute(classAttributeIdentifier);
if (classAttribute != null) {
return classMapper.lookupType(classAttribute);
} else if (!validField) {
return classMapper.lookupType(reader.getNodeName());
} else {
return classMapper.lookupDefaultType(reflectionProvider.getFieldType(result, fieldName, definedInCls));
}
}
public static class DuplicateFieldException extends ConversionException {
public DuplicateFieldException(String msg) {
super(msg);
}
}
}
|
package org.twitter.zipkin.storage.cassandra;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.utils.Bytes;
import com.google.common.base.Preconditions;
import com.google.common.io.CharStreams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public final class Repository implements AutoCloseable {
public static final String KEYSPACE = "zipkin";
public static final short BUCKETS = 10;
private static final Logger LOG = LoggerFactory.getLogger(Repository.class);
private static final Random RAND = new Random();
private static final List<Integer> ALL_BUCKETS = Collections.unmodifiableList(new ArrayList<Integer>() {{
for (int i = 0; i < BUCKETS; ++i) {
add(i);
}
}});
private static final long WRITTEN_NAMES_TTL
= Long.getLong("zipkin.store.cassandra.internal.writtenNamesTtl", 60 * 60 * 1000);
private final Session session;
private final PreparedStatement selectTraces;
private final PreparedStatement insertSpan;
private final PreparedStatement selectDependencies;
private final PreparedStatement insertDependencies;
private final PreparedStatement selectServiceNames;
private final PreparedStatement insertServiceName;
private final PreparedStatement selectSpanNames;
private final PreparedStatement insertSpanName;
private final PreparedStatement selectTraceIdsByServiceName;
private final PreparedStatement insertTraceIdByServiceName;
private final PreparedStatement selectTraceIdsBySpanName;
private final PreparedStatement insertTraceIdBySpanName;
private final PreparedStatement selectTraceIdsByAnnotations;
private final PreparedStatement insertTraceIdByAnnotation;
private final Map<String,String> metadata;
private final ThreadLocal<Set<String>> writtenNames = new ThreadLocal<Set<String>>() {
private long cacheInterval = toCacheInterval(System.currentTimeMillis());
@Override
protected Set<String> initialValue() {
return new HashSet<String>();
}
@Override
public Set<String> get() {
long newCacheInterval = toCacheInterval(System.currentTimeMillis());
if (cacheInterval != newCacheInterval) {
cacheInterval = newCacheInterval;
set(new HashSet<String>());
}
return super.get();
}
private long toCacheInterval(long ms) {
return ms / WRITTEN_NAMES_TTL;
}
};
public Repository(String keyspace, Cluster cluster) {
metadata = Schema.ensureExists(keyspace, cluster);
session = cluster.connect(keyspace);
insertSpan = session.prepare(
QueryBuilder
.insertInto("traces")
.value("trace_id", QueryBuilder.bindMarker("trace_id"))
.value("ts", QueryBuilder.bindMarker("ts"))
.value("span_name", QueryBuilder.bindMarker("span_name"))
.value("span", QueryBuilder.bindMarker("span"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
selectTraces = session.prepare(
QueryBuilder.select("trace_id", "span")
.from("traces")
.where(QueryBuilder.in("trace_id", QueryBuilder.bindMarker("trace_id")))
.limit(QueryBuilder.bindMarker("limit_")));
selectDependencies = session.prepare(
QueryBuilder.select("dependencies")
.from("dependencies")
.where(QueryBuilder.in("day", QueryBuilder.bindMarker("days"))));
insertDependencies = session.prepare(
QueryBuilder
.insertInto("dependencies")
.value("day", QueryBuilder.bindMarker("day"))
.value("dependencies", QueryBuilder.bindMarker("dependencies")));
selectServiceNames = session.prepare(
QueryBuilder.select("service_name")
.from("service_names"));
insertServiceName = session.prepare(
QueryBuilder
.insertInto("service_names")
.value("service_name", QueryBuilder.bindMarker("service_name"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
selectSpanNames = session.prepare(
QueryBuilder.select("span_name")
.from("span_names")
.where(QueryBuilder.eq("service_name", QueryBuilder.bindMarker("service_name")))
.and(QueryBuilder.eq("bucket", QueryBuilder.bindMarker("bucket"))));
insertSpanName = session.prepare(
QueryBuilder
.insertInto("span_names")
.value("service_name", QueryBuilder.bindMarker("service_name"))
.value("bucket", QueryBuilder.bindMarker("bucket"))
.value("span_name", QueryBuilder.bindMarker("span_name"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
selectTraceIdsByServiceName = session.prepare(
QueryBuilder.select("ts", "trace_id")
.from("service_name_index")
.where(QueryBuilder.eq("service_name", QueryBuilder.bindMarker("service_name")))
.and(QueryBuilder.in("bucket", QueryBuilder.bindMarker("bucket")))
.and(QueryBuilder.lte("ts", QueryBuilder.bindMarker("ts")))
.limit(QueryBuilder.bindMarker("limit_"))
.orderBy(QueryBuilder.desc("ts")));
insertTraceIdByServiceName = session.prepare(
QueryBuilder
.insertInto("service_name_index")
.value("service_name", QueryBuilder.bindMarker("service_name"))
.value("bucket", QueryBuilder.bindMarker("bucket"))
.value("ts", QueryBuilder.bindMarker("ts"))
.value("trace_id", QueryBuilder.bindMarker("trace_id"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
selectTraceIdsBySpanName = session.prepare(
QueryBuilder.select("ts", "trace_id")
.from("service_span_name_index")
.where(QueryBuilder.eq("service_span_name", QueryBuilder.bindMarker("service_span_name")))
.and(QueryBuilder.lte("ts", QueryBuilder.bindMarker("ts")))
.limit(QueryBuilder.bindMarker("limit_"))
.orderBy(QueryBuilder.desc("ts")));
insertTraceIdBySpanName = session.prepare(
QueryBuilder
.insertInto("service_span_name_index")
.value("service_span_name", QueryBuilder.bindMarker("service_span_name"))
.value("ts", QueryBuilder.bindMarker("ts"))
.value("trace_id", QueryBuilder.bindMarker("trace_id"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
selectTraceIdsByAnnotations = session.prepare(
QueryBuilder.select("ts", "trace_id")
.from("annotations_index")
.where(QueryBuilder.eq("annotation", QueryBuilder.bindMarker("annotation")))
.and(QueryBuilder.in("bucket", QueryBuilder.bindMarker("bucket")))
.and(QueryBuilder.lte("ts", QueryBuilder.bindMarker("ts")))
.limit(QueryBuilder.bindMarker("limit_"))
.orderBy(QueryBuilder.desc("ts")));
insertTraceIdByAnnotation = session.prepare(
QueryBuilder
.insertInto("annotations_index")
.value("annotation", QueryBuilder.bindMarker("annotation"))
.value("bucket", QueryBuilder.bindMarker("bucket"))
.value("ts", QueryBuilder.bindMarker("ts"))
.value("trace_id", QueryBuilder.bindMarker("trace_id"))
.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))));
}
/**
* Store the span in the underlying storage for later retrieval.
*/
public void storeSpan(long traceId, long timestamp, String spanName, ByteBuffer span, int ttl) {
Preconditions.checkNotNull(spanName);
Preconditions.checkArgument(!spanName.isEmpty());
if (0 == timestamp && metadata.get("traces.compaction.class").contains("DateTieredCompactionStrategy")) {
LOG.warn("span with no first or last timestamp. "
+ "if this happens a lot consider switching back to SizeTieredCompactionStrategy for "
+ KEYSPACE + ".traces");
}
try {
BoundStatement bound = insertSpan.bind()
.setLong("trace_id", traceId)
.setLong("ts", timestamp)
.setString("span_name", spanName)
.setBytes("span", span)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertSpan(traceId, timestamp, spanName, span, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertSpan(traceId, timestamp, spanName, span, ttl), ex);
throw ex;
}
}
private String debugInsertSpan(long traceId, long timestamp, String spanName, ByteBuffer span, int ttl) {
return insertSpan.getQueryString()
.replace(":trace_id", String.valueOf(traceId))
.replace(":ts", String.valueOf(timestamp))
.replace(":span_name", spanName)
.replace(":span", Bytes.toHexString(span))
.replace(":ttl_", String.valueOf(ttl));
}
/**
* Get the available trace information from the storage system.
* Spans in trace should be sorted by the first annotation timestamp
* in that span. First event should be first in the spans list.
*
* The return list will contain only spans that have been found, thus
* the return list may not match the provided list of ids.
*/
public Map<Long,List<ByteBuffer>> getSpansByTraceIds(Long[] traceIds, int limit) {
Preconditions.checkNotNull(traceIds);
try {
Map<Long,List<ByteBuffer>> spans = new LinkedHashMap<>();
if (0 < traceIds.length) {
BoundStatement bound = selectTraces.bind()
.setList("trace_id", Arrays.asList(traceIds))
.setInt("limit_", limit);
bound.setFetchSize(Integer.MAX_VALUE);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectTraces(traceIds, limit));
}
for (Row row : session.execute(bound).all()) {
long traceId = row.getLong("trace_id");
if (!spans.containsKey(traceId)) {
spans.put(traceId, new ArrayList<ByteBuffer>());
}
spans.get(traceId).add(row.getBytes("span"));
}
}
return spans;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectTraces(traceIds, limit), ex);
throw ex;
}
}
private String debugSelectTraces(Long[] traceIds, int limit) {
return selectTraces.getQueryString()
.replace(":trace_id", Arrays.toString(traceIds))
.replace(":limit_", String.valueOf(limit));
}
public void storeDependencies(long epochDayMillis, ByteBuffer dependencies) {
Date startFlooredToDay = new Date(epochDayMillis);
try {
BoundStatement bound = insertDependencies.bind()
.setDate("day", startFlooredToDay)
.setBytes("dependencies", dependencies);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertDependencies(startFlooredToDay, dependencies));
}
session.execute(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertDependencies(startFlooredToDay, dependencies), ex);
throw ex;
}
}
private String debugInsertDependencies(Date startFlooredToDay, ByteBuffer dependencies) {
return insertDependencies.getQueryString()
.replace(":day", startFlooredToDay.toString())
.replace(":dependencies", Bytes.toHexString(dependencies));
}
public List<ByteBuffer> getDependencies(long startEpochDayMillis, long endEpochDayMillis) {
List<Date> days = getDays(startEpochDayMillis, endEpochDayMillis);
try {
BoundStatement bound = selectDependencies.bind().setList("days", days);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectDependencies(days));
}
List<ByteBuffer> dependencies = new ArrayList<>();
for (Row row : session.execute(bound).all()) {
dependencies.add(row.getBytes("dependencies"));
}
return dependencies;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectDependencies(days), ex);
throw ex;
}
}
private String debugSelectDependencies(List<Date> days) {
return selectDependencies.getQueryString().replace(":days", Arrays.toString(days.toArray()));
}
public Set<String> getServiceNames() {
try {
Set<String> serviceNames = new HashSet<>();
BoundStatement bound = selectServiceNames.bind();
if (LOG.isDebugEnabled()) {
LOG.debug(selectServiceNames.getQueryString());
}
for (Row row : session.execute(bound).all()) {
serviceNames.add(row.getString("service_name"));
}
return serviceNames;
} catch (RuntimeException ex) {
LOG.error("failed " + selectServiceNames.getQueryString(), ex);
throw ex;
}
}
public void storeServiceName(String serviceName, int ttl) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
if (writtenNames.get().add(serviceName)) {
try {
BoundStatement bound = insertServiceName.bind()
.setString("service_name", serviceName)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertServiceName(serviceName, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertServiceName(serviceName, ttl), ex);
writtenNames.get().remove(serviceName);
throw ex;
}
}
}
private String debugInsertServiceName(String serviceName, int ttl) {
return insertServiceName.getQueryString()
.replace(":service_name", serviceName)
.replace(":ttl_", String.valueOf(ttl));
}
public Set<String> getSpanNames(String serviceName) {
Preconditions.checkNotNull(serviceName);
try {
Set<String> spanNames = new HashSet<>();
if (!serviceName.isEmpty()) {
BoundStatement bound = selectSpanNames.bind()
.setString("service_name", serviceName)
.setInt("bucket", 0);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectSpanNames(serviceName));
}
for (Row row : session.execute(bound).all()) {
spanNames.add(row.getString("span_name"));
}
}
return spanNames;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectSpanNames(serviceName), ex);
throw ex;
}
}
private String debugSelectSpanNames(String serviceName) {
return selectSpanNames.getQueryString().replace(':' + "service_name", serviceName);
}
public void storeSpanName(String serviceName, String spanName, int ttl) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
Preconditions.checkNotNull(spanName);
Preconditions.checkArgument(!spanName.isEmpty());
if (writtenNames.get().add(serviceName + "––" + spanName)) {
try {
BoundStatement bound = insertSpanName.bind()
.setString("service_name", serviceName)
.setInt("bucket", 0)
.setString("span_name", spanName)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertSpanName(serviceName, spanName, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertSpanName(serviceName, spanName, ttl), ex);
writtenNames.get().remove(serviceName + "––" + spanName);
throw ex;
}
}
}
private String debugInsertSpanName(String serviceName, String spanName, int ttl) {
return insertSpanName.getQueryString()
.replace(":service_name", serviceName)
.replace(":span_name", spanName)
.replace(":ttl_", String.valueOf(ttl));
}
public Map<Long,Long> getTraceIdsByServiceName(String serviceName, long to, int limit) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
try {
BoundStatement bound = selectTraceIdsByServiceName.bind()
.setString("service_name", serviceName)
.setList("bucket", ALL_BUCKETS)
.setLong("ts", to)
.setInt("limit_", limit);
bound.setFetchSize(Integer.MAX_VALUE);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectTraceIdsByServiceName(serviceName, to, limit));
}
Map<Long,Long> traceIdsToTimestamps = new LinkedHashMap<>();
for (Row row : session.execute(bound).all()) {
traceIdsToTimestamps.put(row.getLong("trace_id"), row.getLong("ts"));
}
return traceIdsToTimestamps;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectTraceIdsByServiceName(serviceName, to, limit), ex);
throw ex;
}
}
private String debugSelectTraceIdsByServiceName(String serviceName, long to, int limit) {
return selectTraceIdsByServiceName.getQueryString()
.replace(":service_name", serviceName)
.replace(":ts", new Date(to / 1000).toString())
.replace(":limit_", String.valueOf(limit));
}
public void storeTraceIdByServiceName(String serviceName, long timestamp, long traceId, int ttl) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
try {
BoundStatement bound = insertTraceIdByServiceName.bind()
.setString("service_name", serviceName)
.setInt("bucket", RAND.nextInt(BUCKETS))
.setLong("ts", timestamp)
.setLong("trace_id", traceId)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertTraceIdByServiceName(serviceName, timestamp, traceId, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertTraceIdByServiceName(serviceName, timestamp, traceId, ttl), ex);
throw ex;
}
}
private String debugInsertTraceIdByServiceName(String serviceName, long timestamp, long traceId, int ttl) {
return insertTraceIdByServiceName.getQueryString()
.replace(":service_name", serviceName)
.replace(":ts", new Date(timestamp / 1000).toString())
.replace(":trace_id", new Date(traceId).toString())
.replace(":ttl_", String.valueOf(ttl));
}
public Map<Long,Long> getTraceIdsBySpanName(String serviceName, String spanName, long to, int limit) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
Preconditions.checkNotNull(spanName);
Preconditions.checkArgument(!spanName.isEmpty());
String serviceSpanName = serviceName + "." + spanName;
try {
BoundStatement bound = selectTraceIdsBySpanName.bind()
.setString("service_span_name", serviceSpanName)
.setLong("ts", to)
.setInt("limit_", limit);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectTraceIdsBySpanName(serviceSpanName, to, limit));
}
Map<Long,Long> traceIdsToTimestamps = new LinkedHashMap<>();
for (Row row : session.execute(bound).all()) {
traceIdsToTimestamps.put(row.getLong("trace_id"), row.getLong("ts"));
}
return traceIdsToTimestamps;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectTraceIdsBySpanName(serviceSpanName, to, limit), ex);
throw ex;
}
}
private String debugSelectTraceIdsBySpanName(String serviceSpanName, long to, int limit) {
return selectTraceIdsByServiceName.getQueryString()
.replace(":service_span_name", serviceSpanName)
.replace(":ts", new Date(to / 1000).toString())
.replace(":limit_", String.valueOf(limit));
}
public void storeTraceIdBySpanName(String serviceName, String spanName, long timestamp, long traceId, int ttl) {
Preconditions.checkNotNull(serviceName);
Preconditions.checkArgument(!serviceName.isEmpty());
Preconditions.checkNotNull(spanName);
Preconditions.checkArgument(!spanName.isEmpty());
try {
String serviceSpanName = serviceName + "." + spanName;
BoundStatement bound = insertTraceIdBySpanName.bind()
.setString("service_span_name", serviceSpanName)
.setLong("ts", timestamp)
.setLong("trace_id", traceId)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertTraceIdBySpanName(serviceSpanName, timestamp, traceId, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertTraceIdBySpanName(serviceName, timestamp, traceId, ttl), ex);
throw ex;
}
}
private String debugInsertTraceIdBySpanName(String serviceSpanName, long timestamp, long traceId, int ttl) {
return insertTraceIdBySpanName.getQueryString()
.replace(":service_span_name", serviceSpanName)
.replace(":ts", String.valueOf(timestamp))
.replace(":trace_id", String.valueOf(traceId))
.replace(":ttl_", String.valueOf(ttl));
}
public Map<Long,Long> getTraceIdsByAnnotation(ByteBuffer annotationKey, long from, int limit) {
try {
BoundStatement bound = selectTraceIdsByAnnotations.bind()
.setBytes("annotation", annotationKey)
.setList("bucket", ALL_BUCKETS)
.setLong("ts", from)
.setInt("limit_", limit);
bound.setFetchSize(Integer.MAX_VALUE);
if (LOG.isDebugEnabled()) {
LOG.debug(debugSelectTraceIdsByAnnotations(annotationKey, from, limit));
}
Map<Long,Long> traceIdsToTimestamps = new LinkedHashMap<>();
for (Row row : session.execute(bound).all()) {
traceIdsToTimestamps.put(row.getLong("trace_id"), row.getLong("ts"));
}
return traceIdsToTimestamps;
} catch (RuntimeException ex) {
LOG.error("failed " + debugSelectTraceIdsByAnnotations(annotationKey, from, limit), ex);
throw ex;
}
}
private String debugSelectTraceIdsByAnnotations(ByteBuffer annotationKey, long from, int limit) {
return selectTraceIdsByAnnotations.getQueryString()
.replace(":annotation", new String(Bytes.getArray(annotationKey)))
.replace(":ts", new Date(from / 1000).toString())
.replace(":limit_", String.valueOf(limit));
}
public void storeTraceIdByAnnotation(ByteBuffer annotationKey, long timestamp, long traceId, int ttl) {
try {
BoundStatement bound = insertTraceIdByAnnotation.bind()
.setBytes("annotation", annotationKey)
.setInt("bucket", RAND.nextInt(BUCKETS))
.setLong("ts", timestamp)
.setLong("trace_id", traceId)
.setInt("ttl_", ttl);
if (LOG.isDebugEnabled()) {
LOG.debug(debugInsertTraceIdByAnnotation(annotationKey, timestamp, traceId, ttl));
}
session.executeAsync(bound);
} catch (RuntimeException ex) {
LOG.error("failed " + debugInsertTraceIdByAnnotation(annotationKey, timestamp, traceId, ttl), ex);
throw ex;
}
}
private String debugInsertTraceIdByAnnotation(ByteBuffer annotationKey, long timestamp, long traceId, int ttl) {
return insertTraceIdByAnnotation.getQueryString()
.replace(":annotation", new String(Bytes.getArray(annotationKey)))
.replace(":ts", new Date(timestamp / 1000).toString())
.replace(":trace_id", String.valueOf(traceId))
.replace(":ttl_", String.valueOf(ttl));
}
private static List<Date> getDays(long from, long to) {
List<Date> days = new ArrayList<>();
for (long time = from; time <= to; time += TimeUnit.DAYS.toMillis(1)) {
days.add(new Date(time));
}
return days;
}
@Override
public void close() {
session.close();
}
private static class Schema {
private static final String SCHEMA = "/cassandra-schema-cql3.txt";
static Map<String,String> ensureExists(String keyspace, Cluster cluster) {
Map<String,String> metadata = new LinkedHashMap<>();
try (Session session = cluster.connect()) {
try (Reader reader = new InputStreamReader(Schema.class.getResourceAsStream(SCHEMA))) {
for (String cmd : String.format(CharStreams.toString(reader)).split(";")) {
cmd = cmd.trim().replace(" " + KEYSPACE, " " + keyspace);
if (!cmd.isEmpty()) {
session.execute(cmd);
}
}
}
KeyspaceMetadata keyspaceMetadata = cluster.getMetadata().getKeyspace(keyspace);
Map<String,String> replicatn = keyspaceMetadata.getReplication();
if("SimpleStrategy".equals(replicatn.get("class")) && "1".equals(replicatn.get("replication_factor"))) {
LOG.warn("running with RF=1, this is not suitable for production. Optimal is 3+");
}
Map<String,String> tracesCompaction = keyspaceMetadata.getTable("traces").getOptions().getCompaction();
metadata.put("traces.compaction.class", tracesCompaction.get("class"));
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
}
return metadata;
}
private Schema() {}
}
}
|
package net.geforcemods.securitycraft.itemblocks;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
public class ItemBlockReinforcedQuartz extends ItemBlockTinted
{
public ItemBlockReinforcedQuartz(Block block)
{
super(block);
setHasSubtypes(true);
}
@Override
public int getMetadata(int damage)
{
return damage;
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
String name = getUnlocalizedName();
switch(stack.getItemDamage())
{
case 1: return name + "_chiseled";
case 2: return name + "_pillar";
default: return name;
}
}
}
|
package com.hubspot.baragon.service.worker;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.baragon.BaragonDataModule;
import com.hubspot.baragon.data.BaragonStateDatastore;
import com.hubspot.baragon.models.AgentRequestType;
import com.hubspot.baragon.models.AgentRequestsStatus;
import com.hubspot.baragon.models.AgentResponse;
import com.hubspot.baragon.models.BaragonRequest;
import com.hubspot.baragon.models.BaragonService;
import com.hubspot.baragon.models.InternalRequestStates;
import com.hubspot.baragon.models.InternalStatesMap;
import com.hubspot.baragon.models.QueuedRequestId;
import com.hubspot.baragon.models.QueuedRequestWithState;
import com.hubspot.baragon.models.RequestAction;
import com.hubspot.baragon.service.config.BaragonConfiguration;
import com.hubspot.baragon.service.edgecache.EdgeCache;
import com.hubspot.baragon.service.exceptions.BaragonExceptionNotifier;
import com.hubspot.baragon.service.managers.AgentManager;
import com.hubspot.baragon.service.managers.RequestManager;
import com.hubspot.baragon.utils.JavaUtils;
@Singleton
public class BaragonRequestWorker implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(BaragonRequestWorker.class);
private final AgentManager agentManager;
private final RequestManager requestManager;
private final BaragonStateDatastore stateDatastore;
private final AtomicLong workerLastStartAt;
private final BaragonExceptionNotifier exceptionNotifier;
private final BaragonConfiguration configuration;
private final EdgeCache edgeCache;
@Inject
public BaragonRequestWorker(AgentManager agentManager,
RequestManager requestManager,
BaragonStateDatastore stateDatastore,
BaragonExceptionNotifier exceptionNotifier,
BaragonConfiguration configuration,
EdgeCache edgeCache,
@Named(BaragonDataModule.BARAGON_SERVICE_WORKER_LAST_START) AtomicLong workerLastStartAt) {
this.agentManager = agentManager;
this.requestManager = requestManager;
this.stateDatastore = stateDatastore;
this.edgeCache = edgeCache;
this.workerLastStartAt = workerLastStartAt;
this.exceptionNotifier = exceptionNotifier;
this.configuration = configuration;
}
private String buildResponseString(Map<String, Collection<AgentResponse>> agentResponses, AgentRequestType requestType) {
if (agentResponses.containsKey(requestType.name()) && !agentResponses.get(requestType.name()).isEmpty()) {
Set<String> messages = new HashSet<>();
for (AgentResponse response : agentResponses.get(requestType.name())) {
if (response.toRequestStatus() == AgentRequestsStatus.FAILURE || response.toRequestStatus() == AgentRequestsStatus.INVALID_REQUEST_NOOP) {
messages.add(String.format("(%s) - %s", response.getStatusCode().or(0), response.getContent().or(response.getException()).or("")));
} else {
messages.add(String.format("%s - %s", response.getUrl(), response.toRequestStatus().name()));
}
}
return JavaUtils.COMMA_JOINER.join(messages);
} else {
return "No agent responses";
}
}
private InternalRequestStates handleCheckRevertResponse(BaragonRequest request, InternalRequestStates currentState) {
final Map<String, Collection<AgentResponse>> agentResponses;
switch (agentManager.getRequestsStatus(request, InternalStatesMap.getRequestType(currentState))) {
case FAILURE:
agentResponses = agentManager.getAgentResponses(request.getLoadBalancerRequestId());
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("Apply failed {%s}, %s failed {%s}", buildResponseString(agentResponses, AgentRequestType.APPLY), InternalStatesMap
.getRequestType(currentState)
.name(), buildResponseString(agentResponses, InternalStatesMap.getRequestType(currentState))));
return InternalStatesMap.getFailureState(currentState);
case SUCCESS:
agentResponses = agentManager.getAgentResponses(request.getLoadBalancerRequestId());
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("Apply failed {%s}, %s OK.", buildResponseString(agentResponses, AgentRequestType.APPLY), InternalStatesMap.getRequestType(currentState)
.name()));
requestManager.revertBasePath(request);
return InternalStatesMap.getSuccessState(currentState);
case RETRY:
return InternalStatesMap.getRetryState(currentState);
default:
return InternalStatesMap.getWaitingState(currentState);
}
}
private InternalRequestStates handleState(InternalRequestStates currentState, BaragonRequest request) {
switch (currentState) {
case PENDING:
final Map<String, String> conflicts = requestManager.getBasePathConflicts(request);
if (!conflicts.isEmpty() && !(request.getAction().or(RequestAction.UPDATE) == RequestAction.DELETE)) {
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), getBasePathConflictMessage(conflicts));
return InternalRequestStates.INVALID_REQUEST_NOOP;
}
final Set<String> missingGroups = requestManager.getMissingLoadBalancerGroups(request);
if (!missingGroups.isEmpty()) {
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("Invalid request due to non-existent load balancer groups: %s", missingGroups));
return InternalRequestStates.INVALID_REQUEST_NOOP;
}
for (String loadBalancerGroup : request.getLoadBalancerService().getLoadBalancerGroups()) {
if (agentManager.invalidAgentCount(loadBalancerGroup)) {
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("Invalid request due to not enough agents present for group: %s", loadBalancerGroup));
return InternalRequestStates.FAILED_REVERTED;
}
}
if (!request.getLoadBalancerService().getDomains().isEmpty()) {
List<String> domainsNotServed = getDomainsNotServed(request.getLoadBalancerService());
if (!domainsNotServed.isEmpty()) {
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("No groups present that serve domains: %s", domainsNotServed));
return InternalRequestStates.INVALID_REQUEST_NOOP;
}
}
if (!(request.getAction().or(RequestAction.UPDATE) == RequestAction.DELETE)) {
requestManager.lockBasePaths(request);
}
return InternalRequestStates.SEND_APPLY_REQUESTS;
case CHECK_APPLY_RESPONSES:
switch (agentManager.getRequestsStatus(request, InternalStatesMap.getRequestType(currentState))) {
case FAILURE:
final Map<String, Collection<AgentResponse>> agentResponses = agentManager.getAgentResponses(request.getLoadBalancerRequestId());
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("Apply failed (%s), reverting...", buildResponseString(agentResponses, InternalStatesMap.getRequestType(currentState))));
return InternalRequestStates.FAILED_SEND_REVERT_REQUESTS;
case SUCCESS:
try {
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), String.format("%s request succeeded! Added upstreams: %s, Removed upstreams: %s", request.getAction()
.or(RequestAction.UPDATE), request.getAddUpstreams(), request.getRemoveUpstreams()));
requestManager.commitRequest(request);
if (performPostApplySteps(request)) {
return InternalRequestStates.COMPLETED;
} else {
return InternalRequestStates.COMPLETED_POST_APPLY_FAILED;
}
} catch (KeeperException ke) {
String message = String.format("Caught zookeeper error for path %s.", ke.getPath());
LOG.error(message, ke);
requestManager.setRequestMessage(request.getLoadBalancerRequestId(), message + ke.getMessage());
return InternalRequestStates.FAILED_SEND_REVERT_REQUESTS;
} catch (Exception e) {
LOG.warn(String.format("Request %s was successful, but failed to commit!", request.getLoadBalancerRequestId()), e);
exceptionNotifier.notify(e, ImmutableMap.of("requestId", request.getLoadBalancerRequestId(), "serviceId", request.getLoadBalancerService().getServiceId()));
return InternalRequestStates.FAILED_SEND_REVERT_REQUESTS;
}
case RETRY:
return InternalRequestStates.SEND_APPLY_REQUESTS;
case INVALID_REQUEST_NOOP:
requestManager.revertBasePath(request);
return InternalRequestStates.INVALID_REQUEST_NOOP;
default:
return InternalRequestStates.CHECK_APPLY_RESPONSES;
}
case SEND_APPLY_REQUESTS:
case FAILED_SEND_REVERT_REQUESTS:
case CANCELLED_SEND_REVERT_REQUESTS:
throw new RuntimeException(String.format("Requests in state %s must be handled by batch request sender", currentState));
case FAILED_CHECK_REVERT_RESPONSES:
case CANCELLED_CHECK_REVERT_RESPONSES:
return handleCheckRevertResponse(request, currentState);
default:
return currentState;
}
}
private boolean performPostApplySteps(BaragonRequest request) {
if (configuration.getEdgeCacheConfiguration().isEnabled()) {
if (edgeCache.invalidateIfNecessary(request)) {
LOG.info("Invalidated edge cache for {}", request);
return true;
} else {
return false;
}
}
return true;
}
private List<String> getDomainsNotServed(BaragonService service) {
List<String> notServed = new ArrayList<>(service.getDomains());
for (String group : service.getLoadBalancerGroups()) {
Set<String> domains = agentManager.getAllDomainsForGroup(group);
for (String domain : domains) {
notServed.remove(domain);
}
}
return notServed;
}
private String getBasePathConflictMessage(Map<String, String> conflicts) {
String message = "Invalid request due to base path conflicts: [";
for (Map.Entry<String, String> entry : conflicts.entrySet()) {
message = String.format("%s %s on group %s,", message, entry.getValue(), entry.getKey());
}
return message.substring(0, message.length() - 1) + " ]";
}
private Map<QueuedRequestWithState, InternalRequestStates> handleQueuedRequests(List<QueuedRequestWithState> queuedRequestsWithState) {
Map<QueuedRequestWithState, InternalRequestStates> results = new HashMap<>();
List<QueuedRequestWithState> toApply = new ArrayList<>();
for (QueuedRequestWithState queuedRequestWithState : queuedRequestsWithState) {
LOG.debug("Handling {}", queuedRequestsWithState);
if (!queuedRequestWithState.getCurrentState().isRequireAgentRequest()) {
try {
results.put(queuedRequestWithState, handleState(queuedRequestWithState.getCurrentState(), queuedRequestWithState.getRequest()));
} catch (Exception e) {
LOG.error("Error processing request {}", queuedRequestWithState.getRequest().getLoadBalancerRequestId(), e);
}
} else {
if (toApply.size() < configuration.getWorkerConfiguration().getMaxBatchSize()) {
toApply.add(queuedRequestWithState);
}
}
}
results.putAll(agentManager.sendRequests(toApply));
return results;
}
@Override
public void run() {
workerLastStartAt.set(System.currentTimeMillis());
try {
final List<QueuedRequestId> queuedRequestIds = requestManager.getQueuedRequestIds();
int added = 0;
while (added < configuration.getWorkerConfiguration().getMaxRequestsPerPoll() && !queuedRequestIds.isEmpty()) {
Map<String, List<QueuedRequestId>> requestsGroupedByService = queuedRequestIds.stream().collect(Collectors.groupingBy(QueuedRequestId::getServiceId));
ArrayList<QueuedRequestId> nonServiceChanges = new ArrayList<>();
ArrayList<QueuedRequestId> serviceChanges = new ArrayList<>();
added = collectRequests(added, requestsGroupedByService, nonServiceChanges, serviceChanges);
// Now take the list of non-service-change requests,
// hydrate them with state,
// and sort them such that the quicker noValidate / noReload requests come first.
List<QueuedRequestWithState> hydratedNonServiceChanges = nonServiceChanges.stream()
.map(this::hydrateQueuedRequestWithState)
.filter(Optional::isPresent)
.map(Optional::get)
.sorted(queuedRequestComparator())
.collect(Collectors.toList());
// Then send them off.
LOG.debug("Processing {} BaragonRequests which don't modify a BaragonService", nonServiceChanges.size());
handleResultStates(handleQueuedRequests(hydratedNonServiceChanges));
// Now send off the service change requests.
List<QueuedRequestWithState> hydratedServiceChanges = serviceChanges.stream()
.map(this::hydrateQueuedRequestWithState)
.filter(Optional::isPresent)
.map(Optional::get)
.sorted(queuedRequestComparator())
.collect(Collectors.toList());
LOG.debug("Processing {} BaragonRequests which modify a BaragonService", serviceChanges.size());
handleResultStates(handleQueuedRequests(hydratedServiceChanges));
queuedRequestIds.removeAll(nonServiceChanges);
queuedRequestIds.removeAll(serviceChanges);
// ...and repeat until we've processed up to the limit of requests
}
} catch (Exception e) {
LOG.warn("Caught exception", e);
exceptionNotifier.notify(e, Collections.<String, String>emptyMap());
} finally {
LOG.debug("Finished poller loop.");
}
}
private void handleResultStates(Map<QueuedRequestWithState, InternalRequestStates> results) {
for (Map.Entry<QueuedRequestWithState, InternalRequestStates> result : results.entrySet()) {
if (result.getValue() != result.getKey().getCurrentState()) {
LOG.info(String.format("%s: %s --> %s", result.getKey().getQueuedRequestId().getRequestId(), result.getKey().getCurrentState(), result.getValue()));
requestManager.setRequestState(result.getKey().getQueuedRequestId().getRequestId(), result.getValue());
}
if (InternalStatesMap.isRemovable(result.getValue())) {
requestManager.removeQueuedRequest(result.getKey().getQueuedRequestId());
requestManager.saveResponseToHistory(result.getKey().getRequest(), result.getValue());
requestManager.deleteRequest(result.getKey().getQueuedRequestId().getRequestId());
}
}
}
private int collectRequests(int previouslyAdded,
Map<String, List<QueuedRequestId>> requestsGroupedByService,
ArrayList<QueuedRequestId> nonServiceChanges,
ArrayList<QueuedRequestId> serviceChanges) {
int added = previouslyAdded;
for (Map.Entry<String, List<QueuedRequestId>> requestsForService : requestsGroupedByService.entrySet()) {
for (QueuedRequestId request : requestsForService.getValue()) {
if (added >= configuration.getWorkerConfiguration().getMaxRequestsPerPoll()) {
return added;
}
// Grab as many non-service-change BaragonRequests as we can.
if (requestManager.getRequest(request.getRequestId()).transform(someRequest -> !isBatchBoundary(someRequest)).or(false)) {
nonServiceChanges.add(request);
added++;
} else {
// Once we hit a BaragonRequest that specifies BaragonService changes, stop collecting requests for this service.
serviceChanges.add(request);
added++;
break;
}
}
}
return added;
}
private boolean isBatchBoundary(BaragonRequest baragonRequest) {
return !stateDatastore.isServiceUnchanged(baragonRequest) || !baragonRequest.getAction().or(RequestAction.UPDATE).equals(RequestAction.UPDATE);
}
private Optional<QueuedRequestWithState> hydrateQueuedRequestWithState(QueuedRequestId queuedRequestId) {
final String requestId = queuedRequestId.getRequestId();
final Optional<InternalRequestStates> maybeState = requestManager.getRequestState(requestId);
if (!maybeState.isPresent()) {
LOG.warn(String.format("%s does not have a request status!", requestId));
return Optional.absent();
}
final Optional<BaragonRequest> maybeRequest = requestManager.getRequest(requestId);
if (!maybeRequest.isPresent()) {
LOG.warn(String.format("%s does not have a request object!", requestId));
return Optional.absent();
}
return Optional.of(new QueuedRequestWithState(queuedRequestId, maybeRequest.get(), maybeState.get()));
}
@VisibleForTesting
static Comparator<QueuedRequestWithState> queuedRequestComparator() {
return (requestA, requestB) -> {
// noValidate & noReload comes first
if ((requestA.getRequest().isNoValidate() && requestA.getRequest().isNoReload()) && (!requestB.getRequest().isNoReload() || !requestB.getRequest().isNoValidate())) {
return -1;
}
if ((requestB.getRequest().isNoValidate() && requestB.getRequest().isNoReload()) && (!requestA.getRequest().isNoReload() || !requestA.getRequest().isNoValidate())) {
return 1;
}
// Then noValidate *or* noReload
if ((requestA.getRequest().isNoValidate() || requestA.getRequest().isNoReload()) && (!requestB.getRequest().isNoReload() && !requestB.getRequest().isNoValidate())) {
return -1;
}
if ((requestB.getRequest().isNoValidate() || requestB.getRequest().isNoReload()) && (!requestA.getRequest().isNoReload() && !requestA.getRequest().isNoValidate())) {
return 1;
}
// Then everything else
return 0;
};
}
}
|
package com.braintreepayments.api.dropin.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.test.AndroidTestCase;
import android.view.View;
import com.braintreepayments.api.Braintree;
import com.braintreepayments.api.dropin.R;
import com.google.android.gms.wallet.Cart;
import com.google.android.gms.wallet.WalletConstants;
import com.paypal.android.sdk.payments.PayPalTouchActivity;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class PaymentButtonTest extends AndroidTestCase {
private Braintree mBraintree;
@Override
public void setUp() {
mBraintree = mock(Braintree.class);
}
public void testNotInflatedByDefault() {
PaymentButton button = new PaymentButton(getContext());
assertNull(button.findViewById(R.id.bt_paypal_button));
}
public void testNotVisibleWhenNoMethodsAreEnabled() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(false);
when(mBraintree.isAndroidPayEnabled()).thenReturn(false);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
assertEquals(View.GONE, button.getVisibility());
}
public void testOnlyShowsPayPal() {
when(mBraintree.isPayPalEnabled()).thenReturn(true);
when(mBraintree.isVenmoEnabled()).thenReturn(false);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_paypal_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_venmo_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider_2).getVisibility());
}
public void testOnlyShowsVenmo() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_venmo_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_paypal_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider_2).getVisibility());
}
public void testOnlyShowsAndroidPay() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(false);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.setAndroidPayOptions(Cart.newBuilder().build(), false, false, false);
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_paypal_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_venmo_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider_2).getVisibility());
}
public void testShowsAndroidPayIfBillingAgreementIsTrue() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(false);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.setAndroidPayOptions(null, true, false, false);
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
}
public void testDoesntShowAndroidPayIfSetAndroidPayOptionsWasNotCalled() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(false);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
assertEquals(View.GONE, button.getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
}
public void testShowsAllMethodsAndDividers() {
when(mBraintree.isPayPalEnabled()).thenReturn(true);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.setAndroidPayOptions(Cart.newBuilder().build(), false, false, false);
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_paypal_button).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_venmo_button).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_payment_button_divider).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_payment_button_divider_2).getVisibility());
}
public void testShowsSecondTwoMethodsWithCorrectDivider() {
when(mBraintree.isPayPalEnabled()).thenReturn(false);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.setAndroidPayOptions(Cart.newBuilder().build(), false, false, false);
button.initialize(null, mBraintree);
assertEquals(View.VISIBLE, button.getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_paypal_button).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_venmo_button).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_android_pay_button).getVisibility());
assertEquals(View.GONE, button.findViewById(R.id.bt_payment_button_divider).getVisibility());
assertEquals(View.VISIBLE, button.findViewById(R.id.bt_payment_button_divider_2).getVisibility());
}
public void testStartsPayWithPayPal() {
when(mBraintree.isPayPalEnabled()).thenReturn(true);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
button.findViewById(R.id.bt_paypal_button).performClick();
verify(mBraintree).startPayWithPayPal(null, PaymentButton.REQUEST_CODE);
}
public void testStartsPayWithVenmo() {
when(mBraintree.isPayPalEnabled()).thenReturn(true);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
button.findViewById(R.id.bt_venmo_button).performClick();
verify(mBraintree).startPayWithVenmo(null, PaymentButton.REQUEST_CODE);
}
public void testStartsPayWithAndroidPay() {
when(mBraintree.isPayPalEnabled()).thenReturn(true);
when(mBraintree.isVenmoEnabled()).thenReturn(true);
when(mBraintree.isAndroidPayEnabled()).thenReturn(true);
PaymentButton button = new PaymentButton(getContext());
Cart cart = Cart.newBuilder().build();
button.setAndroidPayOptions(cart, true, true, true);
button.initialize(null, mBraintree);
button.findViewById(R.id.bt_android_pay_button).performClick();
verify(mBraintree).startPayWithAndroidPay(null, PaymentButton.REQUEST_CODE, cart, true, true, true);
}
public void testDoesNotLaunchFinishMethodsOnNonOkResponses() {
PaymentButton button = new PaymentButton(getContext());
button.onActivityResult(PaymentButton.REQUEST_CODE, Activity.RESULT_CANCELED, new Intent());
verify(mBraintree, never()).finishPayWithPayPal(any(Activity.class), anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithVenmo(anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithAndroidPay(anyInt(), any(Intent.class));
}
public void testDoesNotLaunchFinishMethodsOnUnknownRequestCode() {
PaymentButton button = new PaymentButton(getContext());
button.onActivityResult(PaymentButton.REQUEST_CODE - 1, Activity.RESULT_CANCELED, new Intent());
verify(mBraintree, never()).finishPayWithPayPal(any(Activity.class), anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithVenmo(anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithAndroidPay(anyInt(), any(Intent.class));
}
public void testAllowsRequestCodeOverride() {
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree, 500);
button.onActivityResult(500, Activity.RESULT_OK, new Intent());
verify(mBraintree, never()).finishPayWithPayPal(any(Activity.class), anyInt(),
any(Intent.class));
verify(mBraintree, never()).finishPayWithAndroidPay(anyInt(), any(Intent.class));
verify(mBraintree).finishPayWithVenmo(anyInt(), any(Intent.class));
}
public void testFinishesPayPalOnPayPalIntent() {
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
Intent intent = new Intent()
.putExtra(PayPalTouchActivity.EXTRA_LOGIN_CONFIRMATION, newParcelable());
button.onActivityResult(PaymentButton.REQUEST_CODE, Activity.RESULT_OK, intent);
verify(mBraintree).finishPayWithPayPal(null, Activity.RESULT_OK, intent);
verify(mBraintree, never()).finishPayWithVenmo(anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithAndroidPay(anyInt(), any(Intent.class));
}
public void testFinishesVenmo() {
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
Intent intent = new Intent();
button.onActivityResult(PaymentButton.REQUEST_CODE, Activity.RESULT_OK, intent);
verify(mBraintree, never()).finishPayWithPayPal(any(Activity.class), anyInt(), any(Intent.class));
verify(mBraintree).finishPayWithVenmo(Activity.RESULT_OK, intent);
}
public void testFinishesAndroidPayOnAndroidPayIntent() {
PaymentButton button = new PaymentButton(getContext());
button.initialize(null, mBraintree);
Intent intent = new Intent()
.putExtra(WalletConstants.EXTRA_FULL_WALLET, newParcelable());
button.onActivityResult(PaymentButton.REQUEST_CODE, Activity.RESULT_OK, intent);
verify(mBraintree).finishPayWithAndroidPay(Activity.RESULT_OK, intent);
verify(mBraintree, never()).finishPayWithPayPal(any(Activity.class), anyInt(), any(Intent.class));
verify(mBraintree, never()).finishPayWithVenmo(anyInt(), any(Intent.class));
}
private Parcelable newParcelable() {
return new Parcelable() {
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
};
}
}
|
package com.nitobi.phonegap;
import java.io.IOException;
import java.util.TimeZone;
import android.content.Context;
import android.content.IntentFilter;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationProvider;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.webkit.WebView;
public class PhoneGap{
private static final String LOG_TAG = "PhoneGap";
/*
* UUID, version and availability
*/
public boolean droid = true;
private String version = "0.1";
private Context mCtx;
private Handler mHandler;
private WebView mAppView;
private GpsListener mGps;
private NetworkListener mNetwork;
protected LocationProvider provider;
SmsListener mSmsListener;
DirectoryManager fileManager;
AudioHandler audio;
public PhoneGap(Context ctx, Handler handler, WebView appView) {
this.mCtx = ctx;
this.mHandler = handler;
this.mAppView = appView;
mGps = new GpsListener(ctx);
mNetwork = new NetworkListener(ctx);
mSmsListener = new SmsListener(ctx,mAppView);
fileManager = new DirectoryManager();
audio = new AudioHandler("/sdcard/tmprecording.mp3", ctx);
}
public void updateAccel(){
mHandler.post(new Runnable() {
public void run() {
int accelX = SensorManager.DATA_X;
int accelY = SensorManager.DATA_Y;
int accelZ = SensorManager.DATA_Z;
mAppView.loadUrl("javascript:gotAcceleration(" + accelX + ", " + accelY + "," + accelZ + ")");
}
});
}
public void takePhoto(){
// TO-DO: Figure out what this should do
}
public void playSound(){
// TO-DO: Figure out what this should do
}
public void vibrate(long pattern){
// Start the vibration
Vibrator vibrator = (Vibrator) mCtx.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern);
}
public void getLocation( ){
mHandler.post(new Runnable() {
public void run() {
GeoTuple geoloc = new GeoTuple();
Location loc = mGps.hasLocation() ? mGps.getLocation() : mNetwork.getLocation();
if (loc != null)
{
geoloc.lat = loc.getLatitude();
geoloc.lng = loc.getLongitude();
geoloc.ele = loc.getAltitude();
}
else
{
geoloc.lat = 0;
geoloc.lng = 0;
geoloc.ele = 0;
}
mAppView.loadUrl("javascript:gotLocation(" + geoloc.lat + ", " + geoloc.lng + ")");
}
});
}
public void playSound(final String filename)
{
MediaPlayer mp = new MediaPlayer();
try {
// MediaServer does not allow reading of urls out of app data folder
// thus we grab raw file and submit via file descriptor
// instead
// InputStream is = mCtx.getAssets().open(filename);
// work around cannot play audio streams
// to get around security restriction on MediaPlayer
// until Android sdk 1.1
// thus these changes and the playSound js
// needs moved to Dev.x so that we can if statement out
// via the sdk number
if(getSDKVersion() == "1")
{
// The hack way audio stored in R.raw.filename
// and we if statement check our way through
// to match the window.DroidGap.playSound(filename.mp3)
////call on the html side
int oursound;
if (filename == "bird.mp3") {
mp.create(mCtx, R.raw.bird);
}
if (filename == "on.mp3") {
mp.create(mCtx, R.raw.on);
}
if (filename == "off.mp3"){
mp.create(mCtx, R.raw.off);
}
}
if(getSDKVersion() == "1.1")
{
//TODO: do right way here when Google fixes it
// as we have a security exception preventing
// playing audio file form file:///android_asset/ location
mp.setDataSource("file:///android_asset/" + filename);
mp.prepare();
mp.start();
}
//mp.setDataSource("file:///android_asset/" + filename);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
//TO-DO: Load a Javascript Exception thrower
} catch (IllegalStateException e) {
//TO-DO: Load a Javascript Exception thrower
} catch (IOException e) {
//TO-DO: Load a Javascript Exception thrower
}
}
public String outputText(){
String test = "<p>Test</p>";
return test;
}
public String getUuid()
{
TelephonyManager operator = (TelephonyManager) mCtx.getSystemService(Context.TELEPHONY_SERVICE);
String uuid = operator.getDeviceId();
return uuid;
}
public String getModel()
{
String model = android.os.Build.MODEL;
return model;
}
public String getProductName()
{
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getOSVersion()
{
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion()
{
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getVersion()
{
return version;
}
public void notificationWatchPosition(String filter)
/**
* Starts the listener for incoming notifications of type filter
* TODO: JavaScript Call backs for success and error handling. More filter types.
*/
{
if (filter.contains("SMS"))
{
IntentFilter mFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
mCtx.registerReceiver(mSmsListener,mFilter);
}
}
public void notificationClearWatch(String filter)
/**
* Stops the listener for incoming notifications of type filter
* TODO: JavaScript Call backs for success and error handling
*/
{
if (filter.contains("SMS"))
{
mCtx.unregisterReceiver(mSmsListener);
}
}
public void httpGet(String url, String file)
/**
* grabs a file from specified url and saves it to a name and location
* the base directory /sdcard is abstracted so that paths may be the same from one mobile OS to another
* TODO: JavaScript call backs and error handling
*/
{
HttpHandler http = new HttpHandler();
http.get(url, file);
}
/**
* Check if SD card is ready and already mounted
* TODO: JavaScript Call backs for success and error handling
*/
public int testSaveLocationExists(){
if (fileManager.testSaveLocationExists())
return 0;
else
return 1;
}
/**
* Check if a specific directory of file exists
* TODO: JavaScript Call backs for success and error handling
*/
public int testDirOrFileExists(String file){
if (fileManager.isDirtoryOrFileExists(file))
return 0;
else
return 1;
}
/**
* Delete a specific directory.
* Everyting in side the directory would be gone.
* TODO: JavaScript Call backs for success and error handling
*/
public int deleteDirectory (String dir){
if (fileManager.deleteDir(dir))
return 0;
else
return 1;
}
/**
* Delete a specific file.
* TODO: JavaScript Call backs for success and error handling
*/
public int deleteFile (String file){
if (fileManager.deleteFile(file))
return 0;
else
return 1;
}
/**
* Create a new directory.
* TODO: JavaScript Call backs for success and error handling
*/
public int createDirectory(String dir){
if (fileManager.createDirectory(dir))
return 0;
else
return 1;
}
/**
* AUDIO
* TODO: Basic functions done but needs more work on error handling and call backs, remove record hack
*/
public void startRecordingAudio(String file)
{
/* for this to work the recording needs to be specified in the constructor,
* a hack to get around this, I'm moving the recording after it's complete
*/
audio.startRecording(file);
}
public void stopRecordingAudio()
{
audio.stopRecording();
}
public void startPlayingAudio(String file)
{
audio.startPlaying(file);
}
public void stopPlayingAudio()
{
audio.stopPlaying();
}
public long getCurrentPositionAudio()
{
System.out.println(audio.getCurrentPosition());
return(audio.getCurrentPosition());
}
public long getDurationAudio(String file)
{
System.out.println(audio.getDuration(file));
return(audio.getDuration(file));
}
public void setAudioOutputDevice(String output){
audio.setAudioOutputDevice(output);
}
public int getAudioOutputDevice(){
return audio.getAudioOutputDevice();
}
public String getLine1Number() {
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getLine1Number());
}
public String getVoiceMailNumber() {
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getVoiceMailNumber());
}
public String getNetworkOperatorName(){
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getNetworkOperatorName());
}
public String getSimCountryIso(){
TelephonyManager tm =
(TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
return(tm.getSimCountryIso());
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return(tz.getID());
}
}
|
package kdkbot;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.jibble.pircbot.*;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
import kdkbot.channel.*;
import kdkbot.commands.MessageParser;
import kdkbot.filemanager.*;
import kdkbot.language.*;
import sx.blah.discord.api.IDiscordClient;
public class Kdkbot extends PircBot {
public static HashMap<String, Channel> CHANS = new HashMap<String, Channel>();
public static Kdkbot instance;
public static String botLanguage = "enUS";
public Config botCfg = new Config(FileSystems.getDefault().getPath("./cfg/settings.cfg"));
public ArrayList<String> msgIgnoreList = new ArrayList<String>();
private boolean _verbose = false;
private boolean _logChat = false;
private Pattern logIgnores;
private Log logger;
public Debugger dbg;
private WebInterfaceWatcher webWatcher;
private IDiscordClient platform_discord;
private HashMap<String, ArrayList<String>> messageDuplicatorList;
// Twitter related variables
boolean useTwitter = true;
static Twitter status;
/**
* Initialization of the basic bot
*/
public Kdkbot() throws Exception {
if(instance == null) { // Protection against initializing the bot more than once - singleton!
instance = this;
} else {
throw new Exception("Bot instance already created!");
}
// Setup log system
botCfg.loadConfigContents();
this._logChat = Boolean.parseBoolean(botCfg.getSetting("logChat"));
logIgnores = Pattern.compile(botCfg.getSetting("logIgnores"));
// Setup this instances chat logger
if(_logChat) {
this.logger = new Log();
}
// Setup the debugger instance
this.dbg = new Debugger(false);
if(botCfg.getSetting("enableDebug", "0").equalsIgnoreCase("0")) {
dbg.disable();
} else {
dbg.enable();
}
// Setup this bot
this.setEncoding("UTF-8");
this.setName(botCfg.getSetting("nick"));
this._verbose = Boolean.parseBoolean(botCfg.getSetting("verbose"));
this.setVerbose(_verbose);
@SuppressWarnings("unused") // Is it really unused? Is it really?
boolean connectionSent = false;
do {
try {
this.connect(botCfg.getSetting("irc"), Integer.parseInt(botCfg.getSetting("port")), "oauth:" + botCfg.getSetting("oauth"));
connectionSent = true;
} catch(UnknownHostException e) {
logger.logln(String.format(Translate.getTranslate("log.failedToResolveDelay", botLanguage), botCfg.getSetting("irc")));
Thread.sleep(10 * 1000); // 10s * 1000ms
}
} while (connectionSent = false);
messageDuplicatorList = new HashMap<String, ArrayList<String>>();
// Get channels
String[] cfgChannels = botCfg.getSetting("channels").split(",");
// Join channels
for(int i = 0; i < cfgChannels.length; i++) {
if(cfgChannels[i].startsWith("#") == false) {
cfgChannels[i] = "#" + cfgChannels[i];
}
CHANS.put(cfgChannels[i], new Channel(this, cfgChannels[i]));
dbg.writeln(this, "Added new channel object for channel: " + cfgChannels[i]);
dbg.writeln(this, "Channel object: " + getChannel(cfgChannels[i]));
}
// Instantiate a MessageParser
new MessageParser();
// Setup Twitter interface
if (useTwitter) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(botCfg.getSetting("twitterOAuthConsumer"))
.setOAuthConsumerSecret(botCfg.getSetting("twitterOAuthConsumerSecret"))
.setOAuthAccessToken(botCfg.getSetting("twitterOAuth"))
.setOAuthAccessTokenSecret(botCfg.getSetting("twitterOAuthSecret"));
TwitterFactory tf = new TwitterFactory(cb.build());
status = tf.getInstance();
}
// Setup Discord interface
platform_discord = kdkbot.discord.Core.createClient(botCfg.getSetting("disc_pass"), true);
// Setup web related info
if (Boolean.parseBoolean(botCfg.getSetting("webEnabled"))) {
System.out.println("Enabled Web Watcher.");
System.out.println("Watching @ " + botCfg.getSetting("watcherLocation"));
webWatcher = new WebInterfaceWatcher(botCfg.getSetting("watcherLocation"), botCfg.getSetting("watcherFile"));
webWatcher.watch();
}
}
/**
* Event handler for disconnecting from a server
*/
@Override
public void onDisconnect() {
logger.log("Bot has disconnected. Will be attempting to re-join.");
boolean hasReconnected = false;
int retryAttempts = 1;
do {
logger.logln("Reconnection retry #" + retryAttempts);
try {
if((retryAttempts - 1) % 100 == 0) {
status.updateStatus(Translate.getTranslate("twitter.disconnectStatus", botLanguage));
}
this.reconnect();
// Iterator<Channel> chanIter = CHANS.iterator();
Iterator<Entry<String, Channel>> chanIter = CHANS.entrySet().iterator();
while(chanIter.hasNext()) {
Map.Entry<String, Channel> chan = chanIter.next();
chan.getValue().joinChannel();
}
hasReconnected = true;
} catch (NickAlreadyInUseException e) {
logger.logln(Translate.getTranslate("log.nickInUse", botLanguage));
} catch (UnknownHostException e) {
logger.logln(String.format(Translate.getTranslate("log.failedToResolve", botLanguage), botCfg.getSetting("irc")));
} catch (IOException e) {
e.printStackTrace();
} catch (IrcException e) {
logger.logln(Translate.getTranslate("log.ircException", botLanguage));
} catch (TwitterException e) {
}
// Only sleep if we havent reconnected, otherwise we can safely exit this function.
if(!hasReconnected) {
try {
// 10s * 1000ms
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
retryAttempts++;
} while(!hasReconnected);
try {
status.updateStatus(Translate.getTranslate("twitter.reconnectStatus", botLanguage));
} catch (TwitterException e) {
e.printStackTrace();
}
}
/**
* Event handler for connecting (successfully) to a server
*/
public void onConnect() {
// Re-establishes JOIN/LEAVE msges per Twitch IRCv3 implementation
sendRawLine("CAP REQ :twitch.tv/membership");
}
/**
* Overrides the PIRC implementation of logging to console for purposes of logging to file as well.
* @param line The line in which will be logged
*/
public void log(String line) {
super.log(line);
// Ensure we're logging chat, and if we are, ensure there isnt a line that needs to be ignored
if(this._logChat && !this.logIgnores.matcher(line).find()) {
logger.logln(System.currentTimeMillis() + " " + line);
}
}
/**
* Event handler for join messages received
*/
public void onJoin(String channel, String sender, String login, String hostname) {
Channel curChan = getChannel(channel);
int senderRank = 0;
if(curChan != null) { senderRank = curChan.getSenderRank(sender); }
MessageInfo info = new MessageInfo(channel, sender, "#JOIN", login, hostname, senderRank);
if(curChan != null) { curChan.extraHandler(info); }
}
/**
* Event handler for part messages received
*/
public void onPart(String channel, String sender, String login, String hostname) {
Channel curChan = getChannel(channel);
int senderRank = 0;
if(curChan != null) { senderRank = curChan.getSenderRank(sender); }
MessageInfo info = new MessageInfo(channel, sender, "#JOIN", login, hostname, senderRank);
curChan.extraHandler(info);
}
/**
* Event handler for action messages received
*/
public void onAction(String sender, String login, String hostname, String target, String action) {
if(messageDuplicatorList.get(target) != null) {
Iterator<String> msgDupeIter = messageDuplicatorList.get(target).iterator();
while(msgDupeIter.hasNext()) {
this.sendMessage(msgDupeIter.next(), "*" + sender + " " + action + "*");
}
}
CHANS.get(target).messageHandler(new MessageInfo(target, sender, action, login, hostname, CHANS.get(target).getSenderRank(sender)));
}
public void onUnknown(String msg) {
System.out.println("UNKNOWN MESSAGE: " + msg);
}
/**
* Event handler for messages received
*/
public void onMessage(String channel, String sender, String login, String hostname, String message) {
// Message Duplicator
if(messageDuplicatorList.get(channel) != null && !sender.equalsIgnoreCase("coebot") && !sender.equalsIgnoreCase("jtv") && !sender.equalsIgnoreCase("monstercat")) {
Iterator<String> msgDupeIter = messageDuplicatorList.get(channel).iterator();
while(msgDupeIter.hasNext()) {
this.sendMessage(msgDupeIter.next(), sender + ": " + message);
}
}
MessageInfo info = new MessageInfo(channel, sender, message, login, hostname, CHANS.get(channel).getSenderRank(sender));
// Master Commands Handler
handleMasterCommands(info);
CHANS.get(channel).messageHandler(info);
}
public Channel getChannel(String channel) {
dbg.writeln(this, "Requested for channel object for channel " + channel);
if(!channel.startsWith("
channel = "#" + channel;
}
return Kdkbot.CHANS.get(channel);
}
/**
* Sets up and joins a particular channel
* @param channel The channel to join
* @return -1 if it is already in the channel, 1 if successful, any other value means unsuccessful
*/
public int enterChannel(String channel) {
Kdkbot.instance.dbg.writeln(this, "Entering channel: " + channel);
if (! channel.startsWith("
channel = "#" + channel;
}
if(this.botCfg.getSetting("channels").contains(channel)) {
Kdkbot.instance.dbg.writeln(this, "Channel already entered: " + channel);
return -1;
} else {
Kdkbot.instance.dbg.writeln(this, "Channel not yet entered: " + channel);
// Join channel
this.sendMessage(channel, String.format(Translate.getTranslate("channel.join", botLanguage), channel));
CHANS.put(channel, new Channel(this, channel));
// Add channel to settings cfg
botCfg.setSetting("channels", botCfg.getSetting("channels") + "," + channel);
Channel chan = getChannel(channel);
Kdkbot.instance.dbg.writeln(this, "Adding users " + botCfg.getSetting("masterCommands") + " and " + channel.substring(1) + " to sender rank 5");
chan.setSenderRank(botCfg.getSetting("masterCommands"), 5);
chan.setSenderRank(channel.substring(1), 5);
chan.saveSenderRanks();
// Initialize new commands list for channel if the channel info doesn't exist
Path path = FileSystems.getDefault().getPath("./cfg/" + channel).toAbsolutePath();
if(Files.notExists(path)) {
try {
FileInputStream cmdIn = new FileInputStream(FileSystems.getDefault().getPath("./cfg/default/cmds.cfg").toAbsolutePath().toString());
FileOutputStream cmdOut = new FileOutputStream(FileSystems.getDefault().getPath("./cfg/" + channel + "/cmds.cfg").toAbsolutePath().toString());
cmdOut.getChannel().transferFrom(cmdIn.getChannel(), 0, cmdIn.getChannel().size());
cmdIn.close();
cmdOut.close();
} catch (IOException e) {
// chan.sendMessage(Translate.getTranslate("channel.badInitialize", botLanguage));
}
} // else we don't need to attempt to create a new instance for the channels commands
return 1;
}
}
/**
* Exits a given channel
* @param channel The channel to leave
*/
public void exitChannel(String channel) {
if (! channel.startsWith("
channel = "#" + channel;
}
// Leave channel
this.partChannel(channel);
// Remove it from setting list
String prevChanSetting = botCfg.getSetting("channels");
// Remove it from the setting
prevChanSetting = prevChanSetting.replace(channel, "");
// Remove duplicated commas that can result from removing from channel
prevChanSetting = prevChanSetting.replace(",,", ",");
botCfg.setSetting("channels", prevChanSetting);
botCfg.saveSettings();
}
/**
* Determine if the bot exists in a particular channel
* @param channel The channel to look up
* @return True if the bot is in the channel, false otherwise
*/
public boolean isInChannel(String channel) {
return (this.getChannel(channel) == null) ? false : true;
}
/**
* Master commands: These commands are designated to be used for debugging purposes or otherwise control the bot that has not been fully implemented in other ways.
* @param info The message information to use for parsing
*/
public void handleMasterCommands(MessageInfo info) {
// Master Commands
if(info.sender.equalsIgnoreCase(botCfg.getSetting("masterCommands")) && info.message.startsWith("&&")) {
if(info.message.startsWith("&&debug disable")) {
dbg.disable();
this.sendMessage(info.channel, "Disabled internal debug messages");
} else if(info.message.startsWith("&&debug enable")) {
dbg.enable();
this.sendMessage(info.channel, "Enabled internal debug messages");
} else if (info.message.startsWith("&&ClrLangCache")) {
Translate.resetLanguageCache();
this.sendMessage(info.channel, "Reset language cache");
} else if(info.message.startsWith("&&ReloadNodeData")) {
kdkbot.api.warframe.InternalTranslator.reloadNodeData();
this.sendMessage(info.channel, "Reloaded node data for Warframe");
} else if(info.message.startsWith("&&stop")) {
this.disconnect();
System.exit(0);
} else if(info.message.startsWith("&&echo " )) {
String messageToSend = info.message.substring("&&echo ".length());
this.sendMessage(info.channel, messageToSend);
} else if(info.message.startsWith("&&echoto ")) {
String messageArgs[] = info.message.split(" ", 3);
this.sendMessage(messageArgs[1], messageArgs[2]);
} else if(info.message.startsWith("&&echotoall ")) {
String messageArgs[] = info.message.split(" ", 2);
Iterator<Entry<String, Channel>> chanIter = CHANS.entrySet().iterator();
while(chanIter.hasNext()) {
Map.Entry<String, Channel> pairs = chanIter.next();
this.sendMessage(pairs.getKey().toString(), messageArgs[1]);
}
} else if(info.message.startsWith("&&color ")) {
String colorArgs[] = info.message.split(" ");
this.sendMessage(info.channel, "/color " + colorArgs[1]);
this.sendMessage(info.channel, String.format(Translate.getTranslate("bot.mastercommands.color", botLanguage), colorArgs[1]));
} else if(info.message.startsWith("&&status ")) {
try {
Kdkbot.status.updateStatus(info.message.substring("&&status ".length()));
Kdkbot.instance.sendMessage(info.channel, Translate.getTranslate("bot.mastercommands.status", botLanguage));
} catch (TwitterException e) {
Kdkbot.instance.sendMessage(info.channel, String.format(Translate.getTranslate("bot.mastercommands.statusFail", botLanguage), e.getMessage()));
e.printStackTrace();
}
} else if(info.message.startsWith("&&ram?")) {
Kdkbot.instance.sendMessage(info.channel, String.format(Translate.getTranslate("bot.mastercommands.ram", botLanguage), (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024));
} else if(info.message.startsWith("&&gc")) {
Kdkbot.instance.sendMessage(info.channel, Translate.getTranslate("bot.mastercommands.gc", botLanguage));
System.gc();
System.gc();
}
}
}
/**
* Gets the client ID for twitch
* @return The Client ID in plain text for twitch
*/
public String getClientID() {
return botCfg.getSetting("clientId");
}
/**
* Sends a message through a channels sendMessage function
* @param channel The channel to find, and consequently send the message through
* @param message The message to be sent
*/
public void sendChanMessage(String channel, String message) {
try {
Channel chan = getChannel(channel);
chan.sendMessage(message);
} catch(NullPointerException e) {
// In the event an invalid channel is provided, we don't care, toss away the request.
return;
}
}
/**
* Sends a message through a channels sendMessage function
* @param channel The channel to find, and consequently send the message through
* @param key The key to find in a channels language file
* @param formatArgs The format args
*/
public void sendChanMessageTrans(String channel, String key, Object... formatArgs) {
try {
Channel chan = getChannel(channel);
chan.sendMessage(String.format(Translate.getTranslate(key, chan.getLang()), formatArgs));
} catch(NullPointerException e) {
// In the event an invalid channel is provided, we don't care, toss away the request.
return;
}
}
}
|
/*
* Even Fibonacci numbers
*
* Problem 2
*
* Each new term in the Fibonacci sequence is generated by adding the previous two terms.
* By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*
* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*
* Expected result: 4613732
*/
public class Euler2 {
public static void main(String[] args){
/** Determina valores iniciais para os primeiros dois fibonacci */
long firstFibo = 0;
long secondFibo = 1;
long nextFibo = firstFibo + secondFibo;
long sum = 0;
while (nextFibo <= 4000000){
if (nextFibo % 2 == 0){
sum += nextFibo;
}
firstFibo = secondFibo;
secondFibo = nextFibo;
nextFibo = firstFibo + secondFibo;
}
System.out.println(sum);
}
}
|
import java.util.Scanner;
import java.util.ArrayList;
import java.awt.Point;
public class Parser{
private static final char BLACK = 'b';
private static final char WHITE = 'w';
private static final char EMPTY = ' ';
public static void main(String[] args){
/* Read from stdin */
Scanner scan = new Scanner(System.in);
String[] dims = scan.nextLine().split("\\s+");
int w = Integer.parseInt(dims[0]);
int h = Integer.parseInt(dims[1]);
char player = scan.nextLine().charAt(0);
char opponent = (player == BLACK ? WHITE : BLACK);
char[][] board = new char[h][w];
for (int y = 0; y < h; y++){
board[y] = scan.nextLine().toCharArray();
}
/*
Find the best place to put my piece.
- For each empty space, find the number of white pieces caught in a group had a player piece been there.
- Will need Group class with method for checking if is next to empty space.
- Group will have a list of coordinates that makes it up.
- A group will be made from a starting space and adding adjacent spaces into the list of coordinates.
- Given a space, get an array of all adjascent spaces with corresponding pieces and add them to a queue. While the queue is not empty, get the first element of the queue, find all adjacent pieces, add them to the queue, then finally add the current element to the list of coordinates.
- All the while, keep track of how many open spaces are next to the group. The group cannot be blocked if it has more that 1 emprt adja
1. Find all existing white groups
2. For each empty space, check for how many white pieces in groups are caught. Groups are caught if they are not next to any open spaces.
3. Pick the space with the largest number of white pieces caught.
*/
boolean checkedPoints[][] = new boolean[h][w];
ArrayList<Point> emptySpaces = new ArrayList<>();
ArrayList<Group> groups = new ArrayList<>();
for (int y = 0; y < h; y++){
for (int x = 0; x < w; x++){
char c = board[y][x];
if (!checkedPoints[y][x]){
Point p = new Point(x,y);
if (c == EMPTY){
emptySpaces.add(p);
}
else if (c == opponent){
Group g = new Group(x,y,board,opponent);
Point[] coordinates = g.getCoordinates();
for (Point coord : coordinates){
checkedPoints[(int)coord.getY()][(int)coord.getX()] = true;
}
groups.add(g);
}
checkedPoints[y][x] = true;
}
}
}
// Compare the scores
Point bestPoint = null;
int maxScore = 0;
for (Point p : emptySpaces){
int score = 0;
for (Group g : groups){
Point[] adjEmptSpaces = g.getEmptyAdjascentSpaces();
if (adjEmptSpaces.length == 1){
if (adjEmptSpaces[0].equals(p)){
score += g.getCoordinates().length;
}
}
}
if (score > maxScore){
maxScore = score;
bestPoint = p;
}
}
/* Print stuff */
if (bestPoint == null){
System.out.println("No constructive move");
}
else {
System.out.println("(" + (int)bestPoint.getX() + ", " + (int)bestPoint.getY() + ")");
}
}
}
|
package leaptest;
import leaptest.view.HandView;
import leaptest.view.Floor;
import leaptest.controller.KeyboardDebugControl;
import leaptest.controller.LeapHandControl;
import com.jme3.app.SimpleApplication;
import com.jme3.app.StatsAppState;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.shadow.EdgeFilteringMode;
import com.leapmotion.leap.Controller;
import java.util.ArrayList;
import leaptest.controller.GridGravityControl;
import leaptest.controller.BlockContainerColorControl;
import leaptest.controller.BlockContainerDissolveControl;
import leaptest.controller.BlockContainerShadowControl;
import leaptest.controller.BlockDragControl;
import leaptest.controller.BlockTargetHelperControl;
import leaptest.controller.CreationBlockColorControl;
import leaptest.controller.GestureGrabControl;
import leaptest.controller.GestureRotateControl;
import leaptest.controller.GridCamControl;
import leaptest.controller.GridRingColorControl;
import leaptest.controller.KeyboardGridCamControl;
import leaptest.controller.KeyboardGridControl;
import leaptest.controller.KeyboardGridSaveControl;
import leaptest.controller.KeyboardTweakerControl;
import leaptest.controller.MouseBlockControl;
import leaptest.controller.TaskManagerControl;
import leaptest.controller.Updatable;
import leaptest.model.Block;
import leaptest.model.BlockContainer;
import leaptest.model.Grid;
import leaptest.model.GridCam;
import leaptest.model.LeapCalibrator;
import leaptest.model.TaskManager;
import leaptest.utils.ConfigSettings;
import leaptest.utils.DefaultAppSettings;
import leaptest.utils.Log;
import leaptest.utils.Tweaker;
import leaptest.view.MaterialManager;
import leaptest.view.GridLines;
import leaptest.view.GridRing;
import leaptest.view.ModelDisplay;
/**
* Main class executes a simple JMonkeyEngine Application It loads application
* settings from "settings.txt"
*
* @author sil
*/
public class Main extends SimpleApplication
{
private ConfigSettings config;
private Controller leap;
private ArrayList<Updatable> controllers;
private Log log;
private boolean stopping;
private long begintimestamp;
/**
* Loads application config settings from file applies settings and fires up
* application
*
* @param args - ignored
*/
public static void main(String[] args)
{
ConfigSettings config = new ConfigSettings("config.txt");
Main app = new Main(config);
DefaultAppSettings.apply(app, config);
app.start();
}
/**
* Constructor for application overrides basic AppState and makes
* configuration locally available
*
* @param config ConfigSettings for application
*/
public Main(ConfigSettings config)
{
super(new StatsAppState());
this.config = config;
}
@Override
public void simpleInitApp()
{
// Init MaterialManager
MaterialManager.init(assetManager);
// MODELS
// Model settings...
begintimestamp = System.currentTimeMillis();
int griddim = Integer.parseInt(config.getValue("GridSize"));
float cameradistance = Float.parseFloat(config.getValue("CamDist")),
cameraangle = Float.parseFloat(config.getValue("CamAngle"));
Vector3f blockdims = Vector3f.UNIT_XYZ.mult(Float.parseFloat(config.getValue("BlockSize")));
// Add models
log = new Log(config.isSet("Log"));
BlockContainer world = new BlockContainer();
GridCam camera = new GridCam(cameradistance, cameraangle, Vector3f.ZERO);
Grid grid = new Grid(griddim, griddim, griddim, blockdims);
float creationblockstartpos = (config.isSet("Righthanded") ? 1f : -1f);
Block creationblock = new Block(MaterialManager.creationblock, new Vector3f(creationblockstartpos*(grid.getRadius() + 1 * blockdims.x), blockdims.y / 2, 0f), blockdims);
TaskManager taskmanager = (config.isSet("TaskManager") ? new TaskManager(config.getValue("ModelFolder")) : null);
Tweaker tweaker = new Tweaker();
// VIEWS
// Set viewports
viewPort.setBackgroundColor(ColorRGBA.DarkGray);
// Build scene from view models
GridRing gridring = new GridRing(grid.getRadius());
HandView handmodel = new HandView(assetManager);
Floor floor = new Floor(300);
GridLines gridlines = new GridLines(grid.getDimensions()[0] + 2, grid.getCellDimensions().x, grid.getRadius());
rootNode.attachChild(grid);
grid.attachChild(gridlines);
grid.attachChild(gridring);
rootNode.attachChild(handmodel);
rootNode.attachChild(floor);
rootNode.attachChild(world);
rootNode.attachChild(creationblock);
// Add lights
DirectionalLight sun = new DirectionalLight();
sun.setColor(ColorRGBA.White.mult(0.2f));
sun.setDirection(Vector3f.UNIT_Y.negate());
rootNode.addLight(sun);
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(0.8f));
rootNode.addLight(al);
// FILTERS aka post-processors (order matters!!)
// Add shadows
final int SHADOWMAP_SIZE = 1024;
DirectionalLightShadowRenderer dlsr = new DirectionalLightShadowRenderer(assetManager, SHADOWMAP_SIZE, 3);
dlsr.setEnabledStabilization(false);
dlsr.setEdgeFilteringMode(EdgeFilteringMode.Nearest);
dlsr.setLight(sun);
viewPort.addProcessor(dlsr);
// CONTROLS
// Set-up looping controllers (order matters!!)
controllers = new ArrayList<Updatable>();
TaskManagerControl taskcontrol = new TaskManagerControl(taskmanager, grid, this, Long.parseLong(config.getValue("TimerInterval")));
if (taskmanager!=null && config.isSet("Timer"))
controllers.add(taskcontrol);
// Create a Leap Motion interface and put it within the calibrator
leap = new Controller();
LeapCalibrator calib = new LeapCalibrator(leap);
if (config.isSet("Leap"))
{
LeapHandControl leapHandControl = new LeapHandControl(calib, handmodel);
BlockDragControl blockDragControl = new BlockDragControl(world, grid, creationblock, taskcontrol);
GestureGrabControl gestureGrabControl = new GestureGrabControl(calib, blockDragControl, config.isSet("Righthanded"));
GestureRotateControl gestureRotateControl = new GestureRotateControl(calib, grid, camera, config.isSet("RightHanded"));
controllers.add(leapHandControl);
controllers.add(gestureGrabControl);
controllers.add(gestureRotateControl);
controllers.add(new BlockTargetHelperControl(blockDragControl, rootNode, blockdims));
tweaker.registerTweakable(calib);
tweaker.registerTweakable(gestureGrabControl);
tweaker.registerTweakable(gestureRotateControl);
if (config.isSet("Log"))
{
log.addLoggable(blockDragControl);
log.addLoggable(leapHandControl);
log.addLoggable(gestureGrabControl);
log.addLoggable(gestureRotateControl);
}
}
// Add keyboard control
inputManager.clearMappings();
if (config.isSet("DebugESC"))
controllers.add(new KeyboardDebugControl(this));
if (config.isSet("Debug"))
{
controllers.add(new KeyboardTweakerControl(inputManager, tweaker, config.getValue("SetFolder"), config.getValue("SetExtension")));
if (config.isSet("DebugGridSaver"))
controllers.add(new KeyboardGridSaveControl(inputManager, grid, config.getValue("ModelFolder") + config.getValue("ModelFile")));
} else {
tweaker.loadTweakSets(config.getValue("SetFolder"), config.getValue("SetExtension"));
}
if (config.isSet("MouseAndKeyboard"))
{
// Add keyboard control
KeyboardGridControl kbGridControl = new KeyboardGridControl(inputManager, grid);
KeyboardGridCamControl kbGridCamControl = new KeyboardGridCamControl(inputManager, camera);
controllers.add(kbGridControl);
controllers.add(kbGridCamControl);
// Add mouse control
BlockDragControl blockDragControl = new BlockDragControl(world, grid, creationblock, taskcontrol);
MouseBlockControl mouseBlockControl = new MouseBlockControl(inputManager, cam, blockDragControl);
controllers.add(mouseBlockControl);
controllers.add(new BlockTargetHelperControl(blockDragControl, rootNode, blockdims));
if (config.isSet("Log"))
{
log.addLoggable(blockDragControl);
log.addLoggable(mouseBlockControl);
log.addLoggable(kbGridControl);
log.addLoggable(kbGridCamControl);
}
}
// Add model effectors
controllers.add(new GridCamControl(cam, camera));
controllers.add(new GridGravityControl(grid, world));
controllers.add(new BlockContainerDissolveControl(world));
// Add visual effectors
if (config.isSet("ShowModelImage") && config.isSet("TaskManager"))
{
ModelDisplay modeldisplay = new ModelDisplay(assetManager, settings, taskmanager, grid, config.getValue("ModelImgBase"));
guiNode.attachChild(modeldisplay);
controllers.add(modeldisplay);
}
controllers.add(new BlockContainerColorControl(grid));
controllers.add(new BlockContainerColorControl(world));
controllers.add(new CreationBlockColorControl(creationblock));
controllers.add(new GridRingColorControl(grid, gridring));
controllers.add(new BlockContainerShadowControl(grid, blockdims));
controllers.add(new BlockContainerShadowControl(world, blockdims));
// Add loggables to log (order matters for the log order in log.txt)
if (config.isSet("Log"))
{
if (taskmanager != null)
log.addLoggable(taskmanager);
log.addLoggable(camera);
log.addLoggable(grid);
}
}
/**
* Set shutdown flag
* @param shutdown true to shutdown on next update
*/
public void setShutDown(boolean shutdown)
{
stopping = shutdown;
}
@Override
public void simpleUpdate(float tpf)
{
long timestamp = System.currentTimeMillis() - begintimestamp;
log.addEntry(Log.EntryType.Frame, Long.toString(timestamp));
log.log();
for (Updatable c : controllers)
c.update(tpf);
if (stopping)
shutDown();
}
@Override
public void simpleRender(RenderManager rm)
{
}
/**
* Gracefully shutdowns the application and Leap and stores log to file
*/
private void shutDown()
{
System.out.println("Shutting down...");
leap.delete();
if (log.isEnabled())
{
String logfile = config.getValue("LogFolder") + config.getValue("UserNumber") + ".log";
log.save(logfile);
System.out.println("Saved log to: " + logfile);
}
stop();
}
}
|
package leaptest;
import leaptest.view.HandView;
import leaptest.view.Floor;
import leaptest.controller.KeyboardDebugControl;
import leaptest.controller.LeapHandControl;
import com.jme3.app.SimpleApplication;
import com.jme3.app.StatsAppState;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.shadow.EdgeFilteringMode;
import com.leapmotion.leap.Controller;
import java.util.ArrayList;
import leaptest.controller.GridGravityControl;
import leaptest.controller.BlockContainerColorControl;
import leaptest.controller.BlockContainerDissolveControl;
import leaptest.controller.BlockContainerShadowControl;
import leaptest.controller.BlockDragControl;
import leaptest.controller.BlockTargetHelperControl;
import leaptest.controller.GestureGrabControl;
import leaptest.controller.GestureRotateControl;
import leaptest.controller.GridCamControl;
import leaptest.controller.GridRingColorControl;
import leaptest.controller.KeyboardGridCamControl;
import leaptest.controller.KeyboardGridControl;
import leaptest.controller.KeyboardGridSaveControl;
import leaptest.controller.KeyboardTweakerControl;
import leaptest.controller.MouseBlockControl;
import leaptest.controller.Updatable;
import leaptest.model.Block;
import leaptest.model.BlockContainer;
import leaptest.model.Grid;
import leaptest.model.GridCam;
import leaptest.model.LeapCalibrator;
import leaptest.model.TaskManager;
import leaptest.utils.ConfigSettings;
import leaptest.utils.DefaultAppSettings;
import leaptest.utils.Log;
import leaptest.utils.Tweaker;
import leaptest.view.BlockCap;
import leaptest.view.MaterialManager;
import leaptest.view.GridLines;
import leaptest.view.GridRing;
import leaptest.view.ModelDisplay;
/**
* Main class executes a simple JMonkeyEngine Application It loads application
* settings from "settings.txt"
*
* @author sil
*/
public class Main extends SimpleApplication
{
private ConfigSettings config;
private Controller leap;
private ArrayList<Updatable> controllers;
private Log log;
private boolean stopping;
private BlockDragControl blockDragControl;
private LeapHandControl leapHandControl;
private GestureGrabControl gestureGrabControl;
private GestureRotateControl gestureRotateControl;
private MouseBlockControl mouseBlockControl;
private KeyboardGridControl kbGridControl;
private KeyboardGridCamControl kbGridCamControl;
/**
* Loads application config settings from file applies settings and fires up
* application
*
* @param args - ignored
*/
public static void main(String[] args)
{
ConfigSettings config = new ConfigSettings("config.txt");
Main app = new Main(config);
DefaultAppSettings.apply(app, config);
app.start();
}
/**
* Constructor for application overrides basic AppState and makes
* configuration locally available
*
* @param config ConfigSettings for application
*/
public Main(ConfigSettings config)
{
super(new StatsAppState());
this.config = config;
}
@Override
public void simpleInitApp()
{
// Init MaterialManager
MaterialManager.init(assetManager);
// MODELS
// Model settings...
int griddim = Integer.parseInt(config.getValue("GridSize"));
float cameradistance = Float.parseFloat(config.getValue("CamDist")),
cameraangle = Float.parseFloat(config.getValue("CamAngle"));
Vector3f blockdims = Vector3f.UNIT_XYZ.mult(Float.parseFloat(config.getValue("BlockSize")));
// Add models
log = new Log(config.isSet("Log"));
BlockContainer world = new BlockContainer();
GridCam camera = new GridCam(cameradistance, cameraangle, Vector3f.ZERO);
Grid grid = new Grid(griddim, griddim, griddim, blockdims);
float creationblockstartpos = (config.isSet("Righthanded") ? 1f : -1f);
Block creationblock = new Block(MaterialManager.creationblock, new Vector3f(creationblockstartpos*(grid.getRadius() + 2 * blockdims.x), blockdims.y / 2, 0f), blockdims);
TaskManager taskmanager = (config.isSet("TaskManager") ? new TaskManager(config.getValue("ModelFolder")) : null);
Tweaker tweaker = new Tweaker();
// VIEWS
// Set viewports
viewPort.setBackgroundColor(ColorRGBA.DarkGray);
// Build scene from view models
GridRing gridring = new GridRing(grid.getRadius());
HandView handmodel = new HandView(assetManager);
Floor floor = new Floor(300);
GridLines gridlines = new GridLines(grid.getDimensions()[0] + 2, grid.getCellDimensions().x, grid.getRadius());
rootNode.attachChild(grid);
grid.attachChild(gridlines);
grid.attachChild(gridring);
rootNode.attachChild(handmodel);
rootNode.attachChild(floor);
rootNode.attachChild(world);
rootNode.attachChild(creationblock);
BlockCap blockcap = new BlockCap(blockdims);
BlockCap cblockcap = (BlockCap) blockcap.clone();
cblockcap.move(creationblock.getLocalTranslation());
cblockcap.rotate(-FastMath.PI * 0.5f, 0, 0);
cblockcap.setMaterial(creationblock.getMaterial());
cblockcap.setShadowMode(ShadowMode.Receive);
rootNode.attachChild(cblockcap);
// Add lights
DirectionalLight sun = new DirectionalLight();
sun.setColor(ColorRGBA.White.mult(0.2f));
sun.setDirection(Vector3f.UNIT_Y.negate());
rootNode.addLight(sun);
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(0.8f));
rootNode.addLight(al);
// FILTERS aka post-processors (order matters!!)
// Add shadows
final int SHADOWMAP_SIZE = 1024;
DirectionalLightShadowRenderer dlsr = new DirectionalLightShadowRenderer(assetManager, SHADOWMAP_SIZE, 3);
dlsr.setEnabledStabilization(false);
dlsr.setEdgeFilteringMode(EdgeFilteringMode.Nearest);
dlsr.setLight(sun);
viewPort.addProcessor(dlsr);
// CONTROLS
// Set-up looping controllers (order matters!!)
controllers = new ArrayList<Updatable>();
// Create a Leap Motion interface and put it within the calibrator
leap = new Controller();
LeapCalibrator calib = new LeapCalibrator(leap);
if (config.isSet("Leap"))
{
leapHandControl = new LeapHandControl(calib, handmodel);
blockDragControl = new BlockDragControl(world, grid, creationblock, taskmanager);
gestureGrabControl = new GestureGrabControl(calib, blockDragControl, config.isSet("Righthanded"));
gestureRotateControl = new GestureRotateControl(calib, grid, camera);
controllers.add(leapHandControl);
controllers.add(gestureGrabControl);
controllers.add(gestureRotateControl);
controllers.add(new BlockTargetHelperControl(blockDragControl, rootNode, blockdims));
if (config.isSet("Debug"))
{
tweaker.registerTweakable(gestureGrabControl);
tweaker.registerTweakable(gestureRotateControl);
}
}
// Add keyboard control
controllers.add(new KeyboardDebugControl(this));
if (config.isSet("Debug"))
{
tweaker.registerTweakable(calib);
controllers.add(new KeyboardTweakerControl(inputManager, tweaker, config.getValue("SetFolder"), config.getValue("SetExtension")));
if (config.isSet("DebugGridSaver"))
controllers.add(new KeyboardGridSaveControl(inputManager, grid, config.getValue("ModelFolder") + config.getValue("ModelFile")));
}
if (config.isSet("MouseAndKeyboard"))
{
// Add keyboard control
kbGridControl = new KeyboardGridControl(inputManager, grid);
kbGridCamControl = new KeyboardGridCamControl(inputManager, camera);
controllers.add(kbGridControl);
controllers.add(kbGridCamControl);
// Add mouse control
blockDragControl = new BlockDragControl(world, grid, creationblock, taskmanager);
mouseBlockControl = new MouseBlockControl(inputManager, cam, blockDragControl);
controllers.add(mouseBlockControl);
controllers.add(new BlockTargetHelperControl(blockDragControl, rootNode, blockdims));
}
// Add model effectors
controllers.add(new GridCamControl(cam, camera));
controllers.add(new GridGravityControl(grid, world));
controllers.add(new BlockContainerDissolveControl(world));
// Add visual effectors
if (config.isSet("ShowModelImage") && config.isSet("TaskManager"))
{
ModelDisplay modeldisplay = new ModelDisplay(assetManager, settings, taskmanager, grid, config.getValue("ModelImgBase"));
guiNode.attachChild(modeldisplay);
controllers.add(modeldisplay);
}
controllers.add(new BlockContainerColorControl(grid));
controllers.add(new BlockContainerColorControl(world));
controllers.add(new GridRingColorControl(grid, gridring));
controllers.add(new BlockContainerShadowControl(grid, blockdims, blockcap));
controllers.add(new BlockContainerShadowControl(world, blockdims, blockcap));
// Add loggables to log (order matters for the log order in log.txt)
if (config.isSet("Log"))
{
log.addLoggable(taskmanager);
if(config.isSet("Leap"))
{
log.addLoggable(leapHandControl);
log.addLoggable(gestureGrabControl);
log.addLoggable(blockDragControl);
log.addLoggable(gestureRotateControl);
log.addLoggable(camera);
log.addLoggable(grid);
}
else if (config.isSet("MouseAndKeyboard"))
{
log.addLoggable(mouseBlockControl);
log.addLoggable(blockDragControl);
log.addLoggable(kbGridControl);
log.addLoggable(grid);
log.addLoggable(kbGridCamControl);
log.addLoggable(camera);
}
}
}
/**
* Set shutdown flag
* @param shutdown true to shutdown on next update
*/
public void setShutDown(boolean shutdown)
{
stopping = shutdown;
}
@Override
public void simpleUpdate(float tpf)
{
log.log();
for (Updatable c : controllers)
c.update(tpf);
if (stopping)
shutDown();
}
@Override
public void simpleRender(RenderManager rm)
{
}
/**
* Gracefully shutdowns the application and Leap and stores log to file
*/
private void shutDown()
{
System.out.println("Shutting down...");
leap.delete();
if (log.isEnabled())
{
String logfile = config.getValue("LogFolder") + config.getValue("UserNumber") + ".log";
log.save(logfile);
System.out.println("Saved log to: " + logfile);
}
stop();
}
}
|
package lib;
import java.util.ArrayList;
import java.util.List;
/**
* Parse list of Strings to a List of tagged entities.
*/
public final class ParseList {
public static List<TaggedEntity> parseStringList(final List<String> toParse) {
List<TaggedEntity> retList = new ArrayList<>();
System.out.println(
String.join("", "[DEBUG] List has a length of: ",
Integer.toString(toParse.size()), "\n")
);
// check whether we are in a proper tag block. if not ignore all body lines until a next
// proper tag block starts.
Boolean properTag = true;
for (String currLine : toParse) {
if (currLine.contains("(
if (!currLine.endsWith("
System.out.println(String.join("", "[WARNING] Encountered incomplete Tag line. ",
"All lines until the next proper tag line will be ignored."));
properTag = false;
} else {
properTag = true;
System.out.println("[DEBUG] TagLine");
retList.add(new TaggedEntity());
String[] ls = currLine
.substring(currLine.indexOf("(#)") + "(#)".length(),
currLine.length() - "#)".length())
.split(",");
for (String s : ls) {
retList.get(retList.size() - 1).getTags().add(s);
}
}
} else if (!retList.isEmpty() & properTag) {
System.out.println("[DEBUG] BodyLine");
String currString = retList.get(retList.size()-1).getBody();
retList.get(retList.size()-1).setBody(
String.join("", currString, currLine, "\n")
);
} else {
System.out.println("[WARNING] Found line not connected to a tag, will be omitted.");
}
}
System.out.println(String.join("", "[DEBUG] # of Tagged entities: ",
Integer.toString(retList.size()))
);
retList.forEach(c -> System.out.println(
String.join("", "[DEBUG] ", "ID: ", c.getEntityID(), " Tags: ",
Integer.toString(c.getTags().size()), " ", c.getTags().toString(),
" Body: ", c.getBody()
)
)
);
return retList;
}
}
|
package controllers;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.sagebionetworks.bridge.BridgeConstants.STUDY_PROPERTY;
import org.sagebionetworks.bridge.BridgeConstants;
import org.sagebionetworks.bridge.exceptions.ConsentRequiredException;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.json.JsonUtils;
import org.sagebionetworks.bridge.models.Email;
import org.sagebionetworks.bridge.models.EmailVerification;
import org.sagebionetworks.bridge.models.PasswordReset;
import org.sagebionetworks.bridge.models.SignIn;
import org.sagebionetworks.bridge.models.SignUp;
import org.sagebionetworks.bridge.models.UserSession;
import org.sagebionetworks.bridge.models.UserSessionInfo;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl;
import org.springframework.stereotype.Controller;
import play.mvc.Result;
import com.fasterxml.jackson.databind.JsonNode;
@Controller("authenticationController")
public class AuthenticationController extends BaseController {
public Result signIn() throws Exception {
UserSession session = getSessionIfItExists();
if (session != null) {
setSessionToken(session.getSessionToken());
return okResult(new UserSessionInfo(session));
}
try {
JsonNode json = requestToJSON(request());
SignIn signIn = SignIn.fromJson(json);
Study study = getStudyOrThrowException(json);
session = authenticationService.signIn(study, signIn);
setSessionToken(session.getSessionToken());
Result result = okResult(new UserSessionInfo(session));
return result;
} catch(ConsentRequiredException e) {
setSessionToken(e.getUserSession().getSessionToken());
throw e;
}
}
public Result signOut() throws Exception {
UserSession session = getSessionIfItExists();
if (session != null) {
authenticationService.signOut(session.getSessionToken());
}
response().discardCookie(BridgeConstants.SESSION_TOKEN_HEADER);
return okResult("Signed out.");
}
public Result signUp() throws Exception {
JsonNode json = requestToJSON(request());
SignUp signUp = SignUp.fromJson(json, false);
Study study = getStudyOrThrowException(json);
authenticationService.signUp(study, signUp, true);
return createdResult("Signed up.");
}
public Result verifyEmail() throws Exception {
JsonNode json = requestToJSON(request());
EmailVerification emailVerification = EmailVerification.fromJson(json);
Study study = getStudyOrThrowException(json);
// In normal course of events (verify email, consent to research),
// an exception is thrown. Code after this line will rarely execute
UserSession session = authenticationService.verifyEmail(study, emailVerification);
setSessionToken(session.getSessionToken());
return okResult(new UserSessionInfo(session));
}
public Result resendEmailVerification() throws Exception {
JsonNode json = requestToJSON(request());
Email email = Email.fromJson(json);
StudyIdentifier studyIdentifier = getStudyIdentifierOrThrowException(json);
authenticationService.resendEmailVerification(studyIdentifier, email);
return okResult("A request to verify an email address was re-sent.");
}
public Result requestResetPassword() throws Exception {
JsonNode json = requestToJSON(request());
Email email = Email.fromJson(json);
Study study = getStudyOrThrowException(json);
authenticationService.requestResetPassword(study, email);
return okResult("An email has been sent allowing you to set a new password.");
}
public Result resetPassword() throws Exception {
PasswordReset passwordReset = PasswordReset.fromJson(requestToJSON(request()));
authenticationService.resetPassword(passwordReset);
return okResult("Password has been changed.");
}
/**
* Unauthenticated calls that require a study (most of the calls not requiring authentication, including this one),
* should include the study identifier as part of the JSON payload. This call handles such JSON and converts it to a
* study. As a fallback for existing clients, it also looks for the study information in the query string or
* headers. If the study cannot be found in any of these places, it throws an exception, because the API will not
* work correctly without it.
*
* @param email
* @return
*/
private Study getStudyOrThrowException(JsonNode node) {
String studyId = getStudyStringOrThrowException(node);
return studyService.getStudy(studyId);
}
private StudyIdentifier getStudyIdentifierOrThrowException(JsonNode node) {
String studyId = getStudyStringOrThrowException(node);
return new StudyIdentifierImpl(studyId);
}
@SuppressWarnings("deprecation")
private String getStudyStringOrThrowException(JsonNode node) {
String studyId = JsonUtils.asText(node, STUDY_PROPERTY);
if (isNotBlank(studyId)) {
return studyId;
}
studyId = getStudyIdentifier();
if (studyId != null) {
return studyId;
}
throw new EntityNotFoundException(Study.class);
}
}
|
package magick;
public class PixelPacket extends Magick {
private int red, green, blue, opacity;
// Constructor
public PixelPacket(int red, int green, int blue, int opacity)
{
this.red = red;
this.green = green;
this.blue = blue;
this.opacity = opacity;
}
// Set methods.
public void setRed(int red)
{
this.red = red;
}
public void setGreen(int green)
{
this.green = green;
}
public void setBlue(int blue)
{
this.blue = blue;
}
public void setOpacity(int opacity)
{
this.opacity = opacity;
}
// Get Methods
public int getRed()
{
return red;
}
public int getGreen()
{
return green;
}
public int getBlue()
{
return blue;
}
public int getOpacity()
{
return opacity;
}
/**
* looks up a RGB values for a color given in the target string.
*
* @param target Specifies the color to lookup in the X color database
* @return a PixelPacket that represents the target
*/
public static native PixelPacket queryColorDatabase(String target)
throws MagickException;
/**
* Display the object as a String
* @see java.lang.Object#toString()
*/
public String toString() {
return "PixelPacket("+getRed()+","+getGreen()+","+getBlue()+","+getOpacity()+")";
}
}
|
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//For each test case
for(byte t = Byte.parseByte(br.readLine()); t > 0; --t){
//Get input
final char[] str = br.readLine().toCharArray();
//Solve
int numOps = 0;
for(short i = 0, j = (short)(str.length-1); i < j; numOps += Math.abs(str[i++] - str[j
//Print output
sb.append(numOps + "\n");
}
System.out.print(sb);
}
}
|
package com.chenxb.util;
public class Constant {
|
// File: $Id$
/**
* A parallel SAT solver. Given a symbolic boolean equation in CNF, find a set
* of assignments that make this equation true.
*
* In this implementation the solver simply takes the first unassigned
* variable, and tries both possible assignments. These tries can of course be
* done in parallel, making this ideally suited for Satin. More subtle
* approaches are definitely possible, though.
*
* @author Kees van Reeuwijk
* @version $Revision$
*/
import java.io.File;
public class SATSolver extends ibis.satin.SatinObject implements SATInterface, java.io.Serializable {
static final boolean traceSolver = false;
static final boolean printSatSolutions = true;
static final boolean traceNewCode = true;
static int label = 0;
/**
* The method that implements a Satin task.
* The method throws a SATResultException if it finds a solution,
* or terminates normally if it cannot find a solution.
* @param level branching level
* @param p the SAT problem to solve
* @param ctx the changable context of the solver
* @param var the next variable to assign
* @param val the value to assign
*/
public void solve(
int level,
SATProblem p,
SATContext ctx,
int var,
boolean val
) throws SATResultException
{
if( traceSolver ){
System.err.println( "s" + level + ": trying assignment var[" + var + "]=" + val );
}
ctx.assignments[var] = val?1:0;
int res;
if( val ){
res = ctx.propagatePosAssignment( p, var );
}
else {
res = ctx.propagateNegAssignment( p, var );
}
if( res == -1 ){
// Propagation reveals a conflict.
if( traceSolver ){
System.err.println( "s" + level + ": propagation found a conflict" );
}
return;
}
if( res == 1 ){
// Propagation reveals problem is satisfied.
SATSolution s = new SATSolution( ctx.assignments );
if( traceSolver | printSatSolutions ){
System.err.println( "s" + level + ": propagation found a solution: " + s );
}
if( !p.isSatisfied( ctx.assignments ) ){
System.err.println( "Error: " + level + ": solution does not satisfy problem." );
}
throw new SATResultException( s );
}
int nextvar = ctx.getDecisionVariable();
if( nextvar<0 ){
// There are no variables left to assign, clearly there
// is no solution.
if( traceSolver ){
System.err.println( "s" + level + ": nothing to branch on" );
}
return;
}
// We have variable 'nextvar' to branch on.
SATContext negctx = (SATContext) ctx.clone();
SATContext posctx = (SATContext) ctx.clone();
boolean firstvar = ctx.posDominant( nextvar );
solve( level+1, p, posctx, nextvar, firstvar );
solve( level+1, p, negctx, nextvar, !firstvar );
sync();
}
/**
* Given a SAT problem, returns a solution, or <code>null</code> if
* there is no solution.
* @param p The problem to solve.
* @return a solution of the problem, or <code>null</code> if there is no solution
*/
static SATSolution solveSystem( final SATProblem p )
{
SATSolution res = null;
if( p.isConflicting() ){
return null;
}
if( p.isSatisfied() ){
return new SATSolution( p.buildInitialAssignments() );
}
SATSolver s = new SATSolver();
// Now recursively try to find a solution.
try {
int var = p.getMFUVariable();
if( traceSolver ){
System.err.println( "Top level: branching on variable " + var );
}
if( var == -1 ){
return null;
}
SATContext ctx = new SATContext(
p.getClauseCount(),
p.buildTermCounts(),
p.buildPosClauses(),
p.buildNegClauses()
);
ctx.assignments = p.buildInitialAssignments();
int r = ctx.optimize( p );
if( r == 1 ){
if( !p.isSatisfied( ctx.assignments ) ){
System.err.println( "Error: solution does not satisfy problem." );
}
return new SATSolution( ctx.assignments );
}
if( r == -1 ){
return null;
}
int nextvar = ctx.getDecisionVariable();
if( nextvar<0 ){
// There are no variables left to assign, clearly there
// is no solution.
if( traceSolver | traceNewCode ){
System.err.println( "top: nothing to branch on" );
}
return null;
}
SATContext negctx = (SATContext) ctx.clone();
if( ctx.posDominant( nextvar ) ){
s.solve( 0, p, ctx, nextvar, true );
s.solve( 0, p, negctx, nextvar, false );
}
else {
s.solve( 0, p, negctx, nextvar, false );
s.solve( 0, p, ctx, nextvar, true );
}
s.sync();
}
catch( SATResultException r ){
if( r.s == null ){
System.err.println( "A null solution thrown???" );
}
res = r.s;
s.abort();
}
return res;
}
/**
* Allows execution of the class.
*/
public static void main( String args[] ) throws java.io.IOException
{
if( args.length != 1 ){
System.err.println( "Exactly one filename argument required." );
System.exit( 1 );
}
File f = new File( args[0] );
if( !f.exists() ){
System.err.println( "File does not exist: " + f );
System.exit( 1 );
}
SATProblem p = SATProblem.parseDIMACSStream( f );
p.buildAdministration();
p.report( System.out );
long startTime = System.currentTimeMillis();
SATSolution res = solveSystem( p );
long endTime = System.currentTimeMillis();
double time = ((double) (endTime - startTime))/1000.0;
System.out.println( "Time: " + time );
if( res == null ){
System.out.println( "There are no solutions" );
}
else {
System.out.println( "There is a solution: " + res );
}
}
}
|
package com.dmdirc;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.irc.IRCParser;
import com.dmdirc.parser.irc.MyInfo;
import com.dmdirc.parser.irc.ServerInfo;
import com.dmdirc.util.IrcAddress;
/**
* Provides a method to retrieve a parser.
*
* @since 0.6
* @author chris
*/
public class ParserFactory {
/**
* Retrieves a parser instance.
*
* @param myInfo The client information to use
* @param address The address of the server to connect to
* @return An appropriately configured parser
* @since 0.6.3m2
*/
public Parser getParser(final MyInfo myInfo, final IrcAddress address) {
// TODO: Hacky Hack McHack
final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667),
address.getPassword());
info.setSSL(address.isSSL());
if ("irc-test".equals(address.getProtocol())) {
try {
return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser")
.getConstructor(MyInfo.class, ServerInfo.class)
.newInstance(myInfo, info);
} catch (Exception ex) {
Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex);
}
}
return new IRCParser(myInfo, info);
}
}
|
package com.dmdirc.logger;
import com.dmdirc.Main;
import com.dmdirc.config.IdentityManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
/**
* Logger class for the application.
*/
public final class Logger {
/** ProgramError folder. */
private static File errorDir;
/** Prevent instantiation of a new instance of Logger. */
private Logger() {
//Ignore
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
*/
public static void userError(final ErrorLevel level,
final String message) {
userError(level, message, "");
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
* @param details Verbose description of the error
*/
public static void userError(final ErrorLevel level,
final String message, final String details) {
error(level, message, null, false);
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Throwable cause for the error
*/
public static void userError(final ErrorLevel level,
final String message, final Throwable exception) {
error(level, message, null, false);
}
/**
* Called when a non user correctable error occurs, the error will be
* logged and optionally sent to the developers.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Cause of error
*/
public static void appError(final ErrorLevel level,
final String message, final Throwable exception) {
error(level, message, exception, true);
}
/**
* Handles an error in the program.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Cause of error
* @param sendable Whether the error is sendable
*/
private static void error(final ErrorLevel level,
final String message, final Throwable exception,
final boolean sendable) {
final ProgramError error = createError(level, message, exception);
final boolean report =
IdentityManager.getGlobalConfig().getOptionBool("general", "submitErrors", false)
& !IdentityManager.getGlobalConfig().getOptionBool("temp", "noerrorreporting", false);
if (!sendable) {
error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
}
if (sendable && report) {
ErrorManager.sendError(error);
}
if (level == ErrorLevel.FATAL && !report) {
error.setReportStatus(ErrorReportStatus.FINISHED);
}
ErrorManager.getErrorManager().addError(error);
}
/**
* Creates a new ProgramError from the supplied information, and writes
* the error to a file.
*
* @param level Error level
* @param message Error message
* @param exception Error cause
*
* @return ProgramError encapsulating the supplied information
*/
private static ProgramError createError(final ErrorLevel level,
final String message, final Throwable exception) {
final String[] trace;
final StackTraceElement[] traceElements;
if (exception == null) {
trace = new String[0];
} else {
traceElements = exception.getStackTrace();
trace = new String[traceElements.length + 1];
trace[0] = exception.toString();
for (int i = 0; i < traceElements.length; i++) {
trace[i + 1] = traceElements[i].toString();
}
}
final ProgramError error = new ProgramError(
ErrorManager.getErrorManager().getNextErrorID(), level, message,
trace, new Date(System.currentTimeMillis()));
writeError(error);
return error;
}
/**
* Writes the specified error to a file.
*
* @param error ProgramError to write to a file.
*/
private static void writeError(final ProgramError error) {
final PrintWriter out = new PrintWriter(createNewErrorFile(error), true);
out.println("Date:" + error.getDate());
out.println("Level: " + error.getLevel());
out.println("Description: " + error.getMessage());
out.println("Details:");
final String[] trace = error.getTrace();
for (String traceLine : trace) {
out.println('\t' + traceLine);
}
out.close();
}
/**
* Creates a new file for an error and returns the output stream.
*
* @param error Error to create file for
*
* @return BufferedOutputStream to write to the error file
*/
@SuppressWarnings("PMD.SystemPrintln")
private static synchronized OutputStream createNewErrorFile(final ProgramError error) {
if (errorDir == null) {
errorDir = new File(Main.getConfigDir() + "errors");
if (!errorDir.exists()) {
errorDir.mkdirs();
}
}
final String logName = error.getDate().getTime() + "-" + error.getLevel();
final File errorFile = new File(errorDir, logName + ".log");
if (errorFile.exists()) {
boolean rename = false;
int i = 0;
while (!rename) {
i++;
rename = errorFile.renameTo(new File(errorDir, logName + "-" + i + ".log"));
}
}
try {
errorFile.createNewFile();
} catch (IOException ex) {
System.err.println("Error creating new file: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
try {
return new FileOutputStream(errorFile);
} catch (FileNotFoundException ex) {
System.err.println("Error creating new stream: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
}
}
|
package com.data;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import crypto.Cryptography;
import data.DatabaseManager;
import data.Message;
import data.User;
import data.contents.ChatContent;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
public class AndroidSQLManager implements DatabaseManager {
public static final String DB_NAME = "clientdatabase";
public static final String DB_PATH = "/data/data/com.activities/databases/";
private final String CREATE_USER = "CREATE TABLE IF NOT EXISTS user (id TEXT, public_key BLOB, symmetric_key BLOB, PRIMARY KEY(id)); ";
private final String CREATE_MESSAGE = "CREATE TABLE IF NOT EXISTS message (sender_id TEXT, receiver_id TEXT, timestamp INTEGER, content TEXT, PRIMARY KEY(sender_id, receiver_id, timestamp));";
private final String USER = "user";
private final String ID = "id";
private final String PUB_KEY = "public_key";
private final String SYMM_KEY = "symmetric_key";
private final String MESSAGE = "message";
private final String SENDER = "sender_id";
private final String RECEIVER = "receiver_id";
private final String TIMESTAMP = "timestamp";
private final String CONTENT = "content";
SQLiteDatabase db;
public void connect(Activity activity) {
db = activity.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
createTables(CREATE_USER);
createTables(CREATE_MESSAGE);
}
public void connect() {
db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
createTables(CREATE_USER);
createTables(CREATE_MESSAGE);
}
public void disconnect() {
db.close();
}
@Override
public void createTables(String createScriptFile) {
db.execSQL(createScriptFile);
}
@Override
public User getUserFromGivenId(String id) {
User user = null;
Cursor c = db.query(USER, null, ID + " = ?", new String[]{id}, null, null, null); // SELECT * FROM user WHERE id = ?; ? = id
if(c.moveToNext()) {
PublicKey pub_key = Cryptography.getPublicKeyFromBytes(c.getBlob(c.getColumnIndex(PUB_KEY)));
byte[] skey = c.getBlob(c.getColumnIndex(SYMM_KEY));
SecretKey symm_key;
if(skey.length == 0) // check if loaded SecretKey is null
symm_key = null;
else
symm_key = Cryptography.getSecretKeyFromBytes(c.getBlob(c.getColumnIndex(SYMM_KEY)));
user = new User(id, new KeyPair(pub_key, null), symm_key);
}
return user;
}
@Override
public PublicKey getPublicKeyFromId(String id) {
PublicKey key = null;
Cursor c = db.query(USER, new String[]{PUB_KEY}, ID + " = ?", new String[]{id}, null, null, null); // SELECT public_key FROM user WHERE id = ?; ? = id
if(c.moveToNext())
key = Cryptography.getPublicKeyFromBytes(c.getBlob(1));
return key;
}
@Override
public boolean userExists(String id) {
return (getUserFromGivenId(id) != null);
}
@Override
public void insertUser(User user) {
String query = "INSERT INTO " + USER + " VALUES (?, ?, ?);";
SQLiteStatement st = db.compileStatement(query);
st.bindString(1, user.getId());
st.bindBlob(2, user.getPublicKey().getEncoded());
if(user.getSecretKey() != null)
st.bindBlob(3, user.getSecretKey().getEncoded());
else
st.bindBlob(3, new byte[0]); // value must not be null
st.executeInsert();
}
@Override
public ArrayList<User> loadUsers() {
ArrayList<User> users = new ArrayList<>();
Cursor c = db.query(USER, null, null, null, null, null, ID); // SELECT * FROM user ORDER BY id;
while(c.moveToNext()) {
String id = c.getString(c.getColumnIndex(ID));
PublicKey pub_key = Cryptography.getPublicKeyFromBytes(c.getBlob(c.getColumnIndex(PUB_KEY)));
byte[] skey = c.getBlob(c.getColumnIndex(SYMM_KEY));
SecretKey symm_key;
if(skey.length == 0) // check if loaded SecretKey is null
symm_key = null;
else
symm_key = Cryptography.getSecretKeyFromBytes(c.getBlob(c.getColumnIndex(SYMM_KEY)));
users.add(new User(id, new KeyPair(pub_key, null), symm_key));
}
return users;
}
@Override
public boolean removeUser(String id) {
String query = "DELETE FROM " + USER + " WHERE " + ID + " = ?;";
SQLiteStatement st = db.compileStatement(query);
st.bindString(1, id);
return (st.executeUpdateDelete() > 0);
}
@Override
public void insertMessage(Message<ChatContent> chatContentMessage) {
String query = "INSERT INTO " + MESSAGE + " VALUES (?, ?, ?, ?);";
SQLiteStatement st = db.compileStatement(query);
st.bindString(1, chatContentMessage.getSender());
st.bindString(2, chatContentMessage.getReceiver());
st.bindLong(3, chatContentMessage.getTimestamp().getTime());
st.bindString(4, chatContentMessage.getContent().getMessage());
st.executeInsert();
}
public boolean removeMessage(Message<ChatContent> message) {
String query = "DELETE FROM " + MESSAGE + " WHERE " + SENDER + " = ? AND " + RECEIVER + " = ? AND " + TIMESTAMP + " = ?;";
SQLiteStatement st = db.compileStatement(query);
st.bindString(1, message.getSender());
st.bindString(2, message.getReceiver());
st.bindLong(3, message.getTimestamp().getTime());
return (st.executeUpdateDelete() > 0);
}
@Override
public ArrayList<Message<ChatContent>> loadMessagesFromReceiver(String id) {
ArrayList<Message<ChatContent>> messages = new ArrayList<>();
Cursor c = db.query(MESSAGE, null, RECEIVER + " = ?", new String[]{id}, null, null, null); // SELECT * FROM message WHERE receiver = ?; ? = id
while(c.moveToNext()) {
String sender = c.getString(c.getColumnIndex(SENDER));
String content = c.getString(c.getColumnIndex(CONTENT));
Date timestamp = new Date(c.getLong(c.getColumnIndex(TIMESTAMP)));
messages.add(new Message<ChatContent>(timestamp, sender, id, new ChatContent(content)));
}
return messages;
}
@Override
public ArrayList<Message<ChatContent>> loadMessagesFromSender(String id) {
ArrayList<Message<ChatContent>> messages = new ArrayList<>();
Cursor c = db.query(MESSAGE, null, SENDER + " = ?", new String[]{id}, null, null, null); // SELECT * FROM message WHERE sender = ?; ? = id
while(c.moveToNext()) {
String receiver = c.getString(c.getColumnIndex(RECEIVER));
String content = c.getString(c.getColumnIndex(CONTENT));
Date timestamp = new Date(c.getLong(c.getColumnIndex(TIMESTAMP)));
messages.add(new Message<ChatContent>(timestamp, id, receiver, new ChatContent(content)));
}
return messages;
}
public ArrayList<Message<ChatContent>> loadChat(String id) {
ArrayList<Message<ChatContent>> messages = new ArrayList<>();
Cursor c = db.query(MESSAGE, null, SENDER + " = ? OR " + RECEIVER + " = ?", new String[]{id, id}, null, null, TIMESTAMP);
while(c.moveToNext()) {
String receiver = c.getString(c.getColumnIndex(RECEIVER));
String sender = c.getString(c.getColumnIndex(SENDER));
String content = c.getString(c.getColumnIndex(CONTENT));
Date timestamp = new Date(c.getLong(c.getColumnIndex(TIMESTAMP)));
messages.add(new Message<ChatContent>(timestamp, sender, receiver, new ChatContent(content)));
}
return messages;
}
public boolean deleteChat(String id) {
String query = "DELETE FROM " + MESSAGE + " WHERE " + SENDER + " = ? OR " + RECEIVER + " = ?;";
SQLiteStatement st = db.compileStatement(query);
st.bindString(1, id);
st.bindString(2, id);
return (st.executeUpdateDelete() > 0);
}
}
|
package com.logaritmos;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Rectangle implements Serializable {
private static final long serialVersionUID = 5L;
private int left;
private int right;
private int top;
private int bottom;
public Rectangle(int l,int r, int t, int b){
this.setXaxis(l,r);
this.setYaxis(t,b);
}
// corrige los valores de un rectangulo en cada eje en caso de estar desordenados
public static void rectify(Rectangle rect) {
rect.setXaxis(rect.left, rect.right);
rect.setYaxis(rect.bottom, rect.top);
}
private void setXaxis(int a, int b){
//el eje crece de izquierda a derecha
this.left = min(a,b);
this.right = max(a,b);
}
private void setYaxis(int a, int b){
//el eje Y crece de abajo hacia arriba
this.top = max(a,b);
this.bottom = min(a,b);
}
// getters
public int getTop() {
return this.top;
}
public int getBottom() {
return this.bottom;
}
public int getLeft() {
return this.left;
}
public int getRight() {
return this.right;
}
public int getHeight() {
return abs(this.top - this.bottom);
}
public int getWidth() {
return abs(this.right - this.left);
}
public double area() {
return (double) this.getHeight()*this.getWidth();
}
public double deltaArea(Rectangle rect1, Rectangle rect2) {
return abs(rect1.area() - rect2.area());
}
public boolean intersects(Rectangle aRectangle) {
Rectangle minorY;
Rectangle majorY;
if (this.bottom <= aRectangle.bottom) {
minorY = this;
majorY = aRectangle;
} else {
minorY = aRectangle;
majorY = this;
}
return minorY.left <= majorY.left && minorY.right >= majorY.right && minorY.top >= majorY.bottom
|| minorY.left <= majorY.left && minorY.left <= majorY.right && majorY.top <= majorY.bottom;
}
public double intersectArea(Rectangle r) {
if (!this.intersects(r)) {return 0;}
double dx = 0;
double dy = 0;
if(this.right >= r.left) {
if(r.left >= this.left) {
dx = min(r.right, this.right) - r.left;
} else {
if (r.right >= this.right) {
dx = this.right - this.left;
} else {
dx = this.left - r.right;
}
}
}
if(this.top >= r.bottom) {
if(r.bottom >= this.bottom) {
dy = min(this.bottom, r.top);
} else {
if(r.top >= this.top) {
dy = this.top - this.bottom;
} else {
dy = this.bottom - r.top;
}
}
}
return dx*dy;
}
public static double overlapSum(Rectangle r, ArrayList<Rectangle> rects) {
double result = 0;
for (Rectangle rec : rects) {
result += r.intersectArea(rec);
}
return result;
}
public static Rectangle calculateMBR(List<Rectangle> r) {
Rectangle ans = new Rectangle(0,0,0,0);
for (int i=0; i<r.size(); i++) {
ans.left = min(ans.left, r.get(i).left);
ans.right = max(ans.right, r.get(i).right);
ans.bottom = min(ans.bottom, r.get(i).bottom);
ans.top = max(ans.top, r.get(i).top);
}
return ans;
}
public boolean overlaps(Rectangle aRectangle) {
return (this.inVertical(aRectangle) && this.inHorizontal(aRectangle));
}
private boolean inVertical(Rectangle aRectangle){
return (this.inTop(aRectangle.top) || this.inBottom(aRectangle.bottom));
}
private boolean inHorizontal(Rectangle aRectangle){
return (this.inLeft(aRectangle.left) || this.inRight(aRectangle.right));
}
private boolean contains(int number, int min ,int max){
return number>=min && number<=max;
}
private boolean inTop(int aTop){
return contains(aTop,this.bottom,this.top);
}
private boolean inBottom(int aBottom){
return contains(aBottom,this.bottom,this.top);
}
private boolean inLeft(int aLeft){
return contains(aLeft,this.left,this.right);
}
private boolean inRight(int aRight){
return contains(aRight,this.left,this.right);
}
public void multiMax(int i, int i1, int i2, int i3) {
}
}
|
package com.redpois0n.git;
public class Branch {
private String name;
private Commit commit;
private String status;
private boolean isSelected;
public Branch(String name, Commit commit) {
this.name = name;
this.commit = commit;
}
public String getName() {
return name;
}
public Commit getCommit() {
return commit;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
@Override
public boolean equals(Object o) {
if (o instanceof Branch) {
Branch branch = (Branch) o;
return branch.getCommit().equals(getCommit());
}
return false;
}
}
|
package com.sun.pdfview;
import com.sun.pdfview.colorspace.IndexedColor;
import com.sun.pdfview.colorspace.PDFColorSpace;
import com.sun.pdfview.colorspace.YCCKColorSpace;
import com.sun.pdfview.decode.PDFDecoder;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.image.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Encapsulates a PDF Image
*/
public class PDFImage {
public static void dump(PDFObject obj) throws IOException {
p("dumping PDF object: " + obj);
if (obj == null) {
return;
}
HashMap dict = obj.getDictionary();
p(" dict = " + dict);
for (Object key : dict.keySet()) {
p("key = " + key + " value = " + dict.get(key));
}
}
public static void p(String string) {
System.out.println(string);
}
private static int[][] GREY_TO_ARGB = new int[8][];
private static int[] getGreyToArgbMap(int numBits)
{
assert numBits <= 8;
int[] argbVals = GREY_TO_ARGB[numBits - 1];
if (argbVals == null) {
argbVals = createGreyToArgbMap(numBits);
}
return argbVals;
}
/**
* Create a map from all bit-patterns of a certain depth greyscale to the
* corresponding sRGB values via the ICC colorr converter.
* @param numBits the number of greyscale bits
* @return a 2^bits array of standard 32-bit ARGB fits for each greyscale value
* at that bitdepth
*/
private static int[] createGreyToArgbMap(int numBits)
{
final ColorSpace greyCs = PDFColorSpace.getColorSpace(
PDFColorSpace.COLORSPACE_GRAY).getColorSpace();
byte[] greyVals = new byte[1 << numBits];
for (int i = 0; i < greyVals.length; ++i) {
greyVals[i] = (byte) (i & 0xFF);
}
final int[] argbVals = new int[greyVals.length];
final int mask = (1 << numBits) - 1;
final WritableRaster inRaster = Raster.createPackedRaster(
new DataBufferByte(
greyVals,
greyVals.length),
greyVals.length, 1,
greyVals.length,
new int[] {mask},
null);
final BufferedImage greyImage = new
BufferedImage(
new PdfComponentColorModel(
greyCs,
new int[] {numBits}),
inRaster, false, null);
final ColorModel ccm = ColorModel.getRGBdefault();
final WritableRaster outRaster = Raster.createPackedRaster(
new DataBufferInt(
argbVals,
argbVals.length),
argbVals.length, 1,
argbVals.length,
((PackedColorModel)ccm).getMasks(),
null);
final BufferedImage srgbImage = new BufferedImage(
ccm,
outRaster,
false,
null);
final ColorConvertOp op = new ColorConvertOp(
greyCs,
ColorSpace.getInstance(ColorSpace.CS_sRGB), null);
op.filter(greyImage, srgbImage);
GREY_TO_ARGB[numBits - 1] = argbVals;
return argbVals;
}
/** color key mask. Array of start/end pairs of ranges of color components to
* mask out. If a component falls within any of the ranges it is clear. */
private int[] colorKeyMask = null;
/** the width of this image in pixels */
private int width;
/** the height of this image in pixels */
private int height;
/** the colorspace to interpret the samples in */
private PDFColorSpace colorSpace;
/** the number of bits per sample component */
private int bpc;
/** whether this image is a mask or not */
private boolean imageMask = false;
/** the SMask image, if any */
private PDFImage sMask;
/** the decode array */
private float[] decode;
private float[] decodeMins;
private float[] decodeCoefficients;
/** the actual image data */
private PDFObject imageObj;
/**
* Create an instance of a PDFImage
*/
protected PDFImage(PDFObject imageObj) {
this.imageObj = imageObj;
}
/**
* Read a PDFImage from an image dictionary and stream
*
* @param obj the PDFObject containing the image's dictionary and stream
* @param resources the current resources
*/
public static PDFImage createImage(PDFObject obj, Map resources) throws IOException {
return createImage( obj, resources, false);
}
/**
* Read a PDFImage from an image dictionary and stream
* @see PDFImage#createImage(PDFObject, java.util.Map)
* @param useAsSMask - flag for switching colors in case image is used as sMask internally
* this is needed for handling transparency in smask images.
*/
static PDFImage createImage(PDFObject obj, Map resources, boolean useAsSMask)
throws IOException {
// create the image
PDFImage image = new PDFImage(obj);
// get the width (required)
PDFObject widthObj = obj.getDictRef("Width");
if (widthObj == null) {
throw new PDFParseException("Unable to read image width: " + obj);
}
image.setWidth(widthObj.getIntValue());
// get the height (required)
PDFObject heightObj = obj.getDictRef("Height");
if (heightObj == null) {
throw new PDFParseException("Unable to get image height: " + obj);
}
image.setHeight(heightObj.getIntValue());
// figure out if we are an image mask (optional)
PDFObject imageMaskObj = obj.getDictRef("ImageMask");
if (imageMaskObj != null) {
image.setImageMask(imageMaskObj.getBooleanValue());
}
// read the bpc and colorspace (required except for masks)
if (image.isImageMask()) {
image.setBitsPerComponent(1);
// create the indexed color space for the mask
// [PATCHED by michal.busta@gmail.com] - default value od Decode according to PDF spec. is [0, 1]
// so the color arry should be:
// [PATCHED by XOND] - switched colors in case the image is used as SMask for another image, otherwise transparency isn't
// handled correctly.
Color[] colors = useAsSMask? new Color[]{ Color.WHITE, Color.BLACK } : new Color[]{ Color.BLACK, Color.WHITE };
PDFObject imageMaskDecode = obj.getDictRef("Decode");
if (imageMaskDecode != null) {
PDFObject[] array = imageMaskDecode.getArray();
float decode0 = array[0].getFloatValue();
if (decode0 == 1.0f) {
colors = useAsSMask? new Color[]{ Color.BLACK, Color.WHITE }: new Color[]{ Color.WHITE, Color.BLACK };
}
}
image.setColorSpace(new IndexedColor(colors));
} else {
// get the bits per component (required)
PDFObject bpcObj = obj.getDictRef("BitsPerComponent");
if (bpcObj == null) {
throw new PDFParseException("Unable to get bits per component: " + obj);
}
image.setBitsPerComponent(bpcObj.getIntValue());
// get the color space (required)
PDFObject csObj = obj.getDictRef("ColorSpace");
if (csObj == null) {
throw new PDFParseException("No ColorSpace for image: " + obj);
}
PDFColorSpace cs = PDFColorSpace.getColorSpace(csObj, resources);
image.setColorSpace(cs);
}
// read the decode array
PDFObject decodeObj = obj.getDictRef("Decode");
if (decodeObj != null) {
PDFObject[] decodeArray = decodeObj.getArray();
float[] decode = new float[decodeArray.length];
for (int i = 0; i < decodeArray.length; i++) {
decode[i] = decodeArray[i].getFloatValue();
}
image.setDecode(decode);
}
// read the soft mask.
// If ImageMask is true, this entry must not be present.
// (See implementation note 52 in Appendix H.)
if (imageMaskObj == null) {
PDFObject sMaskObj = obj.getDictRef("SMask");
if (sMaskObj == null) {
// try the explicit mask, if there is no SoftMask
sMaskObj = obj.getDictRef("Mask");
}
if (sMaskObj != null) {
if (sMaskObj.getType() == PDFObject.STREAM) {
try {
PDFImage sMaskImage = PDFImage.createImage(sMaskObj, resources, true);
image.setSMask(sMaskImage);
} catch (IOException ex) {
p("ERROR: there was a problem parsing the mask for this object");
dump(obj);
ex.printStackTrace(System.out);
}
} else if (sMaskObj.getType() == PDFObject.ARRAY) {
// retrieve the range of the ColorKeyMask
// colors outside this range will not be painted.
try {
image.setColorKeyMask(sMaskObj);
} catch (IOException ex) {
p("ERROR: there was a problem parsing the color mask for this object");
dump(obj);
ex.printStackTrace(System.out);
}
}
}
}
return image;
}
/**
* Get the image that this PDFImage generates.
*
* @return a buffered image containing the decoded image data
*/
public BufferedImage getImage() {
try {
BufferedImage bi = (BufferedImage) imageObj.getCache();
if (bi == null) {
byte[] data = null;
ByteBuffer jpegBytes = null;
final boolean jpegDecode = PDFDecoder.isLastFilter(imageObj, PDFDecoder.DCT_FILTERS);
if (jpegDecode) {
// if we're lucky, the stream will have just the DCT
// filter applied to it, and we'll have a reference to
// an underlying mapped file, so we'll manage to avoid
// a copy of the encoded JPEG bytes
jpegBytes = imageObj.getStreamBuffer(PDFDecoder.DCT_FILTERS);
} else {
data = imageObj.getStream();
}
// parse the stream data into an actual image
bi = parseData(data, jpegBytes);
imageObj.setCache(bi);
}
// if(bi != null)
// ImageIO.write(bi, "png", new File("/tmp/test/" + System.identityHashCode(this) + ".png"));
return bi;
} catch (IOException ioe) {
System.out.println("Error reading image");
ioe.printStackTrace();
return null;
}
}
/**
* Decodes jpeg data, possibly attempting a manual YCCK decode
* if requested. Users should use {@link #getColorModel()} to
* see which color model should now be used after a successful
* decode.
*/
private class JpegDecoder
{
/** The jpeg bytes */
private ByteBuffer jpegData;
/** The color model employed */
private ColorModel cm;
/** Whether the YCCK/CMYK decode work-around should be used */
private boolean ycckcmykDecodeMode = false;
/**
* Class constructor
* @param jpegData the JPEG data
* @param cm the color model as presented in the PDF
*/
private JpegDecoder(ByteBuffer jpegData, ColorModel cm) {
this.jpegData = jpegData;
this.cm = cm;
}
/**
* Identify whether the decoder should operate in YCCK/CMYK
* decode mode, whereby the YCCK Chroma is specifically
* looked for and the color model is changed to support
* converting raw YCCK color values, working around
* a lack of YCCK/CMYK report in the standard Java
* jpeg readers. Non-YCCK images will not be decoded
* while in this mode.
* @param ycckcmykDecodeMode
*/
public void setYcckCmykDecodeMode( boolean ycckcmykDecodeMode ) {
this.ycckcmykDecodeMode = ycckcmykDecodeMode;
}
/**
* Get the color model that should be used now
* @return
*/
public ColorModel getColorModel() {
return cm;
}
/**
* Attempt to decode the jpeg data
* @return the successfully decoded image
* @throws IOException if the image couldn't be decoded due
* to a lack of support or some IO problem
*/
private BufferedImage decode() throws IOException {
ImageReadParam readParam = null;
if (getDecode() != null) {
// we have to allocate our own buffered image so that we can
// install our colour model which will do the desired decode
readParam = new ImageReadParam();
SampleModel sm =
cm.createCompatibleSampleModel (getWidth (), getHeight ());
final WritableRaster raster =
Raster.createWritableRaster(sm, new Point(0, 0));
readParam.setDestination(new BufferedImage(cm, raster, true, null));
}
final Iterator<ImageReader> jpegReaderIt =
ImageIO.getImageReadersByFormatName("jpeg");
IIOException lastIioEx = null;
while (jpegReaderIt.hasNext()) {
try {
final ImageReader jpegReader = jpegReaderIt.next();
jpegReader.setInput(ImageIO.createImageInputStream(
new ByteBufferInputStream(jpegData)), true, false);
return readImage(jpegReader, readParam);
} catch (IIOException e) {
// its most likely complaining about an unsupported image
// type; hopefully the next image reader will be able to
// understand it
jpegData.reset();
lastIioEx = e;
}
}
throw lastIioEx;
}
private BufferedImage readImage(ImageReader jpegReader, ImageReadParam param) throws IOException {
if ( ycckcmykDecodeMode ) {
// The standard Oracle Java JPEG readers can't deal with CMYK YCCK encoded images
// without a little help from us. We'll try and pick up such instances and work around it.
final IIOMetadata imageMeta = jpegReader.getImageMetadata(0);
if (imageMeta != null) {
final Node standardMeta = imageMeta.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
if (standardMeta != null) {
final Node chroma = getChild(standardMeta, "Chroma");
if (chroma != null) {
final Node csType = getChild(chroma, "ColorSpaceType");
if (csType != null) {
final Attr csTypeNameNode = (Attr)csType.getAttributes().getNamedItem("name");
if (csTypeNameNode != null ) {
final String typeName = csTypeNameNode.getValue();
final boolean YCCK;
if( (YCCK="YCCK".equals( typeName )) || "CMYK".equals(typeName) ) {
// If it's a YCCK image, then we can coax a workable image out of it
// by grabbing the raw raster and installing a YCCK converting
// color space wrapper around the existing (CMYK) color space; this will
// do the YCCK conversion for us
// If it's a CMYK image - just raster it in existing CMYK color space
// first make sure we can get the unadjusted raster
final Raster raster = jpegReader.readRaster(0, param);
if( YCCK ) {
// and now use it with a YCCK converting color space.
PDFImage.this.colorSpace = new PDFColorSpace(new YCCKColorSpace(colorSpace.getColorSpace()));
// re-calculate the color model since the color space has changed
cm = PDFImage.this.createColorModel();
}
return new BufferedImage(
cm,
Raster.createWritableRaster(raster.getSampleModel(), raster.getDataBuffer(), null),
true,
null);
}
}
}
}
}
}
throw new IIOException("Neither YCCK nor CMYK image");
} else {
if (param != null && param.getDestination() != null) {
// if we've already set up a destination image then we'll use it
return jpegReader.read(0, param);
} else {
// otherwise we'll create a new buffered image with the
// desired color model
return new BufferedImage(cm, jpegReader.read(0, param).getRaster(), true, null);
}
}
}
/**
* Get a named child node
* @param aNode the node
* @param aChildName the name of the child node
* @return the first direct child node with that name or null
* if it doesn't exist
*/
private Node getChild(Node aNode, String aChildName) {
for (int i = 0; i < aNode.getChildNodes().getLength(); ++i) {
final Node child = aNode.getChildNodes().item(i);
if (child.getNodeName().equals(aChildName)) {
return child;
}
}
return null;
}
}
/**
* <p>Parse the image stream into a buffered image. Note that this is
* guaranteed to be called after all the other setXXX methods have been
* called.</p>
*
* <p>NOTE: the color convolving is extremely slow on large images.
* It would be good to see if it could be moved out into the rendering
* phases, where we might be able to scale the image down first.</p
*
* @param data the data when already completely filtered and uncompressed
* @param jpegData a byte buffer if data still requiring the DCDTecode filter
* is being used
*/
protected BufferedImage parseData(byte[] data, ByteBuffer jpegData) throws IOException {
// String hex;
// String name;
// synchronized (System.out) {
// System.out.println("\n\n" + name + ": " + data.length);
// for (int i = 0; i < data.length; i++) {
// hex = "0x" + Integer.toHexString(0xFF & data[i]);
// System.out.print(hex);
// if (i < data.length - 1) {
// System.out.print(", ");
// if ((i + 1) % 25 == 0) {
// System.out.print("\n");
// System.out.println("\n");
// System.out.flush();
// pick a color model, based on the number of components and
// bits per component
ColorModel cm = createColorModel();
BufferedImage bi = null;
if (jpegData != null) {
// Use imageio to decode the JPEG into
// a BufferedImage. Perhaps JAI will be installed
// so that decodes will be faster and better supported
// TODO - strictly speaking, the application of the YUV->RGB
// transformation when reading JPEGs does not adhere to the spec.
// We're just going to let java read this in - as it is, the standard
// jpeg reader looks for the specific Adobe marker header so that
// it may apply the transform, so that's good. If that marker
// isn't present, then it also applies a number of other heuristics
// to determine whether the transform should be applied.
// In practice, it probably almost always does the right thing here,
// though note that the present or default value of the ColorTransform
// dictionary entry is not being observed, so there is scope for
// error. Hopefully the JAI reader does the same.
// We might need to attempt this with multiple readers, so let's
// remember where the jpeg data starts
jpegData.mark();
JpegDecoder decoder = new JpegDecoder(jpegData, cm);
IIOException decodeEx = null;
try {
bi = decoder.decode();
} catch (IIOException e) {
decodeEx = e;
// The native readers weren't able to process the image.
// One common situation is that the image is YCCK/CMYK encoded,
// which isn't supported by the default jpeg readers.
// We've got a work-around we can attempt, though:
decoder.setYcckCmykDecodeMode( true );
try {
bi = decoder.decode();
} catch (IOException e2) {
// It probably wasn't the YCCK/CMYK issue! We'll drop
// through and allow the initial exception to be reported
}
}
// the decoder may have requested installation of a new color model
cm = decoder.getColorModel();
// make these immediately unreachable, as the referenced
// jpeg data might be quite large
jpegData = null;
decoder = null;
if (bi == null) {
// This isn't pretty, but it's what's been happening
// previously, so we'll preserve it for the time
// being. At least we'll offer a hint now!
assert decodeEx != null;
throw new IIOException(decodeEx.getMessage() +
". Maybe installing JAI for expanded image format " +
"support would help?", decodeEx);
}
} else {
DataBuffer db = new DataBufferByte(data, data.length);
// create a compatible raster
SampleModel sm =
cm.createCompatibleSampleModel (getWidth (), getHeight ());
WritableRaster raster;
try {
raster =
Raster.createWritableRaster (sm, db, new Point (0, 0));
} catch (RasterFormatException e) {
// this here seems a bit on the odd side. Is this really required,
// or was it compensating for an old bug?
int calculatedLineBits = getWidth() *
getColorSpace().getNumComponents() *
getBitsPerComponent();
int calculatedLineBytes = (calculatedLineBits + 7 / 8);
int calculatedBytes = calculatedLineBytes * getHeight();
if (calculatedBytes > data.length) {
byte[] tempLargerData = new byte[calculatedBytes];
System.arraycopy (data, 0, tempLargerData, 0, data.length);
db = new DataBufferByte (tempLargerData, calculatedBytes);
raster = Raster.createWritableRaster(sm, db, new Point(0, 0));
} else {
throw e;
}
}
/*
* Workaround for a bug on the Mac -- a class cast exception in
* drawImage() due to the wrong data buffer type (?)
*/
if (cm instanceof IndexColorModel) {
IndexColorModel icm = (IndexColorModel) cm;
// choose the image type based on the size
int type = BufferedImage.TYPE_BYTE_BINARY;
if (getBitsPerComponent() == 8) {
type = BufferedImage.TYPE_BYTE_INDEXED;
}
// create the image with an explicit indexed color model.
bi = new BufferedImage(getWidth(), getHeight(), type, icm);
// set the data explicitly as well
bi.setData(raster);
} else {
bi = new BufferedImage(cm, raster, true, null);
}
}
ColorSpace cs = cm.getColorSpace();
ColorSpace rgbCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
if (isGreyscale(cs) && bpc <= 8 && getDecode() == null && jpegData == null) {
bi = convertGreyscaleToArgb(data, bi);
} else if (!isImageMask() && cs instanceof ICC_ColorSpace && !cs.equals(rgbCS)
&& !Boolean.getBoolean("PDFRenderer.avoidColorConvertOp")) {
// users can use the PDFRenderer.avoidColorConvertOp property to avoid
// use of this color convert op which may segfault on some platforms
// due to a variety of problems related to thread safety and
// the native cmm library underlying this conversioon op, e.g.,
// (Unix platforms seem the most affected)
// If the system is bug-free, though, this does make use
// of native libraries and sees a not insignificant speed-up,
// though it's still not exactly fast. If we don't run this op
// now, it's performed at some later stage, but without using
// the native code
ColorConvertOp op = new ColorConvertOp(cs, rgbCS, null);
BufferedImage converted = new BufferedImage(getWidth(),
getHeight(), BufferedImage.TYPE_INT_ARGB);
bi = op.filter(bi, converted);
}
// add in the alpha data supplied by the SMask, if any
PDFImage sMaskImage = getSMask();
if (sMaskImage != null) {
BufferedImage si = sMaskImage.getImage();
BufferedImage outImage = new BufferedImage(getWidth(),
getHeight(), BufferedImage.TYPE_INT_ARGB);
int[] srcArray = new int[width];
int[] maskArray = new int[width];
for (int i = 0; i < height; i++) {
bi.getRGB(0, i, width, 1, srcArray, 0, width);
si.getRGB(0, i, width, 1, maskArray, 0, width);
for (int j = 0; j < width; j++) {
int ac = 0xff000000;
maskArray[j] = ((maskArray[j] & 0xff) << 24) | (srcArray[j] & ~ac);
}
outImage.setRGB(0, i, width, 1, maskArray, 0, width);
}
bi = outImage;
}
return (bi);
}
private boolean isGreyscale(ColorSpace aCs)
{
return aCs == PDFColorSpace.getColorSpace(PDFColorSpace.COLORSPACE_GRAY).
getColorSpace();
}
private BufferedImage convertGreyscaleToArgb(byte[] data, BufferedImage bi)
{
// we use an optimised greyscale colour conversion, as with scanned
// greyscale/mono documents consisting of nothing but page-size
// images, using the ICC converter is perhaps 15 times slower than this
// method. Using an example scanned, mainly monochrome document, on this
// developer's machine pages took an average of 3s to render using the
// ICC converter filter, and around 115ms using this method. We use
// pre-calculated tables generated using the ICC converter to map between
// each possible greyscale value and its desired value in sRGB.
// We also try to avoid going through SampleModels, WritableRasters or
// BufferedImages as that takes about 3 times as long.
final int[] convertedPixels = new int[getWidth() * getHeight()];
final WritableRaster r = bi.getRaster();
int i = 0;
final int[] greyToArgbMap = getGreyToArgbMap(bpc);
if (bpc == 1) {
int calculatedLineBytes = (getWidth() + 7) / 8;
int rowStartByteIndex;
// avoid hitting the WritableRaster for the common 1 bpc case
if (greyToArgbMap[0] == 0 && greyToArgbMap[1] == 0xFFFFFFFF) {
// optimisation for common case of a direct map to full white
// and black, using bit twiddling instead of consulting the
// greyToArgb map
for (int y = 0; y < getHeight(); ++y) {
// each row is byte-aligned
rowStartByteIndex = y * calculatedLineBytes;
for (int x = 0; x < getWidth(); ++x) {
final byte b = data[rowStartByteIndex + x / 8];
final int white = b >> (7 - (x & 7)) & 1;
// if white == 0, white - 1 will be 0xFFFFFFFF,
// which when xored with 0xFFFFFF will produce 0
// if white == 1, white - 1 will be 0,
// which when xored with 0xFFFFFF will produce 0xFFFFFF
// (ignoring the top two bytes, which are always set high anyway)
convertedPixels[i] = 0xFF000000 | ((white - 1) ^ 0xFFFFFF);
++i;
}
}
} else {
// 1 bpc case where we can't bit-twiddle and need to consult
// the map
for (int y = 0; y < getHeight(); ++y) {
rowStartByteIndex = y * calculatedLineBytes;
for (int x = 0; x < getWidth(); ++x) {
final byte b = data[rowStartByteIndex + x / 8];
final int val = b >> (7 - (x & 7)) & 1;
convertedPixels[i] = greyToArgbMap[val];
++i;
}
}
}
} else {
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
final int greyscale = r.getSample(x, y, 0);
convertedPixels[i] = greyToArgbMap[greyscale];
++i;
}
}
}
final ColorModel ccm = ColorModel.getRGBdefault();
return new BufferedImage(
ccm,
Raster.createPackedRaster(
new DataBufferInt(
convertedPixels,
convertedPixels.length),
getWidth(), getHeight(),
getWidth(), ((PackedColorModel)ccm).getMasks(),
null),
false,
null);
}
/**
* Get the image's width
*/
public int getWidth() {
return width;
}
/**
* Set the image's width
*/
protected void setWidth(int width) {
this.width = width;
}
/**
* Get the image's height
*/
public int getHeight() {
return height;
}
/**
* Set the image's height
*/
protected void setHeight(int height) {
this.height = height;
}
/**
* set the color key mask. It is an array of start/end entries
* to indicate ranges of color indicies that should be masked out.
*
* @param maskArrayObject
*/
private void setColorKeyMask(PDFObject maskArrayObject) throws IOException {
PDFObject[] maskObjects = maskArrayObject.getArray();
colorKeyMask = null;
int[] masks = new int[maskObjects.length];
for (int i = 0; i < masks.length; i++) {
masks[i] = maskObjects[i].getIntValue();
}
colorKeyMask = masks;
}
/**
* Get the colorspace associated with this image, or null if there
* isn't one
*/
protected PDFColorSpace getColorSpace() {
return colorSpace;
}
/**
* Set the colorspace associated with this image
*/
protected void setColorSpace(PDFColorSpace colorSpace) {
this.colorSpace = colorSpace;
}
/**
* Get the number of bits per component sample
*/
protected int getBitsPerComponent() {
return bpc;
}
/**
* Set the number of bits per component sample
*/
protected void setBitsPerComponent(int bpc) {
this.bpc = bpc;
}
/**
* Return whether or not this is an image mask
*/
public boolean isImageMask() {
return imageMask;
}
/**
* Set whether or not this is an image mask
*/
public void setImageMask(boolean imageMask) {
this.imageMask = imageMask;
}
/**
* Return the soft mask associated with this image
*/
public PDFImage getSMask() {
return sMask;
}
/**
* Set the soft mask image
*/
protected void setSMask(PDFImage sMask) {
this.sMask = sMask;
}
/**
* Get the decode array
*/
protected float[] getDecode() {
return decode;
}
/**
* Set the decode array
*/
protected void setDecode(float[] decode) {
float max = (1 << getBitsPerComponent()) - 1;
this.decode = decode;
this.decodeCoefficients = new float[decode.length / 2];
this.decodeMins = new float[decode.length / 2];
for (int i = 0; i < decode.length; i += 2) {
decodeMins[i/2] = decode[i];
decodeCoefficients[i/2] = (decode[i + 1] - decode[i]) / max;
}
}
/**
* get a Java ColorModel consistent with the current color space,
* number of bits per component and decode array
*
* @param bpc the number of bits per component
*/
private ColorModel createColorModel() {
PDFColorSpace cs = getColorSpace();
if (cs instanceof IndexedColor) {
IndexedColor ics = (IndexedColor) cs;
byte[] components = ics.getColorComponents();
int num = ics.getCount();
// process the decode array
if (decode != null) {
byte[] normComps = new byte[components.length];
// move the components array around
for (int i = 0; i < num; i++) {
byte[] orig = new byte[1];
orig[0] = (byte) i;
float[] res = normalize(orig, null, 0);
int idx = (int) res[0];
normComps[i * 3] = components[idx * 3];
normComps[(i * 3) + 1] = components[(idx * 3) + 1];
normComps[(i * 3) + 2] = components[(idx * 3) + 2];
}
components = normComps;
}
// make sure the size of the components array is 2 ^ numBits
// since if it's not, Java will complain
int correctCount = 1 << getBitsPerComponent();
if (correctCount < num) {
byte[] fewerComps = new byte[correctCount * 3];
System.arraycopy(components, 0, fewerComps, 0, correctCount * 3);
components = fewerComps;
num = correctCount;
}
if (colorKeyMask == null || colorKeyMask.length == 0) {
return new IndexColorModel(getBitsPerComponent(), num, components,
0, false);
} else {
byte[] aComps = new byte[num * 4];
int idx = 0;
for (int i = 0; i < num; i++) {
aComps[idx++] = components[(i * 3)];
aComps[idx++] = components[(i * 3) + 1];
aComps[idx++] = components[(i * 3) + 2];
aComps[idx++] = (byte) 0xFF;
}
for (int i = 0; i < colorKeyMask.length; i += 2) {
for (int j = colorKeyMask[i]; j <= colorKeyMask[i + 1]; j++) {
aComps[(j * 4) + 3] = 0; // make transparent
}
}
return new IndexColorModel(getBitsPerComponent(), num, aComps,
0, true);
}
} else {
int[] bits = new int[cs.getNumComponents()];
for (int i = 0; i < bits.length; i++) {
bits[i] = getBitsPerComponent();
}
return decode != null ?
new DecodeComponentColorModel(cs.getColorSpace(), bits) :
new PdfComponentColorModel(cs.getColorSpace(), bits);
}
}
private ColorModel createColorModel(PDFColorSpace cs) {
if (cs instanceof IndexedColor) {
IndexedColor ics = (IndexedColor) cs;
byte[] components = ics.getColorComponents();
int num = ics.getCount();
// process the decode array
if (decode != null) {
byte[] normComps = new byte[components.length];
// move the components array around
for (int i = 0; i < num; i++) {
byte[] orig = new byte[1];
orig[0] = (byte) i;
float[] res = normalize(orig, null, 0);
int idx = (int) res[0];
normComps[i * 3] = components[idx * 3];
normComps[(i * 3) + 1] = components[(idx * 3) + 1];
normComps[(i * 3) + 2] = components[(idx * 3) + 2];
}
components = normComps;
}
// make sure the size of the components array is 2 ^ numBits
// since if it's not, Java will complain
int correctCount = 1 << getBitsPerComponent();
if (correctCount < num) {
byte[] fewerComps = new byte[correctCount * 3];
System.arraycopy(components, 0, fewerComps, 0, correctCount * 3);
components = fewerComps;
num = correctCount;
}
if (colorKeyMask == null || colorKeyMask.length == 0) {
return new IndexColorModel(getBitsPerComponent(), num, components,
0, false);
} else {
byte[] aComps = new byte[num * 4];
int idx = 0;
for (int i = 0; i < num; i++) {
aComps[idx++] = components[(i * 3)];
aComps[idx++] = components[(i * 3) + 1];
aComps[idx++] = components[(i * 3) + 2];
aComps[idx++] = (byte) 0xFF;
}
for (int i = 0; i < colorKeyMask.length; i += 2) {
for (int j = colorKeyMask[i]; j <= colorKeyMask[i + 1]; j++) {
aComps[(j * 4) + 3] = 0; // make transparent
}
}
return new IndexColorModel(getBitsPerComponent(), num, aComps,
0, true);
}
} else {
int[] bits = new int[cs.getNumComponents()];
for (int i = 0; i < bits.length; i++) {
bits[i] = getBitsPerComponent();
}
return decode != null ?
new DecodeComponentColorModel(cs.getColorSpace(), bits) :
new PdfComponentColorModel(cs.getColorSpace(), bits);
}
}
/**
* Normalize an array of values to match the decode array
*/
private float[] normalize(byte[] pixels, float[] normComponents,
int normOffset) {
if (normComponents == null) {
normComponents = new float[normOffset + pixels.length];
}
// trivial loop unroll - saves a little time
switch (pixels.length) {
case 4:
normComponents[normOffset + 3] = decodeMins[3] + (float)(pixels[3] & 0xFF) * decodeCoefficients[3];
case 3:
normComponents[normOffset + 2] = decodeMins[2] + (float)(pixels[2] & 0xFF) * decodeCoefficients[2];
case 2:
normComponents[normOffset + 1] = decodeMins[1] + (float)(pixels[1] & 0xFF) * decodeCoefficients[1];
case 1:
normComponents[normOffset ] = decodeMins[0] + (float)(pixels[0] & 0xFF) * decodeCoefficients[0];
break;
default:
throw new IllegalArgumentException("Someone needs to add support for more than 4 components");
}
return normComponents;
}
/**
* A wrapper for ComponentColorSpace which normalizes based on the
* decode array.
*/
static class PdfComponentColorModel extends ComponentColorModel {
int bitsPerComponent;
public PdfComponentColorModel(ColorSpace cs, int[] bpc) {
super(cs, bpc, false, false, Transparency.OPAQUE,
DataBuffer.TYPE_BYTE);
pixel_bits = bpc.length * bpc[0];
this.bitsPerComponent = bpc[0];
}
@Override
public SampleModel createCompatibleSampleModel(int width, int height) {
if (bitsPerComponent >= 8) {
assert bitsPerComponent == 8 || bitsPerComponent == 16;
final int numComponents = getNumComponents();
int[] bandOffsets = new int[numComponents];
for (int i=0; i < numComponents; i++) {
bandOffsets[i] = i;
}
return new PixelInterleavedSampleModel(
getTransferType(), width, height,
numComponents,
width * numComponents,
bandOffsets);
} else {
switch (getPixelSize()) {
case 1:
case 2:
case 4:
// pixels don't span byte boundaries, so we can use the standard multi pixel
// packing, which offers a slight performance advantage over the other sample
// model, which must consider such cases. Given that sample model interactions
// can dominate processing, this small distinction is worthwhile
return new MultiPixelPackedSampleModel(getTransferType(),
width,
height,
getPixelSize());
default:
// pixels will cross byte boundaries
assert getTransferType() == DataBuffer.TYPE_BYTE;
return new PdfSubByteSampleModel(width, height, getNumComponents(), bitsPerComponent);
}
}
}
@Override
public boolean isCompatibleRaster(Raster raster) {
if (bitsPerComponent < 8 || getNumComponents() == 1) {
SampleModel sm = raster.getSampleModel();
return sm.getSampleSize(0) == bitsPerComponent;
}
return super.isCompatibleRaster(raster);
}
}
class DecodeComponentColorModel extends PdfComponentColorModel
{
DecodeComponentColorModel(ColorSpace cs, int[] bpc)
{
super(cs, bpc);
}
public int getRGB(Object inData) {
float[] norm = getNormalizedComponents(inData, null, 0);
// super-class wants to do a (VERY expensive!) colorspace conversion
// here, but we'll ignore it - I think we'll already have the
// colour space converted.
float[] rgb = norm;//this.colorSpace.toRGB(norm);
// Note that getNormalizedComponents returns non-premult values
return (this.getAlpha(inData) << 24)
| (((int) (rgb[0] * 255.0f + 0.5f)) << 16)
| (((int) (rgb[1] * 255.0f + 0.5f)) << 8)
| (((int) (rgb[2] * 255.0f + 0.5f)));
}
@Override
public float[] getNormalizedComponents(Object pixel,
float[] normComponents, int normOffset) {
return normalize((byte[]) pixel, normComponents, normOffset);
}
}
}
|
package com.tlamatini;
import com.tlamatini.datos.ConexionDB;
import com.tlamatini.negocio.ControlVentanaLogin;
/**
*
* @author sist3mas
*/
public class Aplicacion {
ConexionDB conexion= new ConexionDB();
boolean valida;
public static void main(String[] args) {
Aplicacion app=new Aplicacion();
}
public Aplicacion(){
valida=conexion.crearConexion();
if(valida==true){
ControlVentanaLogin control=new ControlVentanaLogin(conexion);
}else{
System.exit(0);
}
}
}
|
package com.vmware.vim25.mo;
import java.rmi.RemoteException;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.InvalidState;
import com.vmware.vim25.LocalizedMethodFault;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.MethodFault;
import com.vmware.vim25.OutOfBounds;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.TaskInfo;
import com.vmware.vim25.TaskInfoState;
/**
* The managed object class corresponding to the one defined in VI SDK API reference.
* @author Steve JIN (sjin@vmware.com)
*/
public class Task extends ExtensibleManagedObject
{
public static final String PROPNAME_INFO = "info";
public static final String SUCCESS = "success";
public Task(ServerConnection serverConnection, ManagedObjectReference mor)
{
super(serverConnection, mor);
}
public TaskInfo getTaskInfo() throws InvalidProperty, RuntimeFault, RemoteException
{
return (TaskInfo) getCurrentProperty(PROPNAME_INFO);
}
public ManagedEntity getAssociatedManagedEntity()
{
return (ManagedEntity) getManagedObject("info.entity");
}
public ManagedEntity[] getLockedManagedEntities()
{
return (ManagedEntity[]) getManagedObjects("info.locked");
}
public void cancelTask() throws RuntimeFault, RemoteException
{
getVimService().cancelTask(getMOR());
}
public void setTaskState(TaskInfoState tis, Object result, LocalizedMethodFault fault) throws InvalidState, RuntimeFault, RemoteException
{
getVimService().setTaskState(getMOR(), tis, result, fault);
}
public void updateProgress(int percentDone) throws InvalidState, OutOfBounds, RuntimeFault, RemoteException
{
getVimService().updateProgress(getMOR(), percentDone);
}
public String waitForMe() throws InvalidProperty, RuntimeFault, MethodFault, RemoteException
{
Object[] result = waitForValues(
new String[] { "info.state", "info.error" },
new String[] { "state" },
new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error } });
if (result[0].equals(TaskInfoState.success))
{
return SUCCESS;
}
else
{
TaskInfo tinfo = (TaskInfo) getCurrentProperty(PROPNAME_INFO);
LocalizedMethodFault fault = tinfo.getError();
String error = "Error Occured";
if(fault!=null)
{
MethodFault mf = fault.getFault();
throw mf;
}
return error;
}
}
}
|
/**
+ * @author Nick Pan and Talal Javed Qadri and Anthony Olawo and Kat Krieger
*/
package controller;
import game_authoring_environment.ActorsPanel;
import game_authoring_environment.AttributesPanel;
import game_authoring_environment.FullView;
import game_authoring_environment.GAE;
import game_authoring_environment.LeftPanel;
import game_authoring_environment.Library;
import game_authoring_environment.MenuBar;
import game_authoring_environment.RightPanel;
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.plaf.LayerUI;
import objects.GameObject;
import objects.NonPlayer;
import objects.Player;
import engine.GameEngine;
import saladConstants.SaladConstants;
import stage.Game;
public class GAEController {
private DataController myDataController;
private GAE g;
public static final String TITLE = "OOGASalad iTeam";
private static FullView fv;
private static MenuBar mb;
private HashMap<String, Image> availableImages;
private GameEngine myGameEngine;
private HashMap<String, JPanel> panelMap;
private AttributesPanel attributesPanel;
private Library libraryPanel;
private int selectedSceneID;
private int selectedActorID;
private int playerID;
private int eventPairID;
private static final boolean DEBUG = false;
public GAEController(){
playerID = SaladConstants.PLAYER_ID;
myDataController = new DataController();
eventPairID = 0;
myGameEngine = myDataController.initGameEngine(true);
//createGAE(this);
g = new GAE(this);
setUpVariables();
createLevel(1);
createScene(1,0);
switchScene(1,0);
//uploadImage(100,100,)
double d = 0;
//modifyGravityMagnitude(d);
}
private void setUpVariables(){
fv = g.getFullView();
mb = g.getMenuBar();
panelMap = fv.getMap();
attributesPanel = fv.getAttributes();
libraryPanel = fv.getLibrary();
//test code below
}
public GameEngine getEngine(){
return myGameEngine;
}
public RightPanel getRightPanel(){
return fv.getRightPanel();
}
public void createPlayer(int ID,String url, int xSize, int ySize, double xPos, double yPos, String name, int colID, int lives){
String order = SaladConstants.CREATE_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ID+SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url+ SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize +
SaladConstants.SEPARATOR + SaladConstants.POSITION + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos +
SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR+name + SaladConstants.SEPARATOR+ SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR +
colID + SaladConstants.SEPARATOR + SaladConstants.LIVES + SaladConstants.SEPARATOR + lives;
if (!DEBUG) myDataController.receiveOrder(order);
setColIDStayOnEveryTileID(colID);
System.out.println(order);
}
/**
* Modify player's speed without providing player id. The already set player ID is used.
*/
public void modifyPlayerSpeed(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SPEED + SaladConstants.SEPARATOR+xSpeed+ SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's image without providing player id. The already specified player ID is used.
*/
public void modifyPlayerImage( String url, int xSize, int ySize){
String order = SaladConstants.MODIFY_PLAYER_IMAGE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's ID without providing old player id. The already specified player ID is used for the old id.
*/
public void modifyPlayerID(int newID){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_TO_ID + SaladConstants.SEPARATOR+newID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyPlayerColID(int oldColID,int newColID){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's position without providing player id. The already specified playerID is used.
*/
public void modifyPlayerPos(double xPos, double yPos){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.POSITION + SaladConstants.SEPARATOR+xPos+ SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by doing a regular remove without providing player id. The already specified playerID is used.
*/
public void modifyPlayerRegRemove(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+
playerID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_REMOVE + SaladConstants.SEPARATOR +SaladConstants.REGULAR_REMOVE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by making it immortal without providing player id. The already specified playerID is used.
*/
public void modifyPlayerImmortal(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.IMMORTAL + SaladConstants.SEPARATOR+SaladConstants.IMMORTAL;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by making it immobile without providing player id. The already specified playerID is used.
*/
public void modifyPlayerImmobile(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.IMMOBILE + SaladConstants.SEPARATOR+SaladConstants.IMMOBILE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify number of bullets per shoot without specifying player ID. Global player ID which is ID of current selected player is used
*/
public void modifyPlayerSpreadShoot(String imageFileName, int xSize, int ySize, int collID, double speed, int bulletsPerShot, int maxBulletsAllowed){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR + imageFileName +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR +
collID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR + bulletsPerShot + SaladConstants.SEPARATOR + maxBulletsAllowed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot property by slowing it without providing player id. The already specified playerID is used.
*/
public void modifyPlayerSlowShoot(String url, int xSize, int ySize, int colID, double speed, int maxBullets){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR
+ xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR +
maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot property by quickening it without providing player id. The already specified playerID is used.
*/
public void modifyPlayerQuickShoot(String url, int xSize, int ySize, int colID, double speed, int numBullets, int maxBullets){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR+SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR + url +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed +
SaladConstants.SEPARATOR + numBullets + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by changing its property to move in air
*/
public void modifyPlayerCanMoveInAir(boolean enableAirMove){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.CAN_MOVE_IN_AIR + SaladConstants.SEPARATOR+ String.valueOf(enableAirMove);
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's corpse showing property without providing player id. The already specified playerID is used.
*/
public void modifyPlayerShowCorpse(String url, int xSize, int ySize, int time){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SHOW_CORPSE + SaladConstants.SEPARATOR+SaladConstants.SHOW_CORPSE + SaladConstants.SEPARATOR + url +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + time;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's jump behavior without providing player id. The already specified playerID is used.
*/
public void modifyPlayerJumpBehavior(double magnitude, int numJumps){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.JUMP + SaladConstants.SEPARATOR+SaladConstants.JUMP + SaladConstants.SEPARATOR + magnitude +
SaladConstants.SEPARATOR + numJumps;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player so it can't jump
*/
public void modifyPlayerCanNotJump(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP +
SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveUp key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyUp(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_UP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveDown key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyDown(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_DOWN;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveLeft key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyLeft(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_LEFT;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveRight key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyRight(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_RIGHT;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyShoot(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.SHOOT_KEY;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's jump key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyJump(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.JUMP_KEY;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Delete player without providing player id. The already specified playerID is used for the id.
*/
public void deletePlayer(){
String order = SaladConstants.DELETE_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + playerID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createActor(int ID,String url, int xSize, int ySize,
double xPos, double yPos, String name, int colID, int lives){
String order = SaladConstants.CREATE_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ID+SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url+ SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize +
SaladConstants.SEPARATOR + SaladConstants.POSITION + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos +
SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR + name + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + colID
+ SaladConstants.SEPARATOR + SaladConstants.LIVES + SaladConstants.SEPARATOR + lives;
if (!DEBUG) myDataController.receiveOrder(order);
setColIDStayOnEveryTileID(colID);
System.out.println(order);
}
/**
* Modify actor's speed without providing actor id. The selectedActorID is used.
*/
public void modifyActorSpeedNoID(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SPEED + SaladConstants.SEPARATOR+xSpeed + SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's jump
*/
public void modifyActorJump(double magnitude, int numberOfJumpsAllowedInAir){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP + SaladConstants.SEPARATOR +
SaladConstants.JUMP + SaladConstants.SEPARATOR + magnitude + SaladConstants.SEPARATOR + numberOfJumpsAllowedInAir;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor to nullify jumping ability
*/
public void modifyActorCanNotJump(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ selectedActorID + SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP + SaladConstants.SEPARATOR +
SaladConstants.CAN_NOT_JUMP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor jumping latency with time
*/
public void modifyActorJumpByTime(double magnitude, int numberOfJumpsAllowedInAir, int latency){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP_BY_TIME + SaladConstants.SEPARATOR +
SaladConstants.JUMP_BY_TIME + SaladConstants.SEPARATOR + magnitude + SaladConstants.SEPARATOR + numberOfJumpsAllowedInAir + SaladConstants.SEPARATOR + latency;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's jump animation
*/
public void modifyActorAnimationJump(String url, int xSize, int ySize ){
String order = SaladConstants.MODIFY_ACTOR_ANIMATION + SaladConstants.SEPARATOR + SaladConstants.ID +
SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP_ANIMATION +
SaladConstants.SEPARATOR + SaladConstants.JUMP + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR +
xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's forward move animation
*/
public void modifyActorAnimationFDMove(String imgURL, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR_ANIMATION + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID
+ SaladConstants.SEPARATOR + SaladConstants.FD_MOVE + SaladConstants.SEPARATOR + SaladConstants.FD_MOVE
+ SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's backward move animation
*/
public void modifyActorAnimationBKMove(String imgURL, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + SaladConstants.BK_MOVE + SaladConstants.SEPARATOR +
SaladConstants.BK_MOVE + SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize ;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's image without providing actor id. The selectedActorID is used.
*/
public void modifyActorImageNoID(String url, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR_IMAGE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ selectedActorID +SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's ID without providing old actor id. The selectedActorID is used for the old id.
*/
public void modifyActorIDNoOldID(int newID){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_TO_ID + SaladConstants.SEPARATOR+newID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorName(String name){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ selectedActorID+SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR+ name;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorColIDNoID(int newColID){
int oldColID = myDataController.getGame().getPlayer(selectedActorID).colid;
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorColID(int oldColID,int newColID){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's position without providing actor id. The selectedActorID is used.
*/
public void modifyActorPosNoID(double xPos, double yPos){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.POSITION + SaladConstants.SEPARATOR+xPos+ SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's regular move property without providing actor id. The selectedActorID is used.
*/
public void modifyActorRegMoveNoID(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_MOVE + SaladConstants.SEPARATOR + SaladConstants.REGULAR_MOVE+ SaladConstants.SEPARATOR +xSpeed +
SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorSpreadShoot(String imgURL, int xSize, int ySize, int collID,
double speed, int bulletsPerShot, int maxBullets ){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
selectedActorID + SaladConstants.SEPARATOR + SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR
+ ySize + SaladConstants.SEPARATOR + collID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR +
bulletsPerShot + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's vertical movement
*/
public void modifyActorBackForthVerticalMove( double amplitude, int lantency, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
selectedActorID + SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE_WITH_VERTICAL_SPEED +
SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE_WITH_VERTICAL_SPEED + SaladConstants.SEPARATOR
+ amplitude + SaladConstants.SEPARATOR + lantency + SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's regular move property without providing actor id. The selectedActorID is used.
*/
public void modifyActorBackForthMoveNoID(double amplitude, int latency){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.BACK_FORTH_MOVE + SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE+ SaladConstants.SEPARATOR
+ amplitude + SaladConstants.SEPARATOR + latency;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by doing a regular remove without providing actor id. The selectedActorID is used.
*/
public void modifyActorRegRemoveNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_REMOVE + SaladConstants.SEPARATOR +SaladConstants.REGULAR_REMOVE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by making it immortal without providing actor id. The selectedActorID is used.
*/
public void modifyActorImmortalNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID +
SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.IMMORTAL + SaladConstants.SEPARATOR+SaladConstants.IMMORTAL;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by making it immobile without providing actor id. The selectedActorID is used.
*/
public void modifyActorImmobileNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+
selectedActorID+SaladConstants.SEPARATOR + SaladConstants.IMMOBILE + SaladConstants.SEPARATOR+SaladConstants.IMMOBILE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by slowing it without providing actor id. The selectedActorID is used.
*/
public void modifyActorSlowShoot(String url, int xSize, int ySize, int colID, double speed, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR
+ xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by quickening it without providing actor id. The selectedActorID is used.
*/
public void modifyActorQuickShoot(String url, int xSize, int ySize, int colID, double speed, int numBullets, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR+SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR + url +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed +
SaladConstants.SEPARATOR + numBullets + SaladConstants.SEPARATOR+ maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by slowing it without providing actor id and with a time latency. The selectedActorID is used.
*/
public void modifyActorSlowShootByTime(String url, int xSize, int ySize, int colID, double speed, int timeLatency, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT_BY_TIME + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT_BY_TIME +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR +timeLatency + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's spread shoot property without providing actor id and with a time latency. The selectedActorID is used.
*/
public void modifyActorSpreadShootByTime(String url, int xSize, int ySize,
int colID, double speed, int bulletsPerShot, int timeLatency, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT_BY_TIME + SaladConstants.SEPARATOR+SaladConstants.SPREAD_SHOOT_BY_TIME +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR +bulletsPerShot + SaladConstants.SEPARATOR + timeLatency + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
*
*
* @param victimColId
* @param stayOnTile
* @param tileColId
* @param direction
*/
public void modifyTileCollisionBehaviour(int victimColId,String stayOnTile, char tileColId, String direction){
String order = SaladConstants.MODIFY_TILE_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + victimColId + SaladConstants.SEPARATOR
+ SaladConstants.STAY_ON_TILE + SaladConstants.SEPARATOR + stayOnTile + SaladConstants.SEPARATOR + tileColId + SaladConstants.SEPARATOR + direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void setDragTile(char colID, String url){
String order = SaladConstants.SET_DRAG_TILE + SaladConstants.SEPARATOR + SaladConstants.TILE_COLID + SaladConstants.SEPARATOR + colID +
SaladConstants.SEPARATOR + SaladConstants.DRAG_IMAGE + SaladConstants.SEPARATOR + url;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Delete actor without providing actor id. The selectedActorID is used.
*/
public void deleteActorNoID(){
String order = SaladConstants.DELETE_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavHitElimVic(int victimColID,int hitterColID, String moveDirection){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.HITTER_ELIMINATE_VICTIM + SaladConstants.SEPARATOR
+ SaladConstants.HITTER_ELIMINATE_VICTIM + SaladConstants.SEPARATOR + hitterColID + SaladConstants.SEPARATOR +
moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavShootHitObject(int victimCollID, int hitterCollID, String Direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimCollID + SaladConstants.SEPARATOR + SaladConstants.SHOOT_HIT_OBJECT + SaladConstants.SEPARATOR
+ SaladConstants.SHOOT_HIT_OBJECT + SaladConstants.SEPARATOR + SaladConstants.SEPARATOR +
hitterCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavPerishTog(int victimColID,int hitterColID, String moveDirection){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.PERISH_TOGETHER + SaladConstants.SEPARATOR +
SaladConstants.PERISH_TOGETHER+ SaladConstants.SEPARATOR + hitterColID+ SaladConstants.SEPARATOR +
moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavStayOnTile(int victimColID,char tileColID, String moveDirection){
String order = SaladConstants.MODIFY_TILE_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_TILE + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_TILE
+ SaladConstants.SEPARATOR + tileColID+ SaladConstants.SEPARATOR + moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify an object to enable it stand another.
*/
public void modifyCollisionBehaviorToStayOnObject(int victimCollisionID, int hitterCollID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR+victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.STAY_ON_OBJECT + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_OBJECT + SaladConstants.SEPARATOR + hitterCollID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify and object to enable it rebound off of another.
*/
public void modifyCollisionBehaviorRebounce(int victimCollisionID, int hitterCollID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.REBOUND + SaladConstants.SEPARATOR + SaladConstants.REBOUND + SaladConstants.SEPARATOR + hitterCollID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify an object such that it dies on colliding with a tile.
*/
public void modifyCollisionBehaviorToDieByTile(int victimCollisionID, char collID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.KILL_BY_TILE + SaladConstants.SEPARATOR + SaladConstants.KILL_BY_TILE + SaladConstants.SEPARATOR + collID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void deleteLevel(int levelID){
String order = SaladConstants.DELETE_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createLevel(int levelID){
String order = SaladConstants.CREATE_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets a level's initial scene
*/
public void setInitialScene(int levelID, int sceneID){
String order = SaladConstants.MODIFY_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
SaladConstants.SET_INIT_SCENE + SaladConstants.SEPARATOR + levelID + SaladConstants.SEPARATOR + sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void switchScene(int levelID, int sceneID){
String order = SaladConstants.SWITCH_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void deleteScene(int levelID, int sceneID){
String order = SaladConstants.DELETE_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createScene(int levelID, int sceneID){
String order = SaladConstants.CREATE_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifySceneBackground(String path, boolean wrapHorizontal, boolean wrapVertical, int playFieldXSize, int playFieldYSize){
String order = SaladConstants.MODIFY_SCENE_VIEW + SaladConstants.SEPARATOR + SaladConstants.BACKGROUND +
SaladConstants.SEPARATOR + path + SaladConstants.SEPARATOR + String.valueOf(wrapHorizontal) +
SaladConstants.SEPARATOR + String.valueOf(wrapVertical) + SaladConstants.SEPARATOR + playFieldXSize +
SaladConstants.SEPARATOR + playFieldYSize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScenePlayerInitPos(int sceneID, double xPos, double yPos){
String order = SaladConstants.MODIFY_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
sceneID + SaladConstants.SEPARATOR +SaladConstants.PLAYER_INIT_POS + SaladConstants.SEPARATOR + xPos +
SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGameSwitchSceneToNewLevelID(int oldLevelID, int newLevelID, int sceneID){
String order = SaladConstants.MODIFY_GAME + SaladConstants.SEPARATOR + SaladConstants.SWITCH_SCENE_TO_NEW_LEVEL_ID
+ SaladConstants.SEPARATOR + oldLevelID + SaladConstants.SEPARATOR + newLevelID + SaladConstants.SEPARATOR +
sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyInputManager(int key, String keyFunction){
String order = SaladConstants.MODIFY_INPUTMANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_KEY + SaladConstants.SEPARATOR + key +
SaladConstants.SEPARATOR + keyFunction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGravityMagnitude(double magnitude){
String order = SaladConstants.MODIFY_GRAVITY + SaladConstants.SEPARATOR + SaladConstants.GRAVITY_MAGNITUDE+ SaladConstants.SEPARATOR + magnitude;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScoreManagerInitScore(int score){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.INITIAL_SCORE+
SaladConstants.SEPARATOR + score;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScoreManagerCollisionScore(int score, int victimColID, int hitterColID){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_SCORE +
SaladConstants.SEPARATOR + score + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + hitterColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets the tile collision score
*/
public void modifyScoreManagerTileCollisionScore(int scoreChange, int victimCollID, char tileCollID){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_SCORE +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR +
victimCollID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets a scene's transition score
*/
public void modifyScoreManagerTransitionScore(int scoreChange){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TRANSITION_SCORE +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.SCENE_DONE + SaladConstants.SEPARATOR +
selectedSceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Set's a scene's transition score
*/
public void modifyScoreManagerScoreCondition(int scoreChange){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_SCORE_CONDITION +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.TIME;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Set Level's transition blood
*/
public void modifyBloodManagerLevelTransitionBlood(int changeBlood, int oldScene){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TRANSITION_BLOOD
+ SaladConstants.SEPARATOR + changeBlood + SaladConstants.SEPARATOR + SaladConstants.SCENE_DONE
+ SaladConstants.SEPARATOR + oldScene;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyBloodManagerTileCollision(int changeBlood, int victimCollID, char tileCollID){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_BLOOD + SaladConstants.SEPARATOR
+ changeBlood + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR + victimCollID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyBloodManagerCollision(int score, int changeBlood, int victimColID, int hitterColID){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_BLOOD +
SaladConstants.SEPARATOR + changeBlood + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + hitterColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Trigger event manager using time
*/
public void modifyTriggerEventManagerTime(int eventTriggerPairID, int time){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_TIME + SaladConstants.SEPARATOR
+ SaladConstants.TRIGGER_BY_TIME + SaladConstants.SEPARATOR + time;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerRemove(int eventTriggerPairID, String triggerByRemove, int ID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_REMOVE +
SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_REMOVE + SaladConstants.SEPARATOR + ID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerTileCollision(int eventTriggerPairID, int playerOrActorID, int xPos, int yPos,
int xSize, int ySize){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_TILE_COLLISION + SaladConstants.SEPARATOR
+ SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR + playerOrActorID + SaladConstants.SEPARATOR +
xPos + SaladConstants.SEPARATOR + yPos + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerEnemyShower(int eventTriggerPairID, int maxEnemy, String gfx){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_ENEMY_SHOWER + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_ENEMY_SHOWER + SaladConstants.SEPARATOR + maxEnemy + SaladConstants.SEPARATOR + gfx;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerChangeBlood(int eventTriggerPairID, int changeBlood){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_CHANGE_BLOOD + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_CHANGE_BLOOD + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + changeBlood;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerChangeLive(int eventTriggerPairID, int changeLive){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_CHANGE_LIVE + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_CHANGE_LIVE + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + changeLive;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerLoseGame(int eventTriggerPairID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_LOSE_GAME + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_LOSE_GAME;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerLevelDone(int eventTriggerPairID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_LEVEL_DONE + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_LEVEL_DONE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerInitLives(int lives, int playerID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_INIT_LIVES +
SaladConstants.SEPARATOR + lives + SaladConstants.SEPARATOR + playerID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerSetCollisionLife(int changeOfLife,int victimCollidID, int hitterCollidID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_LIFE + SaladConstants.SEPARATOR
+ changeOfLife + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR +
victimCollidID + SaladConstants.SEPARATOR + hitterCollidID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerSetTileCollisionLife(int changeOfLife, int victimCollidID, char tileCollID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_LIFE + SaladConstants.SEPARATOR
+ changeOfLife + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR +
victimCollidID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerRestoreLife(boolean restore){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.RESTORE_LIFE_BY_LEVEL
+ SaladConstants.SEPARATOR + String.valueOf(restore);
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateBackground(String gameState, String url){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.TSBACKGROUND +
SaladConstants.SEPARATOR + url;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateFrame(String gameState, int timeLength){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.FRAME +
SaladConstants.SEPARATOR + timeLength;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateMessage(String gameState, String message, int xPos, int yPos){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.DISPLAY_MESSAGE +
SaladConstants.SEPARATOR + message + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateImage(String gameState, String url, int xPos, int yPos){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.DISPLAY_IMAGE +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGameName(String name){
String order = SaladConstants.MODIFY_GAME + SaladConstants.SEPARATOR + SaladConstants.SET_NAME + SaladConstants.SEPARATOR + name ;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
// GAE funtions below. NOT orders sending to DataController
/**
* Called by Game Authorizing Environment to retrieve the current level ID
* @return the current level ID
*/
public int getCurrentLevelID(){
return myDataController.getCurrentLevelID();
}
/**
* Called by Game Authorizing Environment to retrieve the current scene ID
* @return the current scene ID
*/
public int getCurrentSceneID(){
return myDataController.getCurrentSceneID();
}
public List<String> getAttributes(){
List<String> s = myDataController.getNonPlayer(selectedActorID).getAttributes();
return s;
}
public void updateAttributesActorInfo(){
attributesPanel.updateActorInfo(selectedActorID);
}
public void switchActiveAttributesTab(int index){
attributesPanel.setTab(index);
}
public void switchLibraryTab(int index){
libraryPanel.setTab(index);
}
public int getActorID(){
return selectedActorID;
}
public DataController getDataController(){
return myDataController;
}
public void updateSelectedSceneID(int newID){
selectedSceneID = newID;
}
public void updatePlayerID(int newID){
playerID = newID;
}
public void updateSelectedActorID(int newID){
selectedActorID = newID;
}
public void setActorPanelSelection(int actorID){
switchLibraryTab(1);
ActorsPanel ap= (ActorsPanel) panelMap.get(SaladConstants.ACTOR_PANEL);
ap.update(actorID);
}
/**Modify the thumbnail in Actor panel*/
public void updateActorImage(String imageURL, String name){
ActorsPanel ap= (ActorsPanel) panelMap.get(SaladConstants.ACTOR_PANEL);
ap.setActorImage(selectedActorID, imageURL, name);
}
/**Called to get the url image into our engine package*/
public void uploadImage(int xSize,int ySize, String url){
// try {
// if (!DEBUG) myDataController.uploadImage(xSize, ySize, url);
// return;
// } catch (IOException e) {
// e.printStackTrace();
}
public int getActorCollisionID(){
//myDataController.getGame().getNonPlayerColid(int int sceneidint id)
return 0;
}
public int getSelectedIDFromDataController(){
return myDataController.getSelectedID();
}
public Map<String, Integer> getKeyMap(int playerId2) {
System.out.println("map");
if (myDataController.getGame() != null) {
if (myDataController.getGame().getPlayer(playerId2) != null) {
if (myDataController.getGame().getPlayer(playerId2).getKeyMap() != null) {
Map<Integer, String> map = myDataController.getGame().getPlayer(playerId2).getKeyMap();
System.out.println("map");
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
System.out.println("map");
for (Integer K : map.keySet()) {
String str = map.get(K);
System.out.println(str);
map2.put(str, K);
}
System.out.println("map2");
return map2;
}
}
}
Map<String, Integer> k = new HashMap<String, Integer>();
return k;
}
private void setColIDStayOnEveryTileID(int actorColID){
System.out.println(myDataController.getGame().getOccupiedTileColids());
for(char tileID :myDataController.getGame().getOccupiedTileColids()){
this.modifyCollisBehavStayOnTile(actorColID, tileID, "All");
}
}
public List<Character> getTileColIDs(){
return myDataController.getGame().getOccupiedTileColids();
}
public Map<Integer, NonPlayer> getMapOfNonPlayers(){
Map<Integer, NonPlayer> map = myDataController.getMapOfNonPlayers(selectedSceneID);
return map;
}
public List<GameObject> getObjectsByColid(int scene, int colID){
int levelID = getCurrentLevelID();
List<GameObject> objectColID = myDataController.getGame().getLevel(levelID).getScene(scene).getObjectsByColid(colID);
return objectColID;
}
public NonPlayer getNonPlayer(){
return myDataController.getNonPlayer(selectedActorID);
}
public Player getPlayer(){
return myDataController.getGame().getPlayer(playerID);
}
public int getPlayerID() {
return playerID;
}
public int getEventTriggerPair() {
eventPairID++;
return eventPairID;
}
}
|
/**
+ * @author Nick Pan and Talal Javed Qadri and Anthony Olawo and Kat Krieger
*/
package controller;
import game_authoring_environment.ActorsPanel;
import game_authoring_environment.AttributesPanel;
import game_authoring_environment.FullView;
import game_authoring_environment.GAE;
import game_authoring_environment.LeftPanel;
import game_authoring_environment.Library;
import game_authoring_environment.MenuBar;
import game_authoring_environment.RightPanel;
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.plaf.LayerUI;
import objects.GameObject;
import objects.NonPlayer;
import objects.Player;
import engine.GameEngine;
import saladConstants.SaladConstants;
import stage.Game;
public class GAEController {
private DataController myDataController;
private GAE g;
public static final String TITLE = "OOGASalad iTeam";
private static FullView fv;
private static MenuBar mb;
private HashMap<String, Image> availableImages;
private GameEngine myGameEngine;
private HashMap<String, JPanel> panelMap;
private AttributesPanel attributesPanel;
private Library libraryPanel;
private int selectedSceneID;
private int selectedActorID;
private int playerID;
private int eventPairID;
private static final boolean DEBUG = false;
public GAEController(){
playerID = SaladConstants.PLAYER_ID;
myDataController = new DataController();
eventPairID = 0;
myGameEngine = myDataController.initGameEngine(true);
//createGAE(this);
g = new GAE(this);
setUpVariables();
createLevel(1);
createScene(1,0);
switchScene(1,0);
//uploadImage(100,100,)
double d = 0;
//modifyGravityMagnitude(d);
}
private void setUpVariables(){
fv = g.getFullView();
mb = g.getMenuBar();
panelMap = fv.getMap();
attributesPanel = fv.getAttributes();
libraryPanel = fv.getLibrary();
//test code below
}
public GameEngine getEngine(){
return myGameEngine;
}
public RightPanel getRightPanel(){
return fv.getRightPanel();
}
public void createPlayer(int ID,String url, int xSize, int ySize, double xPos, double yPos, String name, int colID, int lives){
String order = SaladConstants.CREATE_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ID+SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url+ SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize +
SaladConstants.SEPARATOR + SaladConstants.POSITION + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos +
SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR+name + SaladConstants.SEPARATOR+ SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR +
colID + SaladConstants.SEPARATOR + SaladConstants.LIVES + SaladConstants.SEPARATOR + lives;
if (!DEBUG) myDataController.receiveOrder(order);
setColIDStayOnEveryTileID(colID);
System.out.println(order);
}
/**
* Modify player's speed without providing player id. The already set player ID is used.
*/
public void modifyPlayerSpeed(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SPEED + SaladConstants.SEPARATOR+xSpeed+ SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's image without providing player id. The already specified player ID is used.
*/
public void modifyPlayerImage( String url, int xSize, int ySize){
String order = SaladConstants.MODIFY_PLAYER_IMAGE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's ID without providing old player id. The already specified player ID is used for the old id.
*/
public void modifyPlayerID(int newID){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_TO_ID + SaladConstants.SEPARATOR+newID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyPlayerColID(int oldColID,int newColID){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's position without providing player id. The already specified playerID is used.
*/
public void modifyPlayerPos(double xPos, double yPos){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.POSITION + SaladConstants.SEPARATOR+xPos+ SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by doing a regular remove without providing player id. The already specified playerID is used.
*/
public void modifyPlayerRegRemove(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+
playerID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_REMOVE + SaladConstants.SEPARATOR +SaladConstants.REGULAR_REMOVE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by making it immortal without providing player id. The already specified playerID is used.
*/
public void modifyPlayerImmortal(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.IMMORTAL + SaladConstants.SEPARATOR+SaladConstants.IMMORTAL;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by making it immobile without providing player id. The already specified playerID is used.
*/
public void modifyPlayerImmobile(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.IMMOBILE + SaladConstants.SEPARATOR+SaladConstants.IMMOBILE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify number of bullets per shoot without specifying player ID. Global player ID which is ID of current selected player is used
*/
public void modifyPlayerSpreadShoot(String imageFileName, int xSize, int ySize, int collID, double speed, int bulletsPerShot, int maxBulletsAllowed){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR + imageFileName +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR +
collID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR + bulletsPerShot + SaladConstants.SEPARATOR + maxBulletsAllowed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot property by slowing it without providing player id. The already specified playerID is used.
*/
public void modifyPlayerSlowShoot(String url, int xSize, int ySize, int colID, double speed, int maxBullets){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR
+ xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR +
maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot property by quickening it without providing player id. The already specified playerID is used.
*/
public void modifyPlayerQuickShoot(String url, int xSize, int ySize, int colID, double speed, int numBullets, int maxBullets){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR+SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR + url +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed +
SaladConstants.SEPARATOR + numBullets + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player by changing its property to move in air
*/
public void modifyPlayerCanMoveInAir(boolean enableAirMove){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.CAN_MOVE_IN_AIR + SaladConstants.SEPARATOR+ String.valueOf(enableAirMove);
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's jump behavior without providing player id. The already specified playerID is used.
*/
public void modifyPlayerJumpBehavior(double magnitude, int numJumps){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.JUMP + SaladConstants.SEPARATOR+SaladConstants.JUMP + SaladConstants.SEPARATOR + magnitude +
SaladConstants.SEPARATOR + numJumps;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player so it can't jump
*/
public void modifyPlayerCanNotJump(){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
playerID + SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP +
SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveUp key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyUp(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_UP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveDown key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyDown(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ playerID +SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_DOWN;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveLeft key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyLeft(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_LEFT;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's moveRight key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyRight(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.MOVE_RIGHT;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's shoot key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyShoot(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.SHOOT_KEY;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify player's jump key without providing player id. The already specified playerID is used for the id.
*/
public void modifyPlayerKeyJump(int key){
String order = SaladConstants.MODIFY_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+playerID+SaladConstants.SEPARATOR +
SaladConstants.SET_KEY + SaladConstants.SEPARATOR+ key + SaladConstants.SEPARATOR + SaladConstants.JUMP_KEY;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Delete player without providing player id. The already specified playerID is used for the id.
*/
public void deletePlayer(){
String order = SaladConstants.DELETE_PLAYER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + playerID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createActor(int ID,String url, int xSize, int ySize,
double xPos, double yPos, String name, int colID, int lives){
String order = SaladConstants.CREATE_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ID+SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url+ SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize +
SaladConstants.SEPARATOR + SaladConstants.POSITION + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos +
SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR + name + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + colID
+ SaladConstants.SEPARATOR + SaladConstants.LIVES + SaladConstants.SEPARATOR + lives;
if (!DEBUG) myDataController.receiveOrder(order);
setColIDStayOnEveryTileID(colID);
System.out.println(order);
}
/**
* Modify actor's speed without providing actor id. The selectedActorID is used.
*/
public void modifyActorSpeedNoID(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SPEED + SaladConstants.SEPARATOR+xSpeed + SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's jump
*/
public void modifyActorJump(double magnitude, int numberOfJumpsAllowedInAir){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP + SaladConstants.SEPARATOR +
SaladConstants.JUMP + SaladConstants.SEPARATOR + magnitude + SaladConstants.SEPARATOR + numberOfJumpsAllowedInAir;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor to nullify jumping ability
*/
public void modifyActorCanNotJump(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ selectedActorID + SaladConstants.SEPARATOR + SaladConstants.CAN_NOT_JUMP + SaladConstants.SEPARATOR +
SaladConstants.CAN_NOT_JUMP;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor jumping latency with time
*/
public void modifyActorJumpByTime(double magnitude, int numberOfJumpsAllowedInAir, int latency){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP_BY_TIME + SaladConstants.SEPARATOR +
SaladConstants.JUMP_BY_TIME + SaladConstants.SEPARATOR + magnitude + SaladConstants.SEPARATOR + numberOfJumpsAllowedInAir + SaladConstants.SEPARATOR + latency;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's jump animation
*/
public void modifyActorAnimationJump(String url, int xSize, int ySize ){
String order = SaladConstants.MODIFY_ACTOR_ANIMATION + SaladConstants.SEPARATOR + SaladConstants.ID +
SaladConstants.SEPARATOR + selectedActorID + SaladConstants.SEPARATOR + SaladConstants.JUMP_ANIMATION +
SaladConstants.SEPARATOR + SaladConstants.JUMP + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR +
xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's forward move animation
*/
public void modifyActorAnimationFDMove(String imgURL, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR_ANIMATION + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID
+ SaladConstants.SEPARATOR + SaladConstants.FD_MOVE + SaladConstants.SEPARATOR + SaladConstants.FD_MOVE
+ SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Animate an actor's backward move animation
*/
public void modifyActorAnimationBKMove(String imgURL, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + SaladConstants.BK_MOVE + SaladConstants.SEPARATOR +
SaladConstants.BK_MOVE + SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize ;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's image without providing actor id. The selectedActorID is used.
*/
public void modifyActorImageNoID(String url, int xSize, int ySize){
String order = SaladConstants.MODIFY_ACTOR_IMAGE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ selectedActorID +SaladConstants.SEPARATOR +
SaladConstants.IMAGE + SaladConstants.SEPARATOR+url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's ID without providing old actor id. The selectedActorID is used for the old id.
*/
public void modifyActorIDNoOldID(int newID){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_TO_ID + SaladConstants.SEPARATOR+newID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorName(String name){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ selectedActorID+SaladConstants.SEPARATOR + SaladConstants.NAME + SaladConstants.SEPARATOR+ name;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorColIDNoID(int newColID){
int oldColID = myDataController.getGame().getPlayer(selectedActorID).colid;
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+ oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorColID(int oldColID,int newColID){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+oldColID+SaladConstants.SEPARATOR +
SaladConstants.CHANGE_COLLISION_ID + SaladConstants.SEPARATOR +newColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's position without providing actor id. The selectedActorID is used.
*/
public void modifyActorPosNoID(double xPos, double yPos){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.POSITION + SaladConstants.SEPARATOR+xPos+ SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's regular move property without providing actor id. The selectedActorID is used.
*/
public void modifyActorRegMoveNoID(double xSpeed, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_MOVE + SaladConstants.SEPARATOR + SaladConstants.REGULAR_MOVE+ SaladConstants.SEPARATOR +xSpeed +
SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyActorSpreadShoot(String imgURL, int xSize, int ySize, int collID,
double speed, int bulletsPerShot, int maxBullets ){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
selectedActorID + SaladConstants.SEPARATOR + SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT + SaladConstants.SEPARATOR + imgURL + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR
+ ySize + SaladConstants.SEPARATOR + collID + SaladConstants.SEPARATOR + speed + SaladConstants.SEPARATOR +
bulletsPerShot + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's vertical movement
*/
public void modifyActorBackForthVerticalMove( double amplitude, int lantency, double ySpeed){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
selectedActorID + SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE_WITH_VERTICAL_SPEED +
SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE_WITH_VERTICAL_SPEED + SaladConstants.SEPARATOR
+ amplitude + SaladConstants.SEPARATOR + lantency + SaladConstants.SEPARATOR + ySpeed;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's regular move property without providing actor id. The selectedActorID is used.
*/
public void modifyActorBackForthMoveNoID(double amplitude, int latency){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.BACK_FORTH_MOVE + SaladConstants.SEPARATOR + SaladConstants.BACK_FORTH_MOVE+ SaladConstants.SEPARATOR
+ amplitude + SaladConstants.SEPARATOR + latency;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by doing a regular remove without providing actor id. The selectedActorID is used.
*/
public void modifyActorRegRemoveNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.REGULAR_REMOVE + SaladConstants.SEPARATOR +SaladConstants.REGULAR_REMOVE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by making it immortal without providing actor id. The selectedActorID is used.
*/
public void modifyActorImmortalNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID +
SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.IMMORTAL + SaladConstants.SEPARATOR+SaladConstants.IMMORTAL;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor by making it immobile without providing actor id. The selectedActorID is used.
*/
public void modifyActorImmobileNoID(){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+
selectedActorID+SaladConstants.SEPARATOR + SaladConstants.IMMOBILE + SaladConstants.SEPARATOR+SaladConstants.IMMOBILE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by slowing it without providing actor id. The selectedActorID is used.
*/
public void modifyActorSlowShoot(String url, int xSize, int ySize, int colID, double speed, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT + SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR
+ xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by quickening it without providing actor id. The selectedActorID is used.
*/
public void modifyActorQuickShoot(String url, int xSize, int ySize, int colID, double speed, int numBullets, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR+SaladConstants.QUICK_SHOOT + SaladConstants.SEPARATOR + url +
SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR + speed +
SaladConstants.SEPARATOR + numBullets + SaladConstants.SEPARATOR+ maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's shoot property by slowing it without providing actor id and with a time latency. The selectedActorID is used.
*/
public void modifyActorSlowShootByTime(String url, int xSize, int ySize, int colID, double speed, int timeLatency, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SLOW_SHOOT_BY_TIME + SaladConstants.SEPARATOR+SaladConstants.SLOW_SHOOT_BY_TIME +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR +timeLatency + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify actor's spread shoot property without providing actor id and with a time latency. The selectedActorID is used.
*/
public void modifyActorSpreadShootByTime(String url, int xSize, int ySize,
int colID, double speed, int bulletsPerShot, int timeLatency, int maxBullets){
String order = SaladConstants.MODIFY_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+selectedActorID+SaladConstants.SEPARATOR +
SaladConstants.SPREAD_SHOOT_BY_TIME + SaladConstants.SEPARATOR+SaladConstants.SPREAD_SHOOT_BY_TIME +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize + SaladConstants.SEPARATOR + colID + SaladConstants.SEPARATOR
+ speed + SaladConstants.SEPARATOR +bulletsPerShot + SaladConstants.SEPARATOR + timeLatency + SaladConstants.SEPARATOR + maxBullets;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
*
*
* @param victimColId
* @param stayOnTile
* @param tileColId
* @param direction
*/
public void modifyTileCollisionBehaviour(int victimColId,String stayOnTile, char tileColId, String direction){
String order = SaladConstants.MODIFY_TILE_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + victimColId + SaladConstants.SEPARATOR
+ SaladConstants.STAY_ON_TILE + SaladConstants.SEPARATOR + stayOnTile + SaladConstants.SEPARATOR + tileColId + SaladConstants.SEPARATOR + direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void setDragTile(char colID, String url){
String order = SaladConstants.SET_DRAG_TILE + SaladConstants.SEPARATOR + SaladConstants.TILE_COLID + SaladConstants.SEPARATOR + colID +
SaladConstants.SEPARATOR + SaladConstants.DRAG_IMAGE + SaladConstants.SEPARATOR + url;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Delete actor without providing actor id. The selectedActorID is used.
*/
public void deleteActorNoID(){
String order = SaladConstants.DELETE_ACTOR + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR + selectedActorID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavHitElimVic(int victimColID,int hitterColID, String moveDirection){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.HITTER_ELIMINATE_VICTIM + SaladConstants.SEPARATOR
+ SaladConstants.HITTER_ELIMINATE_VICTIM + SaladConstants.SEPARATOR + hitterColID + SaladConstants.SEPARATOR +
moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavShootHitObject(int victimCollID, int hitterCollID, String Direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimCollID + SaladConstants.SEPARATOR + SaladConstants.SHOOT_HIT_OBJECT + SaladConstants.SEPARATOR
+ SaladConstants.SHOOT_HIT_OBJECT + SaladConstants.SEPARATOR + SaladConstants.SEPARATOR +
hitterCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavPerishTog(int victimColID,int hitterColID, String moveDirection){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.PERISH_TOGETHER + SaladConstants.SEPARATOR +
SaladConstants.PERISH_TOGETHER+ SaladConstants.SEPARATOR + hitterColID+ SaladConstants.SEPARATOR +
moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyCollisBehavStayOnTile(int victimColID,char tileColID, String moveDirection){
String order = SaladConstants.MODIFY_TILE_COLLISION_BEHAVIOR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_TILE + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_TILE
+ SaladConstants.SEPARATOR + tileColID+ SaladConstants.SEPARATOR + moveDirection;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify an object to enable it stand another.
*/
public void modifyCollisionBehaviorToStayOnObject(int victimCollisionID, int hitterCollID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR+victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.STAY_ON_OBJECT + SaladConstants.SEPARATOR + SaladConstants.STAY_ON_OBJECT + SaladConstants.SEPARATOR + hitterCollID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify and object to enable it rebound off of another.
*/
public void modifyCollisionBehaviorRebounce(int victimCollisionID, int hitterCollID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.REBOUND + SaladConstants.SEPARATOR + SaladConstants.REBOUND + SaladConstants.SEPARATOR + hitterCollID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Modify an object such that it dies on colliding with a tile.
*/
public void modifyCollisionBehaviorToDieByTile(int victimCollisionID, char collID, String direction){
String order = SaladConstants.MODIFY_COLLISION_BEHAVIOUR + SaladConstants.SEPARATOR + SaladConstants.COLLISION_ID + SaladConstants.SEPARATOR + victimCollisionID+SaladConstants.SEPARATOR +
SaladConstants.KILL_BY_TILE + SaladConstants.SEPARATOR + SaladConstants.KILL_BY_TILE + SaladConstants.SEPARATOR + collID + SaladConstants.SEPARATOR +
direction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void deleteLevel(int levelID){
String order = SaladConstants.DELETE_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createLevel(int levelID){
String order = SaladConstants.CREATE_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets a level's initial scene
*/
public void setInitialScene(int levelID, int sceneID){
String order = SaladConstants.MODIFY_LEVEL + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
SaladConstants.SET_INIT_SCENE + SaladConstants.SEPARATOR + levelID + SaladConstants.SEPARATOR + sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void switchScene(int levelID, int sceneID){
String order = SaladConstants.SWITCH_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void deleteScene(int levelID, int sceneID){
String order = SaladConstants.DELETE_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void createScene(int levelID, int sceneID){
String order = SaladConstants.CREATE_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR+levelID+SaladConstants.SEPARATOR +
SaladConstants.ID + SaladConstants.SEPARATOR+sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifySceneBackground(String path, boolean wrapHorizontal, boolean wrapVertical, int playFieldXSize, int playFieldYSize){
String order = SaladConstants.MODIFY_SCENE_VIEW + SaladConstants.SEPARATOR + SaladConstants.BACKGROUND +
SaladConstants.SEPARATOR + path + SaladConstants.SEPARATOR + String.valueOf(wrapHorizontal) +
SaladConstants.SEPARATOR + String.valueOf(wrapVertical) + SaladConstants.SEPARATOR + playFieldXSize +
SaladConstants.SEPARATOR + playFieldYSize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScenePlayerInitPos(int sceneID, double xPos, double yPos){
String order = SaladConstants.MODIFY_SCENE + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
sceneID + SaladConstants.SEPARATOR +SaladConstants.PLAYER_INIT_POS + SaladConstants.SEPARATOR + xPos +
SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGameSwitchSceneToNewLevelID(int oldLevelID, int newLevelID, int sceneID){
String order = SaladConstants.MODIFY_GAME + SaladConstants.SEPARATOR + SaladConstants.SWITCH_SCENE_TO_NEW_LEVEL_ID
+ SaladConstants.SEPARATOR + oldLevelID + SaladConstants.SEPARATOR + newLevelID + SaladConstants.SEPARATOR +
sceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyInputManager(int key, String keyFunction){
String order = SaladConstants.MODIFY_INPUTMANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_KEY + SaladConstants.SEPARATOR + key +
SaladConstants.SEPARATOR + keyFunction;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGravityMagnitude(double magnitude){
String order = SaladConstants.MODIFY_GRAVITY + SaladConstants.SEPARATOR + SaladConstants.GRAVITY_MAGNITUDE+ SaladConstants.SEPARATOR + magnitude;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScoreManagerInitScore(int score){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.INITIAL_SCORE+
SaladConstants.SEPARATOR + score;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyScoreManagerCollisionScore(int score, int victimColID, int hitterColID){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_SCORE +
SaladConstants.SEPARATOR + score + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + hitterColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets the tile collision score
*/
public void modifyScoreManagerTileCollisionScore(int scoreChange, int victimCollID, char tileCollID){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_SCORE +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR +
victimCollID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Sets a scene's transition score
*/
public void modifyScoreManagerTransitionScore(int scoreChange){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TRANSITION_SCORE +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.SCENE_DONE + SaladConstants.SEPARATOR +
selectedSceneID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Set's a scene's transition score
*/
public void modifyScoreManagerScoreCondition(int scoreChange){
String order = SaladConstants.MODIFY_SCORE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_SCORE_CONDITION +
SaladConstants.SEPARATOR + scoreChange + SaladConstants.SEPARATOR + SaladConstants.TIME;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Set Level's transition blood
*/
public void modifyBloodManagerLevelTransitionBlood(int changeBlood, int oldScene){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TRANSITION_BLOOD
+ SaladConstants.SEPARATOR + changeBlood + SaladConstants.SEPARATOR + SaladConstants.SCENE_DONE
+ SaladConstants.SEPARATOR + oldScene;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyBloodManagerTileCollision(int changeBlood, int victimCollID, char tileCollID){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_BLOOD + SaladConstants.SEPARATOR
+ changeBlood + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR + victimCollID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyBloodManagerCollision(int score, int changeBlood, int victimColID, int hitterColID){
String order = SaladConstants.MODIFY_BLOOD_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_BLOOD +
SaladConstants.SEPARATOR + changeBlood + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR
+ victimColID + SaladConstants.SEPARATOR + hitterColID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
/**
* Trigger event manager using time
*/
public void modifyTriggerEventManagerTime(int eventTriggerPairID, int time){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_TIME + SaladConstants.SEPARATOR
+ SaladConstants.TRIGGER_BY_TIME + SaladConstants.SEPARATOR + time;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerRemove(int eventTriggerPairID, String triggerByRemove, int ID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR +
eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_REMOVE +
SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_REMOVE + SaladConstants.SEPARATOR + ID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerTileCollision(int eventTriggerPairID, int playerOrActorID, int xPos, int yPos,
int xSize, int ySize){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.TRIGGER_BY_TILE_COLLISION + SaladConstants.SEPARATOR
+ SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR + playerOrActorID + SaladConstants.SEPARATOR +
xPos + SaladConstants.SEPARATOR + yPos + SaladConstants.SEPARATOR + xSize + SaladConstants.SEPARATOR + ySize;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerEnemyShower(int eventTriggerPairID, int maxEnemy, String gfx){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_ENEMY_SHOWER + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_ENEMY_SHOWER + SaladConstants.SEPARATOR + maxEnemy + SaladConstants.SEPARATOR + gfx;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerChangeBlood(int eventTriggerPairID, int changeBlood){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_CHANGE_BLOOD + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_CHANGE_BLOOD + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + changeBlood;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerChangeLive(int eventTriggerPairID, int changeLive){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_CHANGE_LIVE + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_CHANGE_LIVE + SaladConstants.SEPARATOR + playerID + SaladConstants.SEPARATOR + changeLive;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerLoseGame(int eventTriggerPairID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_LOSE_GAME + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_LOSE_GAME;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTriggerEventManagerLevelDone(int eventTriggerPairID){
String order = SaladConstants.MODIFY_TRIGGER_EVENT_MANAGER + SaladConstants.SEPARATOR + SaladConstants.ID + SaladConstants.SEPARATOR
+ eventTriggerPairID + SaladConstants.SEPARATOR + SaladConstants.EVENT_LEVEL_DONE + SaladConstants.SEPARATOR
+ SaladConstants.EVENT_LEVEL_DONE;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerInitLives(int lives, int playerID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_INIT_LIVES +
SaladConstants.SEPARATOR + lives + SaladConstants.SEPARATOR + playerID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerSetCollisionLife(int changeOfLife,int victimCollidID, int hitterCollidID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_COLLISION_LIFE + SaladConstants.SEPARATOR
+ changeOfLife + SaladConstants.SEPARATOR + SaladConstants.COLLISION + SaladConstants.SEPARATOR +
victimCollidID + SaladConstants.SEPARATOR + hitterCollidID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerSetTileCollisionLife(int changeOfLife, int victimCollidID, char tileCollID){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.SET_TILE_COLLISION_LIFE + SaladConstants.SEPARATOR
+ changeOfLife + SaladConstants.SEPARATOR + SaladConstants.TILE_COLLISION + SaladConstants.SEPARATOR +
victimCollidID + SaladConstants.SEPARATOR + tileCollID;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyLifeManagerRestoreLife(boolean restore){
String order = SaladConstants.MODIFY_LIFE_MANAGER + SaladConstants.SEPARATOR + SaladConstants.RESTORE_LIFE_BY_LEVEL
+ SaladConstants.SEPARATOR + String.valueOf(restore);
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateBackground(String gameState, String url){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.TSBACKGROUND +
SaladConstants.SEPARATOR + url;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateFrame(String gameState, int timeLength){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.FRAME +
SaladConstants.SEPARATOR + timeLength;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateMessage(String gameState, String message, int xPos, int yPos){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.DISPLAY_MESSAGE +
SaladConstants.SEPARATOR + message + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyTransitionStateImage(String gameState, String url, int xPos, int yPos){
String order = SaladConstants.MODIFY_TRANSITION_STATE + SaladConstants.SEPARATOR + SaladConstants.GAME_STATE +
SaladConstants.SEPARATOR + gameState + SaladConstants.SEPARATOR + SaladConstants.DISPLAY_IMAGE +
SaladConstants.SEPARATOR + url + SaladConstants.SEPARATOR + xPos + SaladConstants.SEPARATOR + yPos;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
public void modifyGameName(String name){
String order = SaladConstants.MODIFY_GAME + SaladConstants.SEPARATOR + SaladConstants.SET_NAME + SaladConstants.SEPARATOR + name ;
if (!DEBUG) myDataController.receiveOrder(order);
System.out.println(order);
}
// GAE funtions below. NOT orders sending to DataController
/**
* Called by Game Authorizing Environment to retrieve the current level ID
* @return the current level ID
*/
public int getCurrentLevelID(){
return myDataController.getCurrentLevelID();
}
/**
* Called by Game Authorizing Environment to retrieve the current scene ID
* @return the current scene ID
*/
public int getCurrentSceneID(){
return myDataController.getCurrentSceneID();
}
public List<String> getAttributes(){
List<String> s = myDataController.getNonPlayer(selectedActorID).getAttributes();
return s;
}
public void updateAttributesActorInfo(){
attributesPanel.updateActorInfo(selectedActorID);
}
public void switchActiveAttributesTab(int index){
attributesPanel.setTab(index);
}
public void switchLibraryTab(int index){
libraryPanel.setTab(index);
}
public int getActorID(){
return selectedActorID;
}
public DataController getDataController(){
return myDataController;
}
public void updateSelectedSceneID(int newID){
selectedSceneID = newID;
}
public void updatePlayerID(int newID){
playerID = newID;
}
public void updateSelectedActorID(int newID){
selectedActorID = newID;
}
public void setActorPanelSelection(int actorID){
switchLibraryTab(1);
ActorsPanel ap= (ActorsPanel) panelMap.get(SaladConstants.ACTOR_PANEL);
ap.update(actorID);
}
/**Modify the thumbnail in Actor panel*/
public void updateActorImage(String imageURL, String name){
ActorsPanel ap= (ActorsPanel) panelMap.get(SaladConstants.ACTOR_PANEL);
ap.setActorImage(selectedActorID, imageURL, name);
}
/**Called to get the url image into our engine package*/
public void uploadImage(int xSize,int ySize, String url){
// try {
// if (!DEBUG) myDataController.uploadImage(xSize, ySize, url);
// return;
// } catch (IOException e) {
// e.printStackTrace();
}
public int getActorCollisionID(){
//myDataController.getGame().getNonPlayerColid(int int sceneidint id)
return 0;
}
public int getSelectedIDFromDataController(){
return myDataController.getSelectedID();
}
public Map<String, Integer> getKeyMap(int playerId2) {
System.out.println("map");
if (myDataController.getGame() != null) {
if (myDataController.getGame().getPlayer(playerId2) != null) {
if (myDataController.getGame().getPlayer(playerId2).getKeyMap() != null) {
Map<Integer, String> map = myDataController.getGame().getPlayer(playerId2).getKeyMap();
System.out.println("map");
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
System.out.println("map");
for (Integer K : map.keySet()) {
String str = map.get(K);
System.out.println(str);
map2.put(str, K);
}
System.out.println("map2");
return map2;
}
}
}
Map<String, Integer> k = new HashMap<String, Integer>();
return k;
}
private void setColIDStayOnEveryTileID(int actorColID){
System.out.println(myDataController.getGame().getOccupiedTileColids());
for(char tileID :myDataController.getGame().getOccupiedTileColids()){
this.modifyCollisBehavStayOnTile(actorColID, tileID, "All");
}
}
public List<Character> getTileColIDs(){
return myDataController.getGame().getOccupiedTileColids();
}
public Map<Integer, NonPlayer> getMapOfNonPlayers(){
Map<Integer, NonPlayer> map = myDataController.getMapOfNonPlayers(selectedSceneID);
return map;
}
public List<GameObject> getObjectsByColid(int scene, int colID){
int levelID = getCurrentLevelID();
List<GameObject> objectColID = myDataController.getGame().getLevel(levelID).getScene(scene).getObjectsByColid(colID);
return objectColID;
}
public NonPlayer getNonPlayer(){
return myDataController.getNonPlayer(selectedActorID);
}
public Player getPlayer(){
return myDataController.getGame().getPlayer(playerID);
}
public int getPlayerID() {
return playerID;
}
public int getEventTriggerPair() {
eventPairID++;
return eventPairID;
}
}
|
package core.search;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import global.utils.Logger;
import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SearchEngine {
public static File find(File startDir, List<SearchAction> actions) {
if (startDir == null || actions == null || actions.isEmpty()) {
Logger.log("find fail: INVALID args");
return null;
}
File curDir = startDir;
for (SearchAction action : actions) {
if (curDir == null) {
return null;
}
// if the SearchAction::name was set by global vars, it could be empty, this may means ignore this search
// action, so continue;
if (action.getName() == null || action.getName().isEmpty())
continue;
if (!curDir.isDirectory()) {
curDir = startDir.getParentFile();
}
switch (action.getActionType()) {
case DIR_ABOVE:
curDir = getEngine().findDirAbove(curDir, action);
break;
case DIR_BELOW:
curDir = getEngine().findDirBelow(curDir, action);
break;
case FILE:
curDir = getEngine().findFile(curDir, action);
break;
}
}
return curDir;
}
// Search
@Nullable
private File findDirAbove(@NotNull File dirFrom, SearchAction action) {
File currentFile = dirFrom;
int deepLimit = action.getDeepLimit();
while (deepLimit > 0 || deepLimit == DEEP_LIMITLESS) {
if (deepLimit != DEEP_LIMITLESS) {
deepLimit
}
// Next File
currentFile = currentFile.getParentFile();
if (currentFile == null) {
return null;
}
//Check Name
if (isNameEquals(action, currentFile.getName())) {
return currentFile;
}
}
return null;
}
@Nullable
private File findDirBelow(@NotNull File dirFrom, SearchAction action) {
return findDirectoryRecursively(action, dirFrom, action.getDeepLimit());
}
@Nullable
private File findFile(@NotNull File dirFrom, SearchAction action) {
return findFileRecursively(action, dirFrom, action.getDeepLimit());
}
// Utils
public static final int DEEP_LIMITLESS = -1;
private static SearchEngine engine;
private static SearchEngine getEngine() {
if (engine == null) {
engine = new SearchEngine();
}
return engine;
}
private boolean isNameEquals(SearchAction action, String fileName) {
if (action.isRegexp()) {
Pattern p = Pattern.compile(action.getName());
Matcher m = p.matcher(fileName);
return m.matches();
} else {
return fileName.equals(action.getName());
}
}
@Nullable
private File findDirectoryRecursively(SearchAction action, File dirFrom, int deepLimit) {
// SubDirs
File[] dirs = dirFrom.listFiles(File::isDirectory);
if (dirs == null) {
return null;
}
// Scan children
for (File dir : dirs) {
if (isNameEquals(action, dir.getName())) {
return dir;
}
}
if (deepLimit == 0) {
return null;
}
//Scan subDirs
for (File dir : dirs) {
int curDeepLimit = DEEP_LIMITLESS;
if (deepLimit != DEEP_LIMITLESS) {
curDeepLimit = deepLimit - 1;
}
File result = findDirectoryRecursively(action, dir, curDeepLimit);
if (result != null) {
return result;
}
}
return null;
}
@Nullable
private File findFileRecursively(SearchAction action, File dirFrom, int deepLimit) {
// Scan children
File[] files = dirFrom.listFiles((file) -> !file.isDirectory());
if (files != null) {
for (File file : files) {
if (isNameEquals(action, file.getName())) {
return file;
}
}
}
File[] dirs = dirFrom.listFiles(File::isDirectory);
if (deepLimit == 0 || dirs == null) {
return null;
}
//Scan subDir's children
for (File dir : dirs) {
int curDeepLimit = DEEP_LIMITLESS;
if (deepLimit != DEEP_LIMITLESS) {
curDeepLimit = deepLimit - 1;
}
File result = findFileRecursively(action, dir, curDeepLimit);
if (result != null) {
return result;
}
}
return null;
}
}
|
package de.toman.milight;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* This class represents a MiLight WiFi box and is able to send commands to a
* particular box.
*
* @author Stefan Toman (toman@tum.de)
*/
public class WiFiBox {
/**
* The address of the WiFi box
*/
private InetAddress address;
/**
* The port of the WiFi box
*/
private int port;
/**
* The default port for unconfigured boxes.
*/
public static final int DEFAULT_PORT = 8899;
/**
* The sleep time between both messages for switching lights to the white
* mode.
*/
public static final int DEFAULT_SLEEP_BETWEEN_MESSAGES = 100;
/**
* The command code for "RGBW COLOR LED ALL OFF".
*/
public static final int COMMAND_ALL_OFF = 0x41;
/**
* The command code for "GROUP 1 ALL OFF".
*/
public static final int COMMAND_GROUP_1_OFF = 0x46;
/**
* The command code for "GROUP 2 ALL OFF".
*/
public static final int COMMAND_GROUP_2_OFF = 0x48;
/**
* The command code for "GROUP 3 ALL OFF".
*/
public static final int COMMAND_GROUP_3_OFF = 0x4A;
/**
* The command code for "GROUP 4 ALL OFF".
*/
public static final int COMMAND_GROUP_4_OFF = 0x4C;
/**
* The command code for "RGBW COLOR LED ALL ON".
*/
public static final int COMMAND_ALL_ON = 0x42;
/**
* The command code for "GROUP 1 ALL ON".
*/
public static final int COMMAND_GROUP_1_ON = 0x45;
/**
* The command code for "GROUP 2 ALL ON".
*/
public static final int COMMAND_GROUP_2_ON = 0x47;
/**
* The command code for "GROUP 3 ALL ON".
*/
public static final int COMMAND_GROUP_3_ON = 0x49;
/**
* The command code for "GROUP 4 ALL ON".
*/
public static final int COMMAND_GROUP_4_ON = 0x4B;
/**
* The command code for "SET COLOR TO WHITE (GROUP ALL)". Send an "ON"
* command 100ms before.
*/
public static final int COMMAND_ALL_WHITE = 0xC2;
/**
* The command code for "SET COLOR TO WHITE (GROUP 1)". Send an "ON" command
* 100ms before.
*/
public static final int COMMAND_GROUP_1_WHITE = 0xC5;
/**
* The command code for "SET COLOR TO WHITE (GROUP 2)". Send an "ON" command
* 100ms before.
*/
public static final int COMMAND_GROUP_2_WHITE = 0xC7;
/**
* The command code for "SET COLOR TO WHITE (GROUP 3)". Send an "ON" command
* 100ms before.
*/
public static final int COMMAND_GROUP_3_WHITE = 0xC9;
/**
* The command code for "SET COLOR TO WHITE (GROUP 4)". Send an "ON" command
* 100ms before.
*/
public static final int COMMAND_GROUP_4_WHITE = 0xCB;
/**
* The command code for "DISCO MODE".
*/
public static final int COMMAND_DISCO = 0x4D;
/**
* The command code for "DISCO SPEED FASTER".
*/
public static final int COMMAND_DISCO_FASTER = 0x44;
/**
* The command code for "DISCO SPEED SLOWER".
*/
public static final int COMMAND_DISCO_SLOWER = 0x43;
/**
* The command code for "DIRECT BRIGHTNESS SETTING" (part of a two-byte
* command).
*/
public static final int COMMAND_BRIGHTNESS = 0x4E;
/**
* The maximum brightness value, starting at 0.
*/
public static final int MAX_BRIGHTNESS = 0x3B;
/**
* A constructor creating a new instance of the WiFi box class.
*
* @param address
* is the address of the WiFi box
* @param port
* is the port of the WiFi box (omit this if unsure)
*/
public WiFiBox(InetAddress address, int port) {
super();
this.address = address;
this.port = port;
}
/**
* A constructor creating a new instance of the WiFi box class using the
* default port number.
*
* @param address
* is the address of the WiFi box
*/
public WiFiBox(InetAddress address) {
this(address, DEFAULT_PORT);
}
/**
* A constructor creating a new instance of the WiFi box class. The address
* is resolved from a hostname or ip address.
*
* @param host
* is the host given as hostname such as "domain.tld" or string
* repesentation of an ip address
* @param port
* is the port of the WiFi box (omit this if unsure)
* @throws UnknownHostException
* if the hostname could not be resolved
*/
public WiFiBox(String host, int port) throws UnknownHostException {
this(InetAddress.getByName(host), port);
}
/**
* A constructor creating a new instance of the WiFi box class using the
* default port number. The address is resolved from a hostname or ip
* address.
*
* @param host
* is the host given as hostname such as "domain.tld" or string
* repesentation of an ip address
* @throws UnknownHostException
* if the hostname could not be resolved
*/
public WiFiBox(String host) throws UnknownHostException {
this(host, DEFAULT_PORT);
}
private void sendMessage(byte[] messages) throws IOException {
if (messages.length != 3) {
throw new IllegalArgumentException(
"The message to send should consist of exactly 3 bytes.");
}
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(messages, messages.length,
address, port);
socket.send(packet);
socket.close();
}
/**
* This function pads a one-byte message to a three-byte message by adding
* the default bytes 0x00 0x55.
*
* @param message
* is the message to pad
* @return is the padded message
*/
private byte[] padMessage(int message) {
byte[] paddedMessage = { (byte) message, 0x55 & 0x00, 0x55 & 0x55 };
return paddedMessage;
}
/**
* This function pads a two-byte message to a three-byte message by adding
* the default byte 0x55.
*
* @param message1
* is the first byte of the message to pad
* @param message2
* is the second byte of the message to pad
* @return is the padded message
*/
private byte[] padMessage(int message1, int message2) {
byte[] paddedMessage = { (byte) message1, (byte) message2, 0x55 & 0x55 };
return paddedMessage;
}
/**
* This function sends an one-byte control message to the WiFi box. The
* message is padded with 0x00 0x55 as given in the documentation.
*
* @param message
* is the message code to send
* @throws IOException
* if the message could not be sent
*/
private void sendMessage(int message) throws IOException {
// pad the message with 0x00 0x55
byte[] paddedMessage = padMessage(message);
// send the padded message
sendMessage(paddedMessage);
}
/**
* This function sends a two-byte control message to the WiFi box. The
* message is padded with 0x55 as given in the documentation.
*
* @param message1
* is the first byte of the message to send
* @param message2
* is the second byte of the message to send
* @throws IOException
* if the message could not be sent
*/
private void sendMessage(int message1, int message2) throws IOException {
// pad the message with 0x55
byte[] paddedMessage = padMessage(message1, message2);
// send the padded message
sendMessage(paddedMessage);
}
private void sendMultipleMessages(final byte[][] messages, final long sleep)
throws IllegalArgumentException {
// check arguments
for (int i = 0; i < messages.length; i++) {
if (messages[i].length != 3) {
throw new IllegalArgumentException(
"All messages should consist of three bytes.");
}
}
// start new thread
new Thread(new Runnable() {
public void run() {
try {
for (byte[] message : messages) {
WiFiBox.this.sendMessage(message);
Thread.sleep(sleep);
}
} catch (IOException e) {
// if the message could not be sent
} catch (InterruptedException e) {
// if the thread could not sleep
}
}
}).start();
}
/**
* This function sends multiple one-byte messages to the WiFi box. All of
* the are padded with the corresponding bytes. Note that the messages are
* sent in a new thread. Therefore, you should not send other commands
* directly after executing this one. Also, there are no exceptions when
* sending messages fails since they occur in another thread.
*
* @param messages
* is the messages to send (in order)
* @param sleep
* is the time to wait between two message in milliseconds
*/
private void sendMultipleMessages(final int[] messages, final long sleep) {
// pad messages
byte[][] paddedMessages = new byte[messages.length][3];
for (int i = 0; i < messages.length; i++) {
paddedMessages[i] = padMessage(messages[i]);
}
// send the padded messages
sendMultipleMessages(paddedMessages, sleep);
}
/**
* Switch all lights off (all groups).
*
* @throws IOException
* if the message could not be sent
*/
public void off() throws IOException {
sendMessage(COMMAND_ALL_OFF);
}
public void off(int group) throws IOException, IllegalArgumentException {
switch (group) {
case 1:
sendMessage(COMMAND_GROUP_1_OFF);
break;
case 2:
sendMessage(COMMAND_GROUP_2_OFF);
break;
case 3:
sendMessage(COMMAND_GROUP_3_OFF);
break;
case 4:
sendMessage(COMMAND_GROUP_4_OFF);
break;
default:
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
}
/**
* Switch all lights on (all groups).
*
* @throws IOException
* if the message could not be sent
*/
public void on() throws IOException {
sendMessage(COMMAND_ALL_ON);
}
public void on(int group) throws IOException, IllegalArgumentException {
switch (group) {
case 1:
sendMessage(COMMAND_GROUP_1_ON);
break;
case 2:
sendMessage(COMMAND_GROUP_2_ON);
break;
case 3:
sendMessage(COMMAND_GROUP_3_ON);
break;
case 4:
sendMessage(COMMAND_GROUP_4_ON);
break;
default:
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
}
/**
* Switch all lights in all groups to the white mode. Note that the messages
* are sent in a new thread. Therefore, you should not send other commands
* directly after executing this one. Also, there are no exceptions when
* sending messages fails since they occur in another thread.
*/
public void white() {
int[] messages = { COMMAND_ALL_ON, COMMAND_ALL_WHITE };
sendMultipleMessages(messages, DEFAULT_SLEEP_BETWEEN_MESSAGES);
}
public void white(int group) throws IllegalArgumentException {
// create message array
int[] messages = new int[2];
switch (group) {
case 1:
messages[0] = COMMAND_GROUP_1_ON;
messages[1] = COMMAND_GROUP_1_WHITE;
break;
case 2:
messages[0] = COMMAND_GROUP_2_ON;
messages[1] = COMMAND_GROUP_2_WHITE;
break;
case 3:
messages[0] = COMMAND_GROUP_3_ON;
messages[1] = COMMAND_GROUP_3_WHITE;
break;
case 4:
messages[0] = COMMAND_GROUP_4_ON;
messages[1] = COMMAND_GROUP_4_WHITE;
break;
default:
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
// send messages
sendMultipleMessages(messages, DEFAULT_SLEEP_BETWEEN_MESSAGES);
}
/**
* Trigger the disco mode for the active group of lights (the last one that
* was switched on).
*
* @throws IOException
* if the message could not be sent
*/
public void discoMode() throws IOException {
sendMessage(COMMAND_DISCO);
}
public void discoMode(int group) throws IllegalArgumentException {
// create message array
int[] messages = { 0, COMMAND_DISCO };
switch (group) {
case 1:
messages[0] = COMMAND_GROUP_1_ON;
break;
case 2:
messages[0] = COMMAND_GROUP_2_ON;
break;
case 3:
messages[0] = COMMAND_GROUP_3_ON;
break;
case 4:
messages[0] = COMMAND_GROUP_4_ON;
break;
default:
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
// send messages
sendMultipleMessages(messages, DEFAULT_SLEEP_BETWEEN_MESSAGES);
}
/**
* Increase the disco mode's speed for the active group of lights (the last
* one that was switched on).
*
* @throws IOException
* if the message could not be sent
*/
public void discoModeFaster() throws IOException {
sendMessage(COMMAND_DISCO_FASTER);
}
/**
* Decrease the disco mode's speed for the active group of lights (the last
* one that was switched on).
*
* @throws IOException
* if the message could not be sent
*/
public void discoModeSlower() throws IOException {
sendMessage(COMMAND_DISCO_SLOWER);
}
public void brightness(int value) throws IOException,
IllegalArgumentException {
// check argument
if (value < 0 || value > MAX_BRIGHTNESS) {
throw new IllegalArgumentException(
"The brightness value should be between 0 and WiFiBox.MAX_BRIGHTNESS");
}
// send message to the WiFi box
sendMessage(COMMAND_BRIGHTNESS, value);
}
public void brightness(int group, int value) throws IOException,
IllegalArgumentException {
// check arguments
if (value < 0 || value > MAX_BRIGHTNESS) {
throw new IllegalArgumentException(
"The brightness value should be between 0 and WiFiBox.MAX_BRIGHTNESS");
}
// create message array
byte[][] messages = new byte[2][3];
// switch on first
switch (group) {
case 1:
messages[0] = padMessage(COMMAND_GROUP_1_ON);
break;
case 2:
messages[0] = padMessage(COMMAND_GROUP_2_ON);
break;
case 3:
messages[0] = padMessage(COMMAND_GROUP_3_ON);
break;
case 4:
messages[0] = padMessage(COMMAND_GROUP_4_ON);
break;
default:
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
// adjust brightness
messages[1] = padMessage(COMMAND_BRIGHTNESS, value);
// send messages
sendMultipleMessages(messages, DEFAULT_SLEEP_BETWEEN_MESSAGES);
}
}
|
package main;
import grid.GridGraph;
import java.util.ArrayList;
import main.analysis.TwoPoint;
import main.testgen.PathLengthClass;
import main.testgen.StandardMazes;
import main.testgen.StartEndPointData;
import main.testgen.TestDataGenerator;
import main.testgen.TestDataLibrary;
import main.utility.Utility;
import uiandio.FileIO;
import uiandio.GraphImporter;
import algorithms.AStar;
import algorithms.AStarOctileHeuristic;
import algorithms.AStarStaticMemory;
import algorithms.AcceleratedAStar;
import algorithms.Anya;
import algorithms.BasicThetaStar;
import algorithms.BreadthFirstSearch;
import algorithms.JumpPointSearch;
import algorithms.LazyThetaStar;
import algorithms.PathFindingAlgorithm;
import algorithms.RecursiveThetaStar;
import algorithms.RestrictedVisibilityGraphAlgorithm;
import algorithms.StrictVisibilityGraphAlgorithm;
import algorithms.StrictVisibilityGraphAlgorithmV2;
import algorithms.VisibilityGraphAlgorithm;
import algorithms.strictthetastar.RecursiveStrictThetaStar;
import algorithms.strictthetastar.StrictThetaStar;
public class AlgoTest {
private static FileIO io;
private static boolean writeToFile = true;
private static boolean pleaseTurnOffAssertions() {
System.out.println("Please turn off assertions during tests (Run -> Run Configurations -> Arguments -> remove -ea)");
return false;
}
public static void run() {
assert pleaseTurnOffAssertions();
//runTestAllAlgos();
AlgoFunction aStar = AStar::new;
AlgoFunction aStarStatic = AStarStaticMemory::new;
AlgoFunction aStarOctile = AStarOctileHeuristic::new;
AlgoFunction aStarOctilePS = AStarOctileHeuristic::postSmooth;
AlgoFunction bfs = BreadthFirstSearch::new;
AlgoFunction jumpPointSearch = JumpPointSearch::new;
AlgoFunction jpsPS = JumpPointSearch::postSmooth;
AlgoFunction lazyThetaStar = LazyThetaStar::new;
AlgoFunction basicThetaStar = BasicThetaStar::new;
AlgoFunction basicThetaStarPS = BasicThetaStar::postSmooth;
AlgoFunction aStarPS = AStar::postSmooth;
AlgoFunction dijkstra = AStar::dijkstra;
AlgoFunction vgaReuse = VisibilityGraphAlgorithm::graphReuse;
AlgoFunction vga = VisibilityGraphAlgorithm::new;
AlgoFunction accAStar = AcceleratedAStar::new;
AlgoFunction anya = Anya::new;
AlgoFunction rVGA = (a,b,c,d,e) -> new RestrictedVisibilityGraphAlgorithm(a,b,c,d,e);
AlgoFunction vgReuse = (a,b,c,d,e) -> VisibilityGraphAlgorithm.graphReuse(a,b,c,d,e);
AlgoFunction sVGA = (a,b,c,d,e) -> new StrictVisibilityGraphAlgorithm(a,b,c,d,e);
AlgoFunction sVGAv2 = (a,b,c,d,e) -> new StrictVisibilityGraphAlgorithmV2(a,b,c,d,e);
AlgoFunction strictThetaStar = StrictThetaStar::new;
AlgoFunction strictThetaStarPS = StrictThetaStar::postSmooth;
AlgoFunction recStrictThetaStar = RecursiveStrictThetaStar::new;
AlgoFunction recStrictThetaStarPS = RecursiveStrictThetaStar::postSmooth;
AlgoFunction recStrictThetaStar_2 = (a,b,c,d,e) -> RecursiveStrictThetaStar.depthLimit(a,b,c,d,e,2);
AlgoFunction recursiveThetaStar = RecursiveThetaStar::new;
FileIO.makeDirs("testResults/");
System.gc(); System.gc();
// float[] buffers = new float[]{0f, 0.01f,0.1f,0.2f,0.4f,0.6f,0.8f,1f,1.2f,1.5f,2f,3f,5f,8f,10f,20f,30f,50f};
// for (float buffer : buffers) {
// AlgoFunction algo = (a,b,c,d,e) -> StrictThetaStarV2e.setBuffer(a,b,c,d,e,buffer);
// testSequence(algo, "StrictThetaStarV2e_"+buffer);
// for (float buffer : buffers) {
// AlgoFunction algo = (a,b,c,d,e) -> StrictThetaStarV1.setBuffer(a,b,c,d,e,buffer);
// testSequence(algo, "StrictThetaStarV1_"+buffer);
// testSequence(aStarStatic, "AStar SLD");
// testSequence(aStarOctile, "AStar Octile");
// testSequence(bfs, "BreadthFirstSearch");
// testSequence(jumpPointSearch, "JumpPointSearch");
testSequence(basicThetaStar, "BasicThetaStar");
testSequence(basicThetaStar, "BasicThetaStar");
testSequence(basicThetaStarPS, "BasicThetaStar_PS");
// testSequence(lazyThetaStar, "LazyThetaStar");
// testSequence(accAStar, "AcceleratedAStar");
// testSequence(aStarOctilePS, "AStarOctile PostSmooth");
// testSequence(jpsPS, "JPS PostSmooth");
// testSequence(dijkstra, "Dijkstra");
// testSequence(vgaReuse, "VisibilityGraph Reuse");
// testSequence(vga, "VisibilityGraphs");
// testSequence(vga, "VISIBILITY GRAPHS PART 2");
testSequence(anya, "Anya");
testSequence(recursiveThetaStar, "RecursiveThetaStar");
testSequence(strictThetaStar, "StrictThetaStar");
testSequence(strictThetaStarPS, "StrictThetaStarPS");
testSequence(recStrictThetaStar, "RecStrictThetaStar");
testSequence(recStrictThetaStarPS, "RecStrictThetaStarPS");
testSequence(recStrictThetaStar_2, "RecStrictThetaStar_2");
// testSequence(sVGA, "StrictVisibilityGraphs");
// testSequence(sVGAv2, "StrictVisibilityGraphsV2");
// testSequence(rVGA, "RestrictedVisibilityGraphs");
// testSequence(vga, "VisibilityGraphs");
}
public static void testSequence(AlgoFunction algo, String name) {
String path = "testResults/" + name.replace(" ", "_") + ".txt";
if (writeToFile) io = new FileIO(path);
boolean pathLengthOnly = false;
boolean runningTimeOnly = true;
TestFunctionData testFunction_slow = printAverageData(20,20);
TestFunctionData testFunction_fast = printAverageData(50,30);
if (pathLengthOnly) {
//testFunction_slow = testPathLengthOnly;
//testFunction_fast = testPathLengthOnly;
testFunction_slow = analyseIndividualPaths;
testFunction_fast = analyseIndividualPaths;
}
if (runningTimeOnly) {
testFunction_slow = testIndividualRunningTimes(3,150);
testFunction_fast = testIndividualRunningTimes(3,150);
}
println("=== Testing " + name + " ===");
println("<< GAME MAPS >>");
println("sc2_steppesofwar - 164x164");// - spacious");
testOnMazeData("sc2_steppesofwar", algo, testFunction_slow);
println("sc2_losttemple - 132x131");
testOnMazeData("sc2_losttemple", algo, testFunction_slow);
println("sc2_extinction - 164x164");// - less spacious");
testOnMazeData("sc2_extinction", algo, testFunction_slow);
println("baldursgate_AR0070SR - 124x134");
testOnMazeData("baldursgate_AR0070SR", algo, testFunction_slow);
println("baldursgate_AR0705SR - 100x86");// - less spacious");
testOnMazeData("baldursgate_AR0705SR", algo, testFunction_slow);
println("baldursgate_AR0418SR - 84x75");// - spacious");
testOnMazeData("baldursgate_AR0418SR", algo, testFunction_slow);
println("sc1_TheFrozenSea - 1024x1024");
testOnMazeData("sc1_TheFrozenSea", algo, testFunction_slow);
println("sc1_SpaceDebris - 512x512");
testOnMazeData("sc1_SpaceDebris", algo, testFunction_slow);
println("wc3_icecrown - 512x512");// (spacious)");
testOnMazeData("wc3_icecrown", algo, testFunction_slow);
println("wc3_dragonfire - 512x512");// (less spacious)");
testOnMazeData("wc3_dragonfire", algo, testFunction_slow);
println("sc1_Legacy - 512x512");
testOnMazeData("sc1_Legacy", algo, testFunction_slow);
println("sc1_GreenerPastures - 768x512");
testOnMazeData("sc1_GreenerPastures", algo, testFunction_slow);
println("baldursgate_AR0603SR - 512x512");
testOnMazeData("baldursgate_AR0603SR", algo, testFunction_slow);
println("wc3_mysticisles - 512x512");
testOnMazeData("wc3_mysticisles", algo, testFunction_slow);
println("wc3_petrifiedforest - 512x512");
testOnMazeData("wc3_petrifiedforest", algo, testFunction_slow);
println("<< GENERATED MAPS >>");
// println("Low Density - 6% - 50x50");
// testOnMazeData("def_iCUZANYD_iSB_iSB_iSB", algo, testFunction_fast);
// println("Medium Density - 20% - 50x50");
// testOnMazeData("def_i10VA3PD_iSB_iSB_iP", algo, testFunction_fast);
// println("High Density - 40% - 50x50");
// testOnMazeData("def_i3ML5FBD_iSB_iSB_iH", algo, testFunction_fast);
// println("Low Density - 6% - 300x300");
// testOnMazeData("def_iHHLNUOB_iMJ_iMJ_iSB", algo, testFunction_slow);
// println("Medium Density - 20% - 300x300");
// testOnMazeData("def_iZLPIX5B_iMJ_iMJ_iP", algo, testFunction_slow);
// println("High Density - 40% - 300x300");
// testOnMazeData("def_iVVJKDR_iMJ_iMJ_iH", algo, testFunction_slow);
// println("Low Density - 6% - 500x500");
// testOnMazeData("def_iIRXXUKC_iUP_iUP_iSB", algo, testFunction_slow);
// println("Medium Density - 20% - 500x500");
// testOnMazeData("def_iOMJ14Z_iUP_iUP_iP", algo, testFunction_slow);
// println("LowDensity2 - 6% - 300x300");
// testOnMazeData("def_iMJWB0QC_iMJ_iMJ_iSB", algo, testFunction_slow);
// println("MediumDensity2 - 20% - 300x300");
// testOnMazeData("def_iBCA5SS_iMJ_iMJ_iP", algo, testFunction_slow);
// println("HighDensity2 - 40% - 300x300");
// testOnMazeData("def_i11AHREB_iMJ_iMJ_iH", algo, testFunction_slow);
// println("LowDensity3 - 6% - 300x300");
// testOnMazeData("def_iOH1TZ0D_iMJ_iMJ_iSB", algo, testFunction_slow);
// println("MediumDensity3 - 20% - 300x300");
// testOnMazeData("def_iAN3IE0C_iMJ_iMJ_iP", algo, testFunction_slow);
// println("HighDensity3 - 40% - 300x300");
// testOnMazeData("def_iI0RFKYC_iMJ_iMJ_iH", algo, testFunction_slow);
println("6%Density - 500x500");
testOnMazeData("def_iIRXXUKC_iUP_iUP_iSB", algo, testFunction_slow);
println("20%Density - 500x500");
testOnMazeData("def_iOMJ14Z_iUP_iUP_iP", algo, testFunction_slow);
println("40%Density - 500x500");
testOnMazeData("def_iREPZHKB_iUP_iUP_iH", algo, testFunction_slow);
// println("40%Density - 1000x1000");
// testOnMazeData("gen_1000x1000_7_i3WH4IJD", algo, testFunction_slow);
// println("40%Density - 2000x2000");
// testOnMazeData("gen_2000x2000_7_iXT3AEED", algo, testFunction_slow);
// println("40%Density - 3000x3000");
// testOnMazeData("gen_3000x3000_7_iSR3L1J", algo, testFunction_slow);
// println("40%Density - 4000x4000");
// testOnMazeData("gen_4000x4000_7_iNUJNZ3", algo, testFunction_slow);
// println("40%Density - 5000x5000");
// testOnMazeData("gen_5000x5000_7_iHOPN1S", algo, testFunction_slow);
println("6%Density2 - 500x500");
testOnMazeData("def_i5QEPQ2C_iUP_iUP_iSB", algo, testFunction_slow);
println("20%Density2 - 500x500");
testOnMazeData("def_iKMRKFCD_iUP_iUP_iP", algo, testFunction_slow);
println("40%Density2 - 500x500");
testOnMazeData("def_i5GM4YH_iUP_iUP_iH", algo, testFunction_slow);
println("6%Density3 - 500x500");
testOnMazeData("def_iFOLAODC_iUP_iUP_iSB", algo, testFunction_slow);
println("20%Density3 - 500x500");
testOnMazeData("def_i5GZXLUD_iUP_iUP_iP", algo, testFunction_slow);
println("40%Density3 - 500x500");
testOnMazeData("def_iA0VKRW_iUP_iUP_iH", algo, testFunction_slow);
// println("obst10_random512-10-7 - 10% - 512x512");
println("obst10_random512-10-7 - 512x512");
testOnMazeData("obst10_random512-10-7", algo, testFunction_slow);
// println("obst40_random512-40-0 - 60% - 512x512");
println("obst40_random512-40-0 - 512x512");
testOnMazeData("obst40_random512-40-0", algo, testFunction_slow);
// println("obst40_random512-40-7 - 67% - 512x512");
println("obst40_random512-40-7 - 512x512");
testOnMazeData("obst40_random512-40-7", algo, testFunction_slow);
//println("corr2_maze512-2-5 - 33% - 512x512");
println("corr2_maze512-2-5 - 512x512");
testOnMazeData("corr2_maze512-2-5", algo, testFunction_slow);
println("corr2_maze512-2-1 - 512x512");
testOnMazeData("corr2_maze512-2-1", algo, testFunction_slow);
println("corr2_maze512-2-7 - 512x512");
testOnMazeData("corr2_maze512-2-7", algo, testFunction_slow);
println("corr2_maze512-2-3 - 512x512");
testOnMazeData("corr2_maze512-2-3", algo, testFunction_slow);
println("corr2_maze512-2-9 - 512x512");
testOnMazeData("corr2_maze512-2-9", algo, testFunction_slow);
println("=== FINISHED TEST FOR " + name + " ===");
println();
if (writeToFile) io.close();
}
private static void println(Object line) {
if (writeToFile) {
io.writeLine(line.toString());
io.flush();
System.out.println(line);
} else {
System.out.println(line);
}
}
private static void println() {
println("");
}
public static ArrayList<TwoPoint> toTwoPointlist(int...points) {
return TestDataGenerator.generateTwoPointList(points);
}
public static void testOnMaze(String mazeName, AlgoFunction algoFunction, TestFunction test) {
ArrayList<TwoPoint> problems = GraphImporter.loadStoredMazeProblems(mazeName);
testOnMaze(mazeName, problems, algoFunction, test);
}
public static void testOnMaze(String mazeName, ArrayList<TwoPoint> problems, AlgoFunction algoFunction, TestFunction test) {
GridGraph gridGraph = GraphImporter.loadStoredMaze(mazeName);
test.test(mazeName, gridGraph, problems, algoFunction);
}
public static void testOnGraph(GridGraph gridGraph, ArrayList<TwoPoint> problems, AlgoFunction algoFunction, TestFunction test) {
test.test("undefined", gridGraph, problems, algoFunction);
}
public static void testOnMazeData(String mazeName, AlgoFunction algoFunction, TestFunctionData test) {
ArrayList<StartEndPointData> problems = GraphImporter.loadStoredMazeProblemData(mazeName);
testOnMazeData(mazeName, problems, algoFunction, test);
}
public static void testOnMazeData(String mazeName, ArrayList<StartEndPointData> problems, AlgoFunction algoFunction, TestFunctionData test) {
GridGraph gridGraph = GraphImporter.loadStoredMaze(mazeName);
problems = Utility.fixProblemPathLength(gridGraph, problems);
test.test(mazeName, gridGraph, problems, algoFunction);
}
public static void testOnGraphData(GridGraph gridGraph, ArrayList<StartEndPointData> problems, AlgoFunction algoFunction, TestFunctionData test) {
test.test("undefined", gridGraph, problems, algoFunction);
}
private static final TestFunctionData testPathLengthOnly = (mazeName, gridGraph, problems, algoFunction) -> {
TestResult[] testResults = new TestResult[problems.size()];
int index = 0;
double totalPathLength = 0;
int totalTautPaths = 0;
int totalOptimalPaths = 0;
for (StartEndPointData problem : problems) {
TwoPoint tp = new TwoPoint(problem.start, problem.end);
testResults[index] = testAlgorithmPathLength(gridGraph, algoFunction, tp);
totalPathLength += testResults[index].pathLength / problem.shortestPath;
totalTautPaths += (testResults[index].isTaut?1:0);
totalOptimalPaths += (Utility.isOptimal(testResults[index].pathLength, problem.shortestPath)?1:0);
index++;
}
int nResults = testResults.length;
println("Average Path Length: " + (totalPathLength/nResults));
println("Percentage Taut: " + (totalTautPaths/(float)nResults));
println("Percentage Optimal: " + (totalOptimalPaths/(float)nResults));
};
private static final TestFunctionData analyseIndividualPaths = (mazeName, gridGraph, problems, algoFunction) -> {
println("|||||mazeName,start,end,optimalLength,actualLength,isTaut,isOptimal");
for (StartEndPointData problem : problems) {
TwoPoint tp = new TwoPoint(problem.start, problem.end);
TestResult testResult = testAlgorithmPathLength(gridGraph, algoFunction, tp);
//double pathLengthRatio = testResult.pathLength / problem.shortestPath;
int isTaut = (testResult.isTaut?1:0);
int isOptimal = (Utility.isOptimal(testResult.pathLength, problem.shortestPath)?1:0);
StringBuilder sb = new StringBuilder(">>>>>");
sb.append(mazeName).append(",");
sb.append(problem.start).append(",");
sb.append(problem.end).append(",");
sb.append(problem.shortestPath).append(",");
sb.append(testResult.pathLength).append(",");
sb.append(isTaut).append(",");
sb.append(isOptimal);
println(sb.toString());
}
};
private static final TestFunction printAverage = (mazeName, gridGraph, problems, algoFunction) -> {
int sampleSize = 10;
int nTrials = 5;
TestResult[] testResults = new TestResult[problems.size()];
int index = 0;
for (TwoPoint problem : problems) {
testResults[index] = testAlgorithm(gridGraph, algoFunction, problem, sampleSize, nTrials);
index++;
}
double totalMean = 0;
double totalSD = 0;
double totalPathLength = 0;
int totalTautPaths = 0;
for (TestResult testResult : testResults) {
totalMean += testResult.time;
totalSD += testResult.timeSD;
totalPathLength += testResult.pathLength;
totalTautPaths += (testResult.isTaut?1:0);
}
int nResults = testResults.length;
println("Sample Size: " + sampleSize + " x " + nTrials + " trials");
println("Average Time: " + (totalMean/nResults));
println("Average SD: " + (totalSD/nResults));
println("Average Path Length: " + (totalPathLength/nResults));
println("Percentage Taut: " + (totalTautPaths/(float)nResults));
};
private static final TestFunctionData printAverageData(int sampleSize, int nTrials) {
return (mazeName, gridGraph, problems, algoFunction) -> {
double sum = 0;
double sumSquare = 0;
double totalPathLength = 0;
int totalTautPaths = 0;
int totalOptimalPaths = 0;
int nResults = 0;
for (StartEndPointData problem : problems) {
TwoPoint tp = new TwoPoint(problem.start, problem.end);
TestResult testResult = testAlgorithm(gridGraph, algoFunction, tp, sampleSize, nTrials);
sum += testResult.time;
sumSquare += testResult.time*testResult.time;
totalPathLength += testResult.pathLength / problem.shortestPath;
totalTautPaths += (testResult.isTaut?1:0);
totalOptimalPaths += (Utility.isOptimal(testResult.pathLength, problem.shortestPath)?1:0);
nResults++;
}
double mean = (double)sum / nResults;
double secondMomentTimesN = (double)sumSquare;
double sampleVariance = (secondMomentTimesN - nResults*(mean*mean)) / (nResults - 1);
double standardDeviation = Math.sqrt(sampleVariance);
println("Sample Size: " + sampleSize + " x " + nTrials + " trials");
println("Average Time: " + mean);
println("Standard Dev: " + standardDeviation);
println("Average Path Length: " + (totalPathLength/nResults));
println("Percentage Taut: " + (totalTautPaths/(float)nResults));
println("Percentage Optimal: " + (totalOptimalPaths/(float)nResults));
//StrictVisibilityGraphAlgorithmV2.printTimes();a=true;
println();
};
}
private static final TestFunctionData testIndividualRunningTimes(int sampleSize, int nTrials) {
return (mazeName, gridGraph, problems, algoFunction) -> {
ArrayList<TwoPoint> twoPointList = new ArrayList<>();
ArrayList<long[]> runningTimesList = new ArrayList<>();
for (StartEndPointData problem : problems) {
TwoPoint tp = new TwoPoint(problem.start, problem.end);
long[] runningTimes = new long[sampleSize];
// Do two blank runs first to increase consistency of results.
testAlgorithmTimeOnce(gridGraph, algoFunction, tp, 2);
for (int i=0;i<sampleSize;++i) {
runningTimes[i] = testAlgorithmTimeOnce(gridGraph, algoFunction, tp, nTrials);
}
twoPointList.add(tp);
runningTimesList.add(runningTimes);
//println(tp + " " + Arrays.toString(runningTimes));
}
println("Maze Name: " + mazeName);
println("Sample Size: " + sampleSize + " x " + nTrials + " trials");
for (int i=0;i<twoPointList.size();++i) {
TwoPoint tp = twoPointList.get(i);
long[] runningTimes = runningTimesList.get(i);
StringBuilder sb = new StringBuilder();
sb.append(tp.p1.x + "-" + tp.p1.y + "_" + tp.p2.x + "-" + tp.p2.y);
for (long runningTime : runningTimes) {
sb.append(" ");
sb.append(runningTime);
}
println(sb);
}
println();
};
}
private static long testAlgorithmTimeOnce(GridGraph gridGraph,
AlgoFunction algoFunction, TwoPoint tp, int nTrials) {
int startX = tp.p1.x;
int startY = tp.p1.y;
int endX = tp.p2.x;
int endY = tp.p2.y;
long start = System.nanoTime();
for (int i=0;i<nTrials;i++) {
AlgoTest.testAlgorithmSpeed(algoFunction, gridGraph, startX, startY, endX, endY);
}
long end = System.nanoTime();
long timeTakenNanosecs = end - start;
//System.out.println(timeTakenNanosecs);
return timeTakenNanosecs;
}
private static TestResult testAlgorithmTime(GridGraph gridGraph,
AlgoFunction algoFunction, TwoPoint tp, int sampleSize, int nTrials) {
double[] data = new double[sampleSize];
double sum = 0;
double sumSquare = 0;
int startX = tp.p1.x;
int startY = tp.p1.y;
int endX = tp.p2.x;
int endY = tp.p2.y;
for (int s = 0; s < sampleSize; s++) {
long start = System.nanoTime();
for (int i=0;i<nTrials;i++) {
AlgoTest.testAlgorithmSpeed(algoFunction, gridGraph, startX, startY, endX, endY);
}
long end = System.nanoTime();
//System.gc();
data[s] = (double)(end-start)/1000000.;
sum += data[s];
sumSquare += data[s]*data[s];
}
double mean = (double)sum / nTrials / sampleSize;
double secondMomentTimesN = (double)sumSquare / nTrials / nTrials;
double sampleVariance = (secondMomentTimesN - sampleSize*(mean*mean)) / (sampleSize - 1);
double standardDeviation = Math.sqrt(sampleVariance);
TestResult testResult = new TestResult(sampleSize, mean, standardDeviation, -1f, false);
return testResult;
}
private static TestResult testAlgorithmPathLength(GridGraph gridGraph,
AlgoFunction algoFunction, TwoPoint tp) {
int[][] path = Utility.generatePath(algoFunction, gridGraph,
tp.p1.x, tp.p1.y, tp.p2.x, tp.p2.y);
double pathLength = Utility.computePathLength(gridGraph, path);
boolean isTaut = Utility.isPathTaut(gridGraph, path);
TestResult testResult = new TestResult(-1, -1, -1, pathLength, isTaut);
return testResult;
}
private static TestResult testAlgorithm(GridGraph gridGraph,
AlgoFunction algoFunction, TwoPoint tp, int sampleSize, int nTrials) {
TestResult pathLength = testAlgorithmPathLength(gridGraph,algoFunction,tp);
TestResult time = testAlgorithmTime(gridGraph,algoFunction,tp,sampleSize,nTrials);
return new TestResult(time.timesRan, time.time, time.timeSD, pathLength.pathLength, pathLength.isTaut);
}
/**
* Run tests for all the algorithms, and outputs them to the file.<br>
* Please look into this method for more information.<br>
* Comment out the algorithms you don't want to test.
* EDIT: No longer used. Replaced by run() as the main testing method.
*/
@Deprecated
private static void runTestAllAlgos() {
/*AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new AStar(gridGraph, sx, sy, ex, ey);
runTests("AStar_TI");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new BreadthFirstSearch(gridGraph, sx, sy, ex, ey);
runTests("BFS");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> BreadthFirstSearch.postSmooth(gridGraph, sx, sy, ex, ey);
runTests("BFS-PS");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> AStar.postSmooth(gridGraph, sx, sy, ex, ey);
runTests("AStar-PS_TI");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> AStar.dijkstra(gridGraph, sx, sy, ex, ey);
runTests("Dijkstra");
// Warning: Anya is unstable
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new Anya(gridGraph, sx, sy, ex, ey);
runTests("Anya");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new BasicThetaStar(gridGraph, sx, sy, ex, ey);
runTests("BasicThetaStar_TI");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> BasicThetaStar.postSmooth(gridGraph, sx, sy, ex, ey);
runTests("BasicThetaStar-PS_TI");
Warning: VisibilityGraph is slow
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new VisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey);
runTests("VisibilityGraph");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> VisibilityGraphAlgorithm.graphReuse(gridGraph, sx, sy, ex, ey);
runTests("VisibilityGraph_REUSE");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> VisibilityGraphAlgorithm.graphReuseSlowDijkstra(gridGraph, sx, sy, ex, ey);
runTests("VisibilityGraph_REUSE_SLOWDIJKSTRA");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> new StrictThetaStar(gridGraph, sx, sy, ex, ey);
runTests("StrictThetaStar_5b");
AnyAnglePathfinding.algoFunction = (gridGraph, sx, sy, ex, ey) -> StrictThetaStar.noHeuristic(gridGraph, sx, sy, ex, ey);
runTests("StrictThetaStar_NoHeuristic_5");
*/
}
/**
* Runs tests for the specified algorithm. Uses the runTest method, which
* will output the test results to the file.
* EDIT: No longer used. Replaced by run() as the main testing method.
* @param algoName The name of the algorithm to be used in the file.
*/
@Deprecated
private static void runTests(AlgoFunction algo, String algoName) {
//runTest(algoName, 4, PathLengthClass.LONGEST);
for (int i=1; i<=6; i++) {
AlgoTest.runTest(algo, algoName, i, PathLengthClass.ALL);
}
}
/**
* Runs a test stated in the TestDataLibrary, and outputs the test result to a file.
* @param algoName The name of the algorithm to be used in the file.
* @param index The index of the test to use (which maze)
* @param pathLengthClass The category of path lengths to use in the test.
* Refer to TestDataLibrary for more information.
* EDIT: No longer used. Replaced by run() as the main testing method.
*/
@Deprecated
private static void runTest(AlgoFunction algo, String algoName, int index, PathLengthClass pathLengthClass) {
String filename = algoName + "_Maze" + index + "_" + pathLengthClass.name();
System.out.println("RUNNING TEST: " + filename);
TestDataLibrary library = new StandardMazes(index, pathLengthClass);
GridGraph gridGraph = library.generateGraph();
System.out.println("Percentage Blocked:" + gridGraph.getPercentageBlocked());
FileIO fileIO = new FileIO(AnyAnglePathfinding.PATH_TESTDATA + filename + ".txt");
fileIO.writeRow("Algorithm", "Maze", "ComputedPath", "OptimalPath", "PathLengthRatio", "Time", "TimeSD", "Start", "End", "Trails");
TestResult tempRes = AlgoTest.testAlgorithm(algo, gridGraph, 0, 0, 1, 0, 1, 1);
System.out.println("Preprocess time: " + tempRes.time);
while (library.hasNextData()) {
StartEndPointData data = library.getNextData();
TestResult testResult = AlgoTest.testAlgorithm(algo, gridGraph, data.start.x,
data.start.y, data.end.x, data.end.y, 10, library.getNTrials());
boolean valid = (testResult.pathLength > 0.00001f);
double ratio = testResult.pathLength/data.shortestPath;
String algorithm = algoName;
String maze = index + "";
String pathLength = testResult.pathLength + "";
String shortestPathLength = data.shortestPath + "";
String pathLengthRatio = ratio + "";
String time = testResult.time + "";
String timeSD = testResult.timeSD + "";
String start = data.start + "";
String end = data.end + "";
String nTrials = library.getNTrials() + "";
if (!valid) {
pathLength = "N/A";
pathLengthRatio = "N/A";
}
fileIO.writeRow(algorithm, maze, pathLength, shortestPathLength, pathLengthRatio, time, timeSD, start, end, nTrials);
fileIO.flush();
}
fileIO.close();
}
/**
* Conducts a running time / path length test on the current algorithm on
* a specified gridGraph. The algorithm used is the algorithm stored in
* algoFunction.
*
* @param gridGraph the grid to run the algorithm on.
* @param startX x-coordinate of start point
* @param startY y-coordinate of start point
* @param endX x-coordinate of goal point
* @param endY y-coordinate of goal point
* @param sampleSize The size of the sample to use. Used in computing
* Standard Deviation.
* @param nTrials The number of times the algorithm is run per test. For
* example, if sampleSize is 10 and nTrials is 50, the algorithm is run 50
* times for each of the 10 tests to get 10 results. This is used for test
* cases which possbly last shorter than a millisecond, making it hard to
* record the running time of we only ran the algorithm once per record.
* @return
*/
private static TestResult testAlgorithm(AlgoFunction algoFunction, GridGraph gridGraph,
int startX, int startY, int endX, int endY, int sampleSize, int nTrials) {
int[] data = new int[sampleSize];
int sum = 0;
long sumSquare = 0;
//sampleSize = 0;// UNCOMMENT TO TEST PATH LENGTH ONLY
for (int s = 0; s < sampleSize; s++) {
long start = System.nanoTime();
for (int i=0;i<nTrials;i++) {
AlgoTest.testAlgorithmSpeed(algoFunction, gridGraph, startX, startY, endX, endY);
}
long end = System.nanoTime();
System.gc();
data[s] = (int)(end-start);
sum += data[s];
sumSquare += data[s]*data[s];
}
double mean = (double)sum / nTrials / sampleSize;
double secondMomentTimesN = (double)sumSquare / nTrials / nTrials;
double sampleVariance = (secondMomentTimesN - sampleSize*(mean*mean)) / (sampleSize - 1);
double standardDeviation = Math.sqrt(sampleVariance);
int[][] path = Utility.generatePath(algoFunction, gridGraph, startX, startY, endX, endY);
double pathLength = Utility.computePathLength(gridGraph, path);
boolean isTaut = Utility.isPathTaut(gridGraph, path);
TestResult testResult = new TestResult(sampleSize, mean, standardDeviation, pathLength, isTaut);
return testResult;
}
/**
* Tells the algorithm to compute a path. returns nothing.
* Used to test how long the algorithm takes to complete the computation.
*/
private static void testAlgorithmSpeed(AlgoFunction algoFunction, GridGraph gridGraph, int sx, int sy,
int ex, int ey) {
PathFindingAlgorithm algo = algoFunction.getAlgo(gridGraph, sx, sy, ex, ey);
algo.computePath();
}
}
class TestResult {
public final int timesRan;
public final double time;
public final double timeSD;
public final double pathLength;
public final boolean isTaut;
public TestResult(int timesRan, double time, double timeSD, double pathLength, boolean isTaut) {
this.timesRan = timesRan;
this.time = time;
this.timeSD = timeSD;
this.pathLength = pathLength;
this.isTaut = isTaut;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Times ran: " + timesRan).append("\n");
sb.append("Mean Time (ms): " + time + " (+/-" + timeSD + ")").append("\n");
sb.append("Path length: " + pathLength).append("\n");
sb.append("Is Taut: " + (isTaut?"YES":"NO")).append("\n");
return sb.toString();
}
}
interface TestFunction {
public void test(String mazeName, GridGraph gridGraph,
ArrayList<TwoPoint> problemSet, AlgoFunction algoFunction);
}
interface TestFunctionData {
public void test(String mazeName, GridGraph gridGraph,
ArrayList<StartEndPointData> problemSet, AlgoFunction algoFunction);
}
|
package aldb;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.InvalidPathException;
import asg.*;
import edu.mit.csail.sdg.alloy4.Err;
import edu.mit.csail.sdg.alloy4compiler.ast.*;
import edu.mit.csail.sdg.alloy4compiler.translator.A4Solution;
/**
* Command Line Interface using cliche.
* Must be public to work with cliche.
*/
public class Cli {
private Path modulePath;
private Module module;
Integer commandIndex;
private A4Solution solution;
Cli(final Path modulePath) throws Err {
this.modulePath = modulePath;
// TODO handle bad path, bad module
this.module = Parser.getModuleFromPath(modulePath);
if (this.module.getAllCommands().size() < 1) {
this.commandIndex = null;
this.solution = null;
} else {
this.commandIndex = 0;
this.solution = Solver.getSolution(
this.modulePath, this.module,
this.module.getAllCommands().get(this.commandIndex));
}
}
/** Evaluate an expression. */
@asg.cliche.Command
public final String print(final String expression) throws Err {
return Parser.evaluate(module, solution, expression);
}
/** Load an Alloy module at the specified path. */
@asg.cliche.Command
public final String file(final String pathString) throws Err {
Path tempModulePath;
Module tempModule;
try {
tempModulePath = Paths.get(pathString);
tempModule = Parser.getModuleFromPath(tempModulePath);
} catch (InvalidPathException e) {
return "Invalid path.";
} catch (Err e) {
return "Alloy module does not compile. Here's the error message:\n"
+ e.toString();
}
this.modulePath = tempModulePath;
this.module = tempModule;
return "";
}
/** Print currently selected Solution. */
@asg.cliche.Command
public final String printSolution() throws Err {
if (solution == null) {
return "";
} else {
return solution.toString();
}
}
/** Get the next Solution, if there is one. */
@asg.cliche.Command
public final String nextSolution() throws Err {
if (solution == null) {
return "There are no solutions.";
} else if (solution.next() == solution) {
solution = Solver.getSolution(
modulePath, module,
module.getAllCommands().get(commandIndex));
return "There are no more solutions. Using first solution.";
} else {
solution = solution.next();
return "";
}
}
/** Show selected command. */
@asg.cliche.Command
public final String printCommand() throws Err {
if (this.commandIndex == null) {
return "No command index set.";
} else {
return this.commandIndex
+ ": "
+ this.module.getAllCommands().get(this.commandIndex);
}
}
/** Set command by index. */
@asg.cliche.Command
public final String setCommand(final int commandIndex) throws Err {
if (commandIndex >= this.module.getAllCommands().size()
|| commandIndex < 0) {
return "Index out of range.";
} else {
this.commandIndex = commandIndex;
return "New command is " + printCommand();
}
}
/** List commands available for this.module. */
@asg.cliche.Command
public final String listCommands() throws Err {
// TODO what if there are no commands
StringBuilder sb = new StringBuilder();
int i = 0;
String prefix = "";
for (Command command : module.getAllCommands()) {
sb.append(prefix + i + ": " + command);
prefix = "\n";
i += 1;
}
return sb.toString();
}
}
|
package org.eclipse.epsilon.emc.cdt;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.epsilon.common.util.StringProperties;
import org.eclipse.epsilon.emc.cdt.propertygetter.CdtPropertyGetter;
import org.eclipse.epsilon.emc.cdt.propertygetter.CdtPropertySetter;
import org.eclipse.epsilon.eol.exceptions.EolRuntimeException;
import org.eclipse.epsilon.eol.exceptions.models.EolEnumerationValueNotFoundException;
import org.eclipse.epsilon.eol.exceptions.models.EolModelElementTypeNotFoundException;
import org.eclipse.epsilon.eol.exceptions.models.EolModelLoadingException;
import org.eclipse.epsilon.eol.exceptions.models.EolNotInstantiableModelElementTypeException;
import org.eclipse.epsilon.eol.execute.introspection.IPropertyGetter;
import org.eclipse.epsilon.eol.execute.introspection.IPropertySetter;
import org.eclipse.epsilon.eol.models.CachedModel;
import org.eclipse.epsilon.eol.models.IRelativePathResolver;
public class CdtModel extends CachedModel<Object>{
/** list of supported types*/
protected List<String> supportedTypes = Arrays.asList("ICElement", "ICProject");
/** denotes property projects*/
public static final String PROPERTY_PROJECT = "cproject";
/** denotes whether bindings should be resolved*/
public static final String PROPERTY_RESOLVE_BINDINGS = "resolveBindings";
/** C project*/
protected ICProject cproject = null;
/** Resolve bindings flag*/
private boolean resolveBindings = false;
/** Visitor element*/
private ReflectiveASTVisitor visitor = null;
/** Refactoring element*/
private RefactoringAST refactor = null;
/** Property getter */
protected CdtPropertyGetter propertyGetter = new CdtPropertyGetter();
/** Property setter */
protected CdtPropertySetter propertySetter = new CdtPropertySetter();
@Override
public Object getEnumerationValue(String enumeration, String label) throws EolEnumerationValueNotFoundException {
System.out.println(getClass().getSimpleName() +".getEnumerationValue(..)");
throw new UnsupportedOperationException("getEnumerationValue(..) not Implemented");
}
@Override
public String getTypeNameOf(Object instance) {
System.out.println(getClass().getSimpleName() +".getTypeNameOf(..)");
throw new UnsupportedOperationException("getTypeNameOf(..) not Implemented");
}
@Override
public Object getElementById(String id) {
System.out.println(getClass().getSimpleName() +".getElementById(..)");
throw new UnsupportedOperationException("getElementById(..) not Implemented");
}
@Override
public String getElementId(Object instance) {
System.out.println(getClass().getSimpleName() +".getElementId(..)");
throw new UnsupportedOperationException("getElementId(..) not Implemented");
}
@Override
public void setElementId(Object instance, String newId) {
System.out.println(getClass().getSimpleName() +".setElementId(..)");
throw new UnsupportedOperationException("setElementId(..) not Implemented");
}
@Override
public boolean isInstantiable(String type) {
System.out.println(getClass().getSimpleName() +".isInstantiable(..)");
throw new UnsupportedOperationException("isInstantiable(..) not Implemented");
}
@Override
public boolean hasType(String type) {
try{
// System.out.println(getClass().getSimpleName() +".hasType(..)");
return supportedTypes.contains(type)
|| (Class.forName("org.eclipse.cdt.core.dom.ast.IAST" + type) != null);
}
catch (ClassNotFoundException e) {
return false;
}
}
@Override
protected Collection<Object> allContentsFromModel() {
System.out.println(getClass().getSimpleName() +".allContentsFromModel(..)");
throw new UnsupportedOperationException("allContentsFromModel(..) not Implemented");
}
@Override
public Collection<Object> getAllOfKind(String kind) throws EolModelElementTypeNotFoundException {
// System.out.println(getClass().getSimpleName() +".getAllOfKind(..)");
return super.getAllOfKind(kind);
}
public Collection<Object> getAllOfType(String type) throws EolModelElementTypeNotFoundException {
System.out.println(getClass().getSimpleName() +".getAllOfType(..)");
return super.getAllOfType(type);
}
@Override
protected Collection<Object> getAllOfKindFromModel(String kind) throws EolModelElementTypeNotFoundException {
// System.out.println(getClass().getSimpleName() +".getAllOfKindFromModel(..)");
return getAllOfTypeFromModel(kind);
}
@Override
protected Collection<Object> getAllOfTypeFromModel(String type) throws EolModelElementTypeNotFoundException {
// System.out.println(getClass().getSimpleName() +".getAllOfTypeFromModel(..)");
return visitor.getAllofType(type);
}
@Override
protected Object createInstanceInModel(String type) throws EolModelElementTypeNotFoundException, EolNotInstantiableModelElementTypeException {
System.out.println(getClass().getSimpleName() +".createInstanceInModel(..)");
throw new UnsupportedOperationException("createInstanceInModel(..) not Implemented");
}
@Override
protected void disposeModel() {
// System.out.println(getClass().getSimpleName() +".disposeModel(..)");
cproject = null;
resolveBindings = false;
visitor = null;
refactor = null;
}
@Override
protected boolean deleteElementInModel(Object instance) throws EolRuntimeException {
System.out.println(getClass().getSimpleName() +".deleteElementInModel(..)");
throw new UnsupportedOperationException("deleteElementInModel(..) not Implemented");
}
@Override
protected Object getCacheKeyForType(String type) throws EolModelElementTypeNotFoundException {
// System.out.println(getClass().getSimpleName() +".getCacheKeyForType(..)");
return type;
}
@Override
protected Collection<String> getAllTypeNamesOf(Object instance) {
System.out.println(getClass().getSimpleName() +".getAllTypeNamesOf(..)");
throw new UnsupportedOperationException("getAllTypeNamesOf(..) not Implemented");
}
/**
* Load properties
*/
@Override
public void load(StringProperties properties, IRelativePathResolver resolver) throws EolModelLoadingException {
super.load(properties, resolver);
//get project name
String projectName = properties.getProperty(CdtModel.PROPERTY_PROJECT);
try {
cproject = CdtUtilities.getICProject(projectName);
} catch (CoreException e) {
throw new EolModelLoadingException(e, this);
}
//get resolve bindings flag
resolveBindings = Boolean.parseBoolean(properties.getProperty(PROPERTY_RESOLVE_BINDINGS));
//init visitor
visitor = new ReflectiveASTVisitor(cproject, resolveBindings);
//init refactor
refactor = new RefactoringAST(cproject, visitor.getAST());
//finally load model
load();
}
/**
* Load model
*/
@Override
protected void loadModel() throws EolModelLoadingException {
}
/**
* Check whether it is the given object is owned
*/
@Override
public boolean owns (Object object){
// System.out.println(object.getClass().getSimpleName() +"\t"+ (object instanceof IASTNode));
if ( (object instanceof ICElement) || (object instanceof IASTNode) ){
return true;
}
return false;
}
/* (non-Javadoc) not implemented
* @see org.eclipse.epsilon.eol.models.IModel#store(java.lang.String)
*/
@Override
public boolean store(String location) {
System.out.println(getClass().getSimpleName() +".store(..)");
throw new UnsupportedOperationException("store(..) not Implemented");
}
/* (non-Javadoc) not implemented
* @see org.eclipse.epsilon.eol.models.IModel#store()
*/
@Override
public boolean store() {
// System.out.println(getClass().getSimpleName() +".store()");
// refactor.addNewFunction("func");
// refactor.replaceFunction("test", "testMe");
// refactor.refactorNameSpace("tinyxml2");
refactor.refactor(new String[]{"tinyxml2.cpp", "tinyxml2.h"});
// return refactor.
// return visitor.saveAST();
return true;
}
/**
* Get property getter
*/
@Override
public IPropertyGetter getPropertyGetter() {
// System.out.println(getClass().getSimpleName() +".getPropertyGetter(..)");
return propertyGetter;
}
/**
* Get property setter
* @return
*/
@Override
public IPropertySetter getPropertySetter() {
System.out.println(getClass().getSimpleName() +".getPropertySetter(..)");
return propertySetter;
}
}
|
package org.jenetics.internal.util;
public class ArrayProxyImpl<T> extends ArrayProxy<T> {
Object[] _array;
private boolean _sealed = false;
public ArrayProxyImpl(final Object[] array, final int start, final int end) {
super(start, end);
_array = array;
}
public ArrayProxyImpl(final int length) {
this(new Object[length], 0, length);
}
@SuppressWarnings("unchecked")
@Override
public T uncheckedOffsetGet(final int absoluteIndex) {
return (T)_array[absoluteIndex];
}
@Override
public void uncheckedOffsetSet(final int absoluteIndex, final T value) {
_array[absoluteIndex] = value;
}
@Override
public ArrayProxyImpl<T> sub(final int start, final int end) {
return new ArrayProxyImpl<>(_array, start + _start, end + _start);
}
@Override
public void cloneIfSealed() {
if (_sealed) {
_array = _array.clone();
_sealed = false;
}
}
@Override
public ArrayProxyImpl<T> seal() {
_sealed = true;
return new ArrayProxyImpl<>(_array, _start, _end);
}
@Override
public ArrayProxyImpl<T> copy() {
final ArrayProxyImpl<T> proxy = new ArrayProxyImpl<>(_length);
System.arraycopy(_array, _start, proxy._array, 0, _length);
return proxy;
}
}
|
package seaweedfs.client;
// adapted from org.apache.hadoop.fs.azurebfs.services.AbfsOutputStream
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.concurrent.*;
public class SeaweedOutputStream extends OutputStream {
private static final Logger LOG = LoggerFactory.getLogger(SeaweedOutputStream.class);
protected final boolean supportFlush = true;
private final FilerClient filerClient;
private final String path;
private final int bufferSize;
private final int maxConcurrentRequestCount;
private final ThreadPoolExecutor threadExecutor;
private final ExecutorCompletionService<Void> completionService;
private final ConcurrentLinkedDeque<WriteOperation> writeOperations;
private final boolean shouldSaveMetadata = false;
private FilerProto.Entry.Builder entry;
private long position;
private boolean closed;
private volatile IOException lastError;
private long lastFlushOffset;
private long lastTotalAppendOffset = 0;
private ByteBuffer buffer;
private long outputIndex;
private String replication = "";
public SeaweedOutputStream(FilerClient filerClient, final String fullpath) {
this(filerClient, fullpath, "");
}
public SeaweedOutputStream(FilerClient filerClient, final String fullpath, final String replication) {
this(filerClient, fullpath, null, 0, 8 * 1024 * 1024, replication);
}
public SeaweedOutputStream(FilerClient filerClient, final String path, FilerProto.Entry.Builder entry,
final long position, final int bufferSize, final String replication) {
this.filerClient = filerClient;
this.replication = replication;
this.path = path;
this.position = position;
this.closed = false;
this.lastError = null;
this.lastFlushOffset = 0;
this.bufferSize = bufferSize;
this.buffer = ByteBufferPool.request(bufferSize);
this.outputIndex = 0;
this.writeOperations = new ConcurrentLinkedDeque<>();
this.maxConcurrentRequestCount = Runtime.getRuntime().availableProcessors();
this.threadExecutor
= new ThreadPoolExecutor(maxConcurrentRequestCount,
maxConcurrentRequestCount,
120L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
this.completionService = new ExecutorCompletionService<>(this.threadExecutor);
this.entry = entry;
if (this.entry == null) {
long now = System.currentTimeMillis() / 1000L;
this.entry = FilerProto.Entry.newBuilder()
.setName(getFileName(path))
.setIsDirectory(false)
.setAttributes(FilerProto.FuseAttributes.newBuilder()
.setFileMode(0755)
.setReplication(replication)
.setCrtime(now)
.setMtime(now)
.clearGroupName()
);
}
}
public static String getParentDirectory(String path) {
int protoIndex = path.indexOf(":
if (protoIndex >= 0) {
int pathStart = path.indexOf("/", protoIndex+3);
path = path.substring(pathStart);
}
if (path.equals("/")) {
return path;
}
int lastSlashIndex = path.lastIndexOf("/");
if (lastSlashIndex == 0) {
return "/";
}
return path.substring(0, lastSlashIndex);
}
public static String getFileName(String path) {
if (path.indexOf("/") < 0) {
return path;
}
int lastSlashIndex = path.lastIndexOf("/");
return path.substring(lastSlashIndex + 1);
}
private synchronized void flushWrittenBytesToServiceInternal(final long offset) throws IOException {
try {
SeaweedWrite.writeMeta(filerClient, getParentDirectory(path), entry);
} catch (Exception ex) {
throw new IOException(ex);
}
this.lastFlushOffset = offset;
}
@Override
public void write(final int byteVal) throws IOException {
write(new byte[]{(byte) (byteVal & 0xFF)});
}
@Override
public synchronized void write(final byte[] data, final int off, final int length)
throws IOException {
maybeThrowLastError();
if (data == null) {
return;
}
if (off < 0 || length < 0 || length > data.length - off) {
throw new IndexOutOfBoundsException();
}
// System.out.println(path + " write [" + (outputIndex + off) + "," + ((outputIndex + off) + length) + ")");
int currentOffset = off;
int writableBytes = bufferSize - buffer.position();
int numberOfBytesToWrite = length;
while (numberOfBytesToWrite > 0) {
if (numberOfBytesToWrite < writableBytes) {
buffer.put(data, currentOffset, numberOfBytesToWrite);
outputIndex += numberOfBytesToWrite;
break;
}
// System.out.println(path + " [" + (outputIndex + currentOffset) + "," + ((outputIndex + currentOffset) + writableBytes) + ") " + buffer.capacity());
buffer.put(data, currentOffset, writableBytes);
outputIndex += writableBytes;
currentOffset += writableBytes;
writeCurrentBufferToService();
numberOfBytesToWrite = numberOfBytesToWrite - writableBytes;
writableBytes = bufferSize - buffer.position();
}
}
/**
* Flushes this output stream and forces any buffered output bytes to be
* written out. If any data remains in the payload it is committed to the
* service. Data is queued for writing and forced out to the service
* before the call returns.
*/
@Override
public void flush() throws IOException {
if (supportFlush) {
flushInternalAsync();
}
}
/**
* Force all data in the output stream to be written to Azure storage.
* Wait to return until this is complete. Close the access to the stream and
* shutdown the upload thread pool.
* If the blob was created, its lease will be released.
* Any error encountered caught in threads and stored will be rethrown here
* after cleanup.
*/
@Override
public synchronized void close() throws IOException {
if (closed) {
return;
}
LOG.debug("close path: {}", path);
try {
flushInternal();
threadExecutor.shutdown();
} finally {
lastError = new IOException("Stream is closed!");
ByteBufferPool.release(buffer);
buffer = null;
outputIndex = 0;
closed = true;
writeOperations.clear();
if (!threadExecutor.isShutdown()) {
threadExecutor.shutdownNow();
}
}
}
private synchronized void writeCurrentBufferToService() throws IOException {
if (buffer.position() == 0) {
return;
}
position += submitWriteBufferToService(buffer, position);
buffer = ByteBufferPool.request(bufferSize);
}
private synchronized int submitWriteBufferToService(final ByteBuffer bufferToWrite, final long writePosition) throws IOException {
((Buffer)bufferToWrite).flip();
int bytesLength = bufferToWrite.limit() - bufferToWrite.position();
if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount) {
waitForTaskToComplete();
}
final Future<Void> job = completionService.submit(() -> {
// System.out.println(path + " is going to save [" + (writePosition) + "," + ((writePosition) + bytesLength) + ")");
SeaweedWrite.writeData(entry, replication, filerClient, writePosition, bufferToWrite.array(), bufferToWrite.position(), bufferToWrite.limit(), path);
// System.out.println(path + " saved [" + (writePosition) + "," + ((writePosition) + bytesLength) + ")");
ByteBufferPool.release(bufferToWrite);
return null;
});
writeOperations.add(new WriteOperation(job, writePosition, bytesLength));
// Try to shrink the queue
shrinkWriteOperationQueue();
return bytesLength;
}
private void waitForTaskToComplete() throws IOException {
boolean completed;
for (completed = false; completionService.poll() != null; completed = true) {
// keep polling until there is no data
}
if (!completed) {
try {
completionService.take();
} catch (InterruptedException e) {
lastError = (IOException) new InterruptedIOException(e.toString()).initCause(e);
throw lastError;
}
}
}
private void maybeThrowLastError() throws IOException {
if (lastError != null) {
throw lastError;
}
}
/**
* Try to remove the completed write operations from the beginning of write
* operation FIFO queue.
*/
private synchronized void shrinkWriteOperationQueue() throws IOException {
try {
while (writeOperations.peek() != null && writeOperations.peek().task.isDone()) {
writeOperations.peek().task.get();
lastTotalAppendOffset += writeOperations.peek().length;
writeOperations.remove();
}
} catch (Exception e) {
lastError = new IOException(e);
throw lastError;
}
}
protected synchronized void flushInternal() throws IOException {
maybeThrowLastError();
writeCurrentBufferToService();
flushWrittenBytesToService();
}
protected synchronized void flushInternalAsync() throws IOException {
maybeThrowLastError();
writeCurrentBufferToService();
flushWrittenBytesToServiceAsync();
}
private synchronized void flushWrittenBytesToService() throws IOException {
for (WriteOperation writeOperation : writeOperations) {
try {
writeOperation.task.get();
} catch (Exception ex) {
lastError = new IOException(ex);
throw lastError;
}
}
LOG.debug("flushWrittenBytesToService: {} position:{}", path, position);
flushWrittenBytesToServiceInternal(position);
}
private synchronized void flushWrittenBytesToServiceAsync() throws IOException {
shrinkWriteOperationQueue();
if (this.lastTotalAppendOffset > this.lastFlushOffset) {
this.flushWrittenBytesToServiceInternal(this.lastTotalAppendOffset);
}
}
private static class WriteOperation {
private final Future<Void> task;
private final long startOffset;
private final long length;
WriteOperation(final Future<Void> task, final long startOffset, final long length) {
this.task = task;
this.startOffset = startOffset;
this.length = length;
}
}
}
|
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
public class Window extends javax.swing.JFrame {
private static boolean escanear = true;
private static final float PORCENTAJE = 0.05f;
private static final long ESPERA = 3000; //ms de esperas entre escaneos en el programa.
private static DefaultTableModel model = new DefaultTableModel(); //Model donde cargare los datos e implementare.
private static Document document;
private static Elements tabla, headersWeb, datos;
private static String[] modelHeaders;
private static String[][] modelData, oldModelData;
/**
* Creates new form in
*/
public Window() {
initComponents();
this.setTitle("Informacion Relativa al Mercado.");
this.setResizable(false);
this.setLocationRelativeTo(null);
}
/**
* Limpieza de los headers para obtener solo texto y no codigo.
* @param element Element actual a tratar.
* @return String con el nombre de la cabecera limpio.
*/
private static String limpiezaHeaders(Element element) {
String header = element.toString();
header = header.substring(header.indexOf('>')+1);
header = header.substring(0, header.indexOf('<'));
return header;
}
/**
* Conversion de Elements a String[] que se puede usar directamente como headers en el JTable.mode() al instanciarlo.
* @param elements Elementos a tratar.
* @return String[] a utilizar directamente como header para table.model().
*/
private static String[] getHeaders(Elements elements) {
ArrayList<String> headersTmp = new ArrayList<>();
String[] headers;
for (int i = 0; i < elements.size()-1; i++) { //-1 para quitar lo de 'informacion relacionada'.
headersTmp.add(limpiezaHeaders(elements.get(i)));
}
headers = new String[headersTmp.size()];
for(int i = 0; i < headersTmp.size(); i++) {
headers[i] = headersTmp.get(i);
}
return headers;
}
/**
* Comprueba si queda alguna tag en al string que eliminar.
* @param string String a chequear.
* @return True si aun quedan tags por eliminar.
*/
private static boolean tagsLeft(String string) {
return string.contains("</") || string.contains(">");
}
/**
* Le quitamos una tag a la String pasada.
* @param string String sobre la que operar.
* @return String con una tag menos.
*/
private static String quitarTag(String string) {
try {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}catch(StringIndexOutOfBoundsException ex) {
string = string.substring(string.indexOf('>')+1);
}
return string;
}
/**
* Conversion de un Nodo para obtener la String que nos interesa.
* @param node Nodo del cual extraemos la informacion.
* @return String con la informacion limpia.
*/
private static String convertNode(Node node) {
String nodo = node.toString();
while(tagsLeft(nodo)) {
nodo = quitarTag(nodo);
}
return nodo;
}
/**
* Quita una etiqueta HTML de la String que se le pasa.
* @param string String a la cual se quiere quitar una etiqueta.
* @return String sin esa etiqueta.
*/
private static String quitarLayerNormal(String string) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
return string;
}
/**
* Quitado expreso de la etiqueta <img />. Hay algunos valores que no la contienen, por lo que es necesario buscarla expresamente.
* @param string String a chequear.
* @return String sin la etiqueta imagen si la contenia.
*/
private static String quitarLayerImg(String string) {
if(string.contains("<img")) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}
return string;
}
/**
* Chequea la String para comprobar si es un valor que sube o baja. Si se mantiene se marca como baja.
* @param string String a chequear.
* @return True si sube, false si no.
*/
private static boolean getTipo(String string) {
return string.contains("\"Sube\"");
}
/**
* Conversion de un element suelto a String[] para aniadirlo a la Tabla.
* Hago la conversion a mano. Son valores tan irregulares que no puedo automatizarlos.
* @param element Element a convertir.
* @return String[] convertida.
*/
private static String[] convertElement(Element element) {
String[] datos = new String[5];
try {
for(int i = 0; i < 2; i++){
datos[i] = convertNode(element.childNode(i));
}
datos[2] = convertNode(element.childNode(2).unwrap()) +"; " +convertNode(element.childNode(4)) +"h";
//No me gusta dejar esto asi pero hay demasiados cambios como para meterlos en metodos independientes, se deberia poder automatizar los recortes pero me da demasiados probremas. Ahora mismo esta manual para cada caso en concreto.
String s = quitarLayerNormal(element.childNode(5).toString());
s = quitarLayerNormal(s);
boolean sube = getTipo(s);
s = quitarLayerImg(s);
String cambioValor = s.substring(s.indexOf('>')+1, s.indexOf('>')+5);
String porcentaje = s.substring(s.lastIndexOf('>')+1).trim();
if(porcentaje.isEmpty()) porcentaje = "(0,00%)"; //Tengo problemas para capturar los 0% porque la pagina lo estructura de otra manera. Solo esta vacio cuando es 0%.
if(sube) datos[3] = "+" +cambioValor +"; " +porcentaje;
else datos[3] = "-" +cambioValor +"; " +porcentaje;
datos[4] = convertNode(element.childNode(6));
}catch(IndexOutOfBoundsException ex) {
System.out.println("ArrayIndex en convertElement(Element element) capturado: " +ex.getLocalizedMessage());
}
return datos;
}
/**
* Conversion de Elements a String[][] que usare directamente como Datos de JTable.mode().
* @param elements Elements con los datos raw.
* @return String[][] con los datos convertidos.
*/
private static String[][] getData(Elements elements) {
int size = elements.get(0).childNodeSize();
String[][] datos = new String[size][];
for(int i = 0; i < size; i++) {
datos[i] = convertElement(elements.get(0).child(i));
}
return datos;
}
/**
* Proceso de adecuacion y obtencion de datos de la web.
*/
private static void adecuacionDatos() {
modelHeaders = getHeaders(headersWeb);
if(oldModelData == null) { //Para la primera iteracion del programa.
modelData = getData(tabla);
oldModelData = modelData;
}
else {
oldModelData = modelData;
modelData = getData(tabla);
}
model = new DefaultTableModel(modelData, modelHeaders);
Window.jTable.setModel(model);
}
/**
* Get de los elementos necesarios para el parse.
*/
private static void iniElementos(String url) {
try {
document = Jsoup.connect(url).get(); //Selecciona el documento entero.
tabla = document.select("table tbody"); //De ese documento, pilla la tabla. Contiene los datos que nos interesan.
for(int i = 0; i < 4; i++) { //Eliminacion de paja que hay por enmedio, con esto lo dejo listo para tratar.
tabla.remove(tabla.get(0));
}
headersWeb = document.select("thead tr th");
datos = document.select("tr");
}catch(IOException ex) {
ex.printStackTrace();
}
}
/**
* Proceso entero de recoleccion y filtrado de los datos.
* @param url Url a la que nos conectamos.
*/
private static void tratamiento(String url) {
iniElementos(url);
adecuacionDatos();
}
/**
* Obtencion del numero limite mediante el cual si se sobrepasa habra que dar aviso al usuario.
* @param porcentaje Porcentaje establecido por el usuario para dar aviso.
* @param valor Valor el cual chequeamos.
* @return Valor limite para avisar.
*/
private static long getLimite(float porcentaje, long valor) {
return (long) (valor*porcentaje/100);
}
private static long parseLong(String string) {
String parse = "";
try {
while(string.contains(".")) {
parse += string.substring(0, string.indexOf('.'));
string = string.substring(string.indexOf('.')+1);
}
parse += string; //Para el ultimo resto y numeros sin punto.
}catch(NullPointerException ex) {
System.out.println("Problema con el parseo custom del Long. " +ex.getLocalizedMessage());
}
return Long.parseLong(parse);
}
/**
* Comprobacion de si un valor se pasa del limite establecido por el porcentaje indicado.
* @param cambio Cambio realizado entre el escaneo viejo y el actual.
* @param limite Limite del cual si se pasa hay que dar aviso.
* @return True si el cambio se pasa de, o iguala el limite.
*/
private static boolean checkLimite(long cambio, long limite) {
boolean isOver;
if(cambio >= 0) isOver = cambio >= limite;
else {
limite -= limite*2;
isOver = cambio <= limite;
}
return isOver;
}
/**
* Comparacion de los valores anteriores con los nuevos escaneados. Si hay un cambio por arriba o abajo superior al porcentaje establecido, da aviso.
* El porcentaje lo tengo en cuenta a traves del valor Viejo.
* @param datosViejos Datos del escaneo anterior para tener una base sobre la cual comparar.
* @param datosNuevos Datos del escaneo nuevo.
*/
private static void comparacion(String[][] datosViejos, String[][] datosNuevos, int comienzoHilo, int limiteHilo) {
long valorNuevo, valorViejo, cambio, cambioLimite;
for (int indiceEmpresa = comienzoHilo; indiceEmpresa < limiteHilo; indiceEmpresa++) {
valorNuevo = parseLong(datosNuevos[indiceEmpresa][4]);
valorViejo = parseLong(datosViejos[indiceEmpresa][4]);
cambioLimite = getLimite(PORCENTAJE, valorNuevo);
cambio = valorNuevo-valorViejo;
boolean over = checkLimite(cambio, cambioLimite);
if(over) System.out.printf("¡ATENCION! ¡Cambio que ha sobrepasado el limite! Empresa %S. Valor anterior: %d. Cambio de: %d. Valor actual: %d", datosNuevos[indiceEmpresa][0], valorViejo, cambio, valorNuevo);
}
// System.out.printf("Valor viejo: %d, Valor Nuevo: %d, Cambio: %d, CambioLimite: %d, Limite superado: %s\n" ,valorViejo, valorNuevo, cambio, cambioLimite, res); //Para testeo.
}
/**
* Ejecucion del escaneo en si mismo. Vuelve a obtener los datos de la pagina y compara los valores totales nuevos contra los anteriores.
* Divide la carga de trabajo en 4 hilos, aunque no hacia mucha falta ya que es poca cantidad de datos a tratar, algo de tiempo si que gana.
* @param url url sobre la que esta operando el programa.
*/
private synchronized static void escanear(String url) {
escanear = true;
while(escanear) {
try {
tratamiento(url);
System.out.println("Escaneo realizado sobre: " +url);
new Thread(() -> comparacion(oldModelData, modelData, 0, 25)).start();
new Thread(() -> comparacion(oldModelData, modelData, 25, 50)).start();
new Thread(() -> comparacion(oldModelData, modelData, 50, 75)).start();
new Thread(() -> comparacion(oldModelData, modelData, 75, 100)).start();
Thread.sleep(ESPERA);
} catch (InterruptedException ex) {
System.out.println("Problema con Thread.sleep en escanear(String url). " +ex.getLocalizedMessage());
}
if(!escanear) System.out.println("Escaneo sobre :" +url +" parado.");
}
}
/**
* Cambio de la fuente de datos junto a la Label que informa al usuario.
* @param url URL de donde sacar los datos.
*/
private static void cambioDatos(String url) {
escanear = false;
tratamiento(url);
switch(url) {
case "https://es.finance.yahoo.com/actives?e=mc":
Window.jLabelTitulo.setText("Valores mas Activos");
break;
case "https://es.finance.yahoo.com/gainers?e=mc":
Window.jLabelTitulo.setText("Mayores Subidas de Precio");
break;
case "https://es.finance.yahoo.com/losers?e=mc":
Window.jLabelTitulo.setText("Bajan de Precio");
break;
default:
break;
}
Runnable r = () -> escanear(url);
new Thread(r).start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupDatos = new javax.swing.ButtonGroup();
jLabelTitulo = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
jMenuBar1 = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuValores = new javax.swing.JMenu();
jRadioButtonMenuItemActivos = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemSubidas = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemBajadas = new javax.swing.JRadioButtonMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabelTitulo.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
jLabelTitulo.setText("Valores mas Activos");
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTable.setShowHorizontalLines(true);
jScrollPane1.setViewportView(jTable);
jMenuFile.setText("File");
jMenuItem1.setText("Salir");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenuFile.add(jMenuItem1);
jMenuBar1.add(jMenuFile);
jMenuValores.setText("Valores");
buttonGroupDatos.add(jRadioButtonMenuItemActivos);
jRadioButtonMenuItemActivos.setSelected(true);
jRadioButtonMenuItemActivos.setText("Valores mas Activos");
jRadioButtonMenuItemActivos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemActivosActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemActivos);
buttonGroupDatos.add(jRadioButtonMenuItemSubidas);
jRadioButtonMenuItemSubidas.setText("Mayores Subidas de Precio");
jRadioButtonMenuItemSubidas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemSubidasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemSubidas);
buttonGroupDatos.add(jRadioButtonMenuItemBajadas);
jRadioButtonMenuItemBajadas.setText("Bajan de Precio");
jRadioButtonMenuItemBajadas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemBajadasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemBajadas);
jMenuBar1.add(jMenuValores);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelTitulo)
.addGap(217, 217, 217))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabelTitulo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jRadioButtonMenuItemActivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemActivosActionPerformed
cambioDatos("https://es.finance.yahoo.com/actives?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemActivosActionPerformed
private void jRadioButtonMenuItemSubidasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemSubidasActionPerformed
cambioDatos("https://es.finance.yahoo.com/gainers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemSubidasActionPerformed
private void jRadioButtonMenuItemBajadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBajadasActionPerformed
cambioDatos("https://es.finance.yahoo.com/losers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemBajadasActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
tratamiento("https://es.finance.yahoo.com/actives?e=mc");
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDatos;
private static javax.swing.JLabel jLabelTitulo;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenu jMenuValores;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemActivos;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBajadas;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemSubidas;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTable jTable;
// End of variables declaration//GEN-END:variables
}
|
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.CodeCompletionFeatures;
import com.intellij.codeInsight.completion.ShowHideIntentionIconLookupAction;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementAction;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.ui.UISettings;
import com.intellij.idea.ActionsBundle;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.ActionButton;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.ComponentUtil;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.Alarm;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.AbstractLayoutManager;
import com.intellij.util.ui.AsyncProcessIcon;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Collection;
/**
* @author peter
*/
class LookupUi {
private static final Logger LOG = Logger.getInstance(LookupUi.class);
@NotNull
private final LookupImpl myLookup;
private final Advertiser myAdvertiser;
private final JBList myList;
private final ModalityState myModalityState;
private final Alarm myHintAlarm = new Alarm();
private final JScrollPane myScrollPane;
private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
private final ActionButton myMenuButton;
private final ActionButton myHintButton;
private final JComponent myBottomPanel;
private int myMaximumHeight = Integer.MAX_VALUE;
private Boolean myPositionedAbove = null;
LookupUi(@NotNull LookupImpl lookup, Advertiser advertiser, JBList list) {
myLookup = lookup;
myAdvertiser = advertiser;
myList = list;
myProcessIcon.setVisible(false);
myLookup.resort(false);
MenuAction menuAction = new MenuAction();
menuAction.add(new ChangeSortingAction());
menuAction.add(new DelegatedAction(ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_JAVADOC)){
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setVisible(!CodeInsightSettings.getInstance().AUTO_POPUP_JAVADOC_INFO);
}
});
menuAction.add(new DelegatedAction(ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_IMPLEMENTATIONS)));
Presentation presentation = new Presentation();
presentation.setIcon(AllIcons.Actions.More);
presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, Boolean.TRUE);
myMenuButton = new ActionButton(menuAction, presentation, ActionPlaces.EDITOR_POPUP, ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE);
AnAction hintAction = new HintAction();
myHintButton = new ActionButton(hintAction, hintAction.getTemplatePresentation(),
ActionPlaces.EDITOR_POPUP, ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE);
myHintButton.setVisible(false);
myBottomPanel = new NonOpaquePanel(new LookupBottomLayout());
myBottomPanel.add(myAdvertiser.getAdComponent());
myBottomPanel.add(myProcessIcon);
myBottomPanel.add(myHintButton);
myBottomPanel.add(myMenuButton);
LookupLayeredPane layeredPane = new LookupLayeredPane();
layeredPane.mainPanel.add(myBottomPanel, BorderLayout.SOUTH);
myScrollPane = ScrollPaneFactory.createScrollPane(lookup.getList(), true);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
ComponentUtil.putClientProperty(myScrollPane.getVerticalScrollBar(), JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true);
lookup.getComponent().add(layeredPane, BorderLayout.CENTER);
layeredPane.mainPanel.add(myScrollPane, BorderLayout.CENTER);
myModalityState = ModalityState.stateForComponent(lookup.getTopLevelEditor().getComponent());
addListeners();
Disposer.register(lookup, myProcessIcon);
Disposer.register(lookup, myHintAlarm);
}
private void addListeners() {
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (myLookup.isLookupDisposed()) return;
myHintAlarm.cancelAllRequests();
updateHint();
}
});
}
private void updateHint() {
myLookup.checkValid();
if (myHintButton.isVisible()) {
myHintButton.setVisible(false);
}
LookupElement item = myLookup.getCurrentItem();
if (item != null && item.isValid()) {
Collection<LookupElementAction> actions = myLookup.getActionsFor(item);
if (!actions.isEmpty()) {
myHintAlarm.addRequest(() -> {
if (ShowHideIntentionIconLookupAction.shouldShowLookupHint() &&
!((CompletionExtender)myList.getExpandableItemsHandler()).isShowing() &&
!myProcessIcon.isVisible()) {
myHintButton.setVisible(true);
}
}, 500, myModalityState);
}
}
}
void setCalculating(boolean calculating) {
Runnable iconUpdater = () -> {
if (calculating && myHintButton.isVisible()) {
myHintButton.setVisible(false);
}
myProcessIcon.setVisible(calculating);
ApplicationManager.getApplication().invokeLater(() -> {
if (!calculating && !myLookup.isLookupDisposed()) {
updateHint();
}
}, myModalityState);
};
if (calculating) {
myProcessIcon.resume();
} else {
myProcessIcon.suspend();
}
new Alarm(myLookup).addRequest(iconUpdater, 100, myModalityState);
}
void refreshUi(boolean selectionVisible, boolean itemsChanged, boolean reused, boolean onExplicitAction) {
Editor editor = myLookup.getTopLevelEditor();
if (editor.getComponent().getRootPane() == null || editor instanceof EditorWindow && !((EditorWindow)editor).isValid()) {
return;
}
if (myLookup.myResizePending || itemsChanged) {
myMaximumHeight = Integer.MAX_VALUE;
}
Rectangle rectangle = calculatePosition();
myMaximumHeight = rectangle.height;
if (myLookup.myResizePending || itemsChanged) {
myLookup.myResizePending = false;
myLookup.pack();
rectangle = calculatePosition();
}
HintManagerImpl.updateLocation(myLookup, editor, rectangle.getLocation());
if (reused || selectionVisible || onExplicitAction) {
myLookup.ensureSelectionVisible(false);
}
}
boolean isPositionedAboveCaret() {
return myPositionedAbove != null && myPositionedAbove.booleanValue();
}
// in layered pane coordinate system.
Rectangle calculatePosition() {
final JComponent lookupComponent = myLookup.getComponent();
Dimension dim = lookupComponent.getPreferredSize();
int lookupStart = myLookup.getLookupStart();
Editor editor = myLookup.getTopLevelEditor();
if (lookupStart < 0 || lookupStart > editor.getDocument().getTextLength()) {
LOG.error(lookupStart + "; offset=" + editor.getCaretModel().getOffset() + "; element=" +
myLookup.getPsiElement());
}
LogicalPosition pos = editor.offsetToLogicalPosition(lookupStart);
Point location = editor.logicalPositionToXY(pos);
location.y += editor.getLineHeight();
location.x -= myLookup.myCellRenderer.getTextIndent();
// extra check for other borders
final Window window = ComponentUtil.getWindow(lookupComponent);
if (window != null) {
final Point point = SwingUtilities.convertPoint(lookupComponent, 0, 0, window);
location.x -= point.x;
}
SwingUtilities.convertPointToScreen(location, editor.getContentComponent());
final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(editor.getContentComponent());
if (!isPositionedAboveCaret()) {
int shiftLow = screenRectangle.y + screenRectangle.height - (location.y + dim.height);
myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height && location.y >= dim.height;
}
if (isPositionedAboveCaret()) {
location.y -= dim.height + editor.getLineHeight();
}
if (!screenRectangle.contains(location)) {
location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
}
Rectangle candidate = new Rectangle(location, dim);
ScreenUtil.cropRectangleToFitTheScreen(candidate);
if (isPositionedAboveCaret()) {
// need to crop as well at bottom if lookup overlaps current line
Point caretLocation = editor.logicalPositionToXY(pos);
SwingUtilities.convertPointToScreen(caretLocation, editor.getContentComponent());
int offset = location.y + dim.height - caretLocation.y;
if (offset > 0) {
candidate.height -= offset;
}
}
JRootPane rootPane = editor.getComponent().getRootPane();
if (rootPane != null) {
SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
}
else {
LOG.error("editor.disposed=" + editor.isDisposed() + "; lookup.disposed=" + myLookup.isLookupDisposed() + "; editorShowing=" + editor.getContentComponent().isShowing());
}
myMaximumHeight = candidate.height;
return new Rectangle(location.x, location.y, dim.width, candidate.height);
}
private class LookupLayeredPane extends JBLayeredPane {
final JPanel mainPanel = new JPanel(new BorderLayout());
private LookupLayeredPane() {
mainPanel.setBackground(LookupCellRenderer.BACKGROUND_COLOR);
add(mainPanel, 0, 0);
setLayout(new AbstractLayoutManager() {
@Override
public Dimension preferredLayoutSize(@Nullable Container parent) {
int maxCellWidth = myLookup.myCellRenderer.getLookupTextWidth() + myLookup.myCellRenderer.getTextIndent();
int scrollBarWidth = myScrollPane.getVerticalScrollBar().getWidth();
int listWidth = Math.min(scrollBarWidth + maxCellWidth, UISettings.getInstance().getMaxLookupWidth());
Dimension bottomPanelSize = myBottomPanel.getPreferredSize();
int panelHeight = myScrollPane.getPreferredSize().height + bottomPanelSize.height;
int width = Math.max(listWidth, bottomPanelSize.width);
width = Math.min(width, Registry.intValue("ide.completion.max.width"));
int height = Math.min(panelHeight, myMaximumHeight);
return new Dimension(width, height);
}
@Override
public void layoutContainer(Container parent) {
Dimension size = getSize();
mainPanel.setSize(size);
mainPanel.validate();
if (IdeEventQueue.getInstance().getTrueCurrentEvent().getID() == MouseEvent.MOUSE_DRAGGED) {
Dimension preferredSize = preferredLayoutSize(null);
if (preferredSize.width != size.width) {
UISettings.getInstance().setMaxLookupWidth(Math.max(500, size.width));
}
int listHeight = myList.getLastVisibleIndex() - myList.getFirstVisibleIndex() + 1;
if (listHeight != myList.getModel().getSize() && listHeight != myList.getVisibleRowCount() && preferredSize.height != size.height) {
UISettings.getInstance().setMaxLookupListHeight(Math.max(5, listHeight));
}
}
myList.setFixedCellWidth(myScrollPane.getViewport().getWidth());
}
});
}
}
private class HintAction extends DumbAwareAction {
private HintAction() {
super(AllIcons.Actions.IntentionBulb);
AnAction showIntentionAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (showIntentionAction != null) {
copyShortcutFrom(showIntentionAction);
getTemplatePresentation().setText(CodeInsightBundle.messagePointer("action.presentation.LookupUi.text"));
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myLookup.showElementActions(e.getInputEvent());
}
}
private static class MenuAction extends DefaultActionGroup implements HintManagerImpl.ActionToIgnore {
private MenuAction() {
setPopup(true);
}
}
private class ChangeSortingAction extends DumbAwareAction implements HintManagerImpl.ActionToIgnore {
private boolean sortByName = UISettings.getInstance().getSortLookupElementsLexicographically();
private ChangeSortingAction() {
super(ActionsBundle.messagePointer("action.ChangeSortingAction.text"));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (e.getPlace() == ActionPlaces.EDITOR_POPUP) {
sortByName = !sortByName;
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CHANGE_SORTING);
UISettings.getInstance().setSortLookupElementsLexicographically(sortByName);
myLookup.resort(false);
}
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setIcon(sortByName ? PlatformIcons.CHECK_ICON : null);
}
}
private static class DelegatedAction extends DumbAwareAction implements HintManagerImpl.ActionToIgnore {
private final AnAction delegateAction;
private DelegatedAction(AnAction action) {
delegateAction = action;
getTemplatePresentation().setText(delegateAction.getTemplateText(), true);
copyShortcutFrom(delegateAction);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (e.getPlace() == ActionPlaces.EDITOR_POPUP) {
delegateAction.actionPerformed(e);
}
}
}
private class LookupBottomLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {}
@Override
public void removeLayoutComponent(Component comp) {}
@Override
public Dimension preferredLayoutSize(Container parent) {
Dimension adSize = myAdvertiser.getAdComponent().getPreferredSize();
Dimension hintButtonSize = myHintButton.getPreferredSize();
Dimension menuButtonSize = myMenuButton.getPreferredSize();
return new Dimension(adSize.width + hintButtonSize.width + menuButtonSize.width,
Math.max(adSize.height, menuButtonSize.height));
}
@Override
public Dimension minimumLayoutSize(Container parent) {
Dimension adSize = myAdvertiser.getAdComponent().getMinimumSize();
Dimension hintButtonSize = myHintButton.getMinimumSize();
Dimension menuButtonSize = myMenuButton.getMinimumSize();
return new Dimension(adSize.width + hintButtonSize.width + menuButtonSize.width,
Math.max(adSize.height, menuButtonSize.height));
}
@Override
public void layoutContainer(Container parent) {
Dimension size = parent.getSize();
Dimension menuButtonSize = myMenuButton.getPreferredSize();
int x = size.width - menuButtonSize.width;
int y = (size.height - menuButtonSize.height) / 2;
myMenuButton.setBounds(x, y, menuButtonSize.width, menuButtonSize.height);
Dimension myHintButtonSize = myHintButton.getPreferredSize();
if (myHintButton.isVisible() && !myProcessIcon.isVisible()) {
x -= myHintButtonSize.width;
y = (size.height - myHintButtonSize.height) / 2;
myHintButton.setBounds(x, y, myHintButtonSize.width, myHintButtonSize.height);
}
else if (!myHintButton.isVisible() && myProcessIcon.isVisible()) {
Dimension myProcessIconSize = myProcessIcon.getPreferredSize();
x -= myProcessIconSize.width;
y = (size.height - myProcessIconSize.height) / 2;
myProcessIcon.setBounds(x, y, myProcessIconSize.width, myProcessIconSize.height);
}
else if (!myHintButton.isVisible() && !myProcessIcon.isVisible()) {
x -= myHintButtonSize.width;
}
else {
throw new IllegalStateException("Can't show both process icon and hint button");
}
Dimension adSize = myAdvertiser.getAdComponent().getPreferredSize();
y = (size.height - adSize.height) / 2;
myAdvertiser.getAdComponent().setBounds(0, y, x, adSize.height);
}
}
}
|
package com.intellij.indentation;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class AbstractIndentParser implements PsiParser {
private PsiBuilder myBuilder;
private int myCurrentIndent;
private HashMap<PsiBuilder.Marker, Integer> myIndents;
private HashMap<PsiBuilder.Marker, Boolean> myNewLines;
private boolean myNewLine = true;
@NotNull
public ASTNode parse(IElementType root, PsiBuilder builder) {
myNewLines = new HashMap<PsiBuilder.Marker, Boolean>();
myIndents = new HashMap<PsiBuilder.Marker, Integer>();
myBuilder = builder;
parseRoot(root);
return myBuilder.getTreeBuilt();
}
protected abstract void parseRoot(IElementType root);
public PsiBuilder.Marker mark(boolean couldBeRolledBack) {
final PsiBuilder.Marker marker = myBuilder.mark();
if (couldBeRolledBack) {
myIndents.put(marker, myCurrentIndent);
myNewLines.put(marker, myNewLine);
}
return marker;
}
public PsiBuilder.Marker mark() {
return mark(false);
}
public void done(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
myIndents.remove(marker);
myNewLines.remove(marker);
marker.done(elementType);
}
public static void collapse(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
marker.collapse(elementType);
}
protected static void drop(@NotNull final PsiBuilder.Marker marker) {
marker.drop();
}
protected void rollbackTo(@NotNull final PsiBuilder.Marker marker) {
if (myIndents.get(marker) == null) {
throw new RuntimeException("Parser can't rollback marker that was created by mark() method, use mark(true) instead");
}
myCurrentIndent = myIndents.get(marker);
myNewLine = myNewLines.get(marker);
myIndents.remove(marker);
myNewLines.remove(marker);
marker.rollbackTo();
}
protected boolean eof() {
return myBuilder.eof();
}
protected int getCurrentOffset() {
return myBuilder.getCurrentOffset();
}
public int getCurrentIndent() {
return myCurrentIndent;
}
protected void error(String message) {
myBuilder.error(message);
}
@Nullable
public IElementType getTokenType() {
return myBuilder.getTokenType();
}
protected static boolean tokenIn(@Nullable final IElementType elementType, IElementType... tokens) {
for (IElementType token : tokens) {
if (elementType == token) {
return true;
}
}
return false;
}
protected boolean currentTokenIn(IElementType... tokens) {
return tokenIn(getTokenType(), tokens);
}
protected boolean currentTokenIn(@NotNull final TokenSet tokenSet) {
return tokenSet.contains(getTokenType());
}
protected static boolean tokenIn(@Nullable final IElementType elementType, @NotNull final TokenSet tokenSet) {
return tokenIn(elementType, tokenSet.getTypes());
}
@NotNull
protected String getTokenText() {
String result = myBuilder.getTokenText();
if (result == null) {
result = "";
}
return result;
}
protected boolean expect(@NotNull final IElementType elementType) {
return expect(elementType, "Expected: " + elementType);
}
protected boolean expect(@NotNull final IElementType elementType, String expectedMessage) {
if (getTokenType() == elementType) {
advance();
return true;
}
error(expectedMessage);
return false;
}
@Nullable
public IElementType lookAhead(int step) {
return myBuilder.lookAhead(step);
}
@Nullable
public IElementType rawLookup(int step) {
return myBuilder.rawLookup(step);
}
public boolean isNewLine() {
return myNewLine;
}
public void advance() {
final String tokenText = myBuilder.getTokenText();
final int tokenLength = tokenText == null ? 0 : tokenText.length();
final int whiteSpaceStart = getCurrentOffset() + tokenLength;
myBuilder.advanceLexer();
final int whiteSpaceEnd = getCurrentOffset();
final String whiteSpaceText = myBuilder.getOriginalText().subSequence(whiteSpaceStart, whiteSpaceEnd).toString();
int i = whiteSpaceText.lastIndexOf('\n');
if (i >= 0) {
myCurrentIndent = whiteSpaceText.length() - i - 1;
myNewLine = true;
}
else {
myNewLine = false;
}
}
protected void advanceUntil(TokenSet tokenSet) {
while (getTokenType() != null && !isNewLine() && !tokenSet.contains(getTokenType())) {
advance();
}
}
protected void advanceUntilEol() {
advanceUntil(TokenSet.EMPTY);
}
protected void errorUntil(TokenSet tokenSet, String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntil(tokenSet);
errorMarker.error(message);
}
protected void errorUntilEol(String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntilEol();
errorMarker.error(message);
}
protected void expectEolOrEof() {
if (!isNewLine() && !eof()) {
errorUntilEol("End of line expected");
}
}
protected abstract IElementType getIndentElementType();
protected abstract IElementType getEolElementType();
}
|
package org.motechproject.mds;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.collections.CollectionUtils;
import org.eclipse.gemini.blueprint.util.OsgiBundleUtils;
import org.joda.time.DateTime;
import org.motechproject.commons.api.AbstractDataProvider;
import org.motechproject.commons.api.DataProvider;
import org.motechproject.commons.date.model.Time;
import org.motechproject.mds.builder.MDSDataProviderBuilder;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.service.MotechDataService;
import org.motechproject.mds.util.ClassName;
import org.motechproject.mds.util.Constants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
/**
* Class responsible for all actions connected with registering MDS data provider in Task module.
*/
@Component("mdsDataProvider")
public class MDSDataProvider extends AbstractDataProvider {
private ResourceLoader resourceLoader;
private MDSDataProviderBuilder mdsDataProviderBuilder;
private BundleContext bundleContext;
private ServiceRegistration serviceRegistration;
@Autowired
public MDSDataProvider(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
registerDataProvider();
}
@Override
public String getName() {
return "data-services";
}
@Override
public Object lookup(String type, String lookupName, Map<String, String> lookupFields) {
Object obj = null;
String className = type.substring(type.lastIndexOf('.') + 1).trim();
if (supports(className)) {
String serviceName = ClassName.getInterfaceName(getPackageRoot() + "." + className);
ServiceReference ref = bundleContext.getServiceReference(serviceName);
if (ref != null) {
try {
Class<?> objectClass = OsgiBundleUtils.findBundleBySymbolicName(bundleContext,
Constants.BundleNames.MDS_ENTITIES_SYMBOLIC_NAME).loadClass(serviceName);
MotechDataService service = (MotechDataService) bundleContext.getService(ref);
obj = MethodUtils.invokeExactMethod(objectClass.cast(service), lookupName,
generateArgumentsForLookup(lookupFields, type));
} catch (ClassNotFoundException e) {
logError("Class %s not found", serviceName, e);
} catch (InvocationTargetException e) {
logError("Can't invoke method %s", lookupName, e);
} catch (NoSuchMethodException e) {
logError("Method %s not found", lookupName, e);
} catch (IllegalAccessException e) {
logError("Can't access method %s", lookupName, e);
}
} else {
logError("Service %s not found", serviceName);
}
}
return obj;
}
private Object[] generateArgumentsForLookup(Map<String, String> lookupFields, String type) throws ClassNotFoundException {
EntityDto entityDto = mdsDataProviderBuilder.getEntityService().getEntityByClassName(type);
List<FieldDto> fieldDtos = mdsDataProviderBuilder.getEntityService().getEntityFields(entityDto.getId());
List<Object> args = new LinkedList<>();
for (FieldDto dto : fieldDtos) {
if (lookupFields.get(dto.getBasic().getName()) != null) {
args.add(castToClass(dto.getType().getTypeClass(), lookupFields.get(dto.getBasic().getName())));
}
}
Collections.reverse(args);
return args.toArray();
}
private Object castToClass(String paramClass, String param) {
Object castParam = param;
if (paramClass.compareTo(Long.class.getName()) == 0) {
castParam = Long.valueOf(param);
} else if (paramClass.compareTo(Integer.class.getName()) == 0) {
castParam = Integer.valueOf(param);
} else if (paramClass.compareTo(Double.class.getName()) == 0) {
castParam = Double.valueOf(param);
} else if (paramClass.compareTo(Boolean.class.getName()) == 0) {
castParam = Boolean.valueOf(param);
} else if (paramClass.compareTo(List.class.getName()) == 0) {
castParam = asList(param);
} else if (paramClass.compareTo(Time.class.getName()) == 0) {
castParam = Time.valueOf(param);
} else if (paramClass.compareTo(DateTime.class.getName()) == 0) {
castParam = DateTime.parse(param);
} else if (paramClass.compareTo(Date.class.getName()) == 0) {
castParam = Date.parse(param);
}
return castParam;
}
@Override
protected Class<?> getClassForType(String type) throws ClassNotFoundException {
Bundle entitiesBundle = OsgiBundleUtils.findBundleBySymbolicName(bundleContext,
Constants.BundleNames.MDS_ENTITIES_SYMBOLIC_NAME);
return (entitiesBundle != null) ? entitiesBundle.loadClass(String.format("%s.%s", getPackageRoot(), type)) : null;
}
@Override
public List<Class<?>> getSupportClasses() {
List<EntityDto> dtos = mdsDataProviderBuilder.getEntityService().listEntities();
List<Class<?>> classes = new ArrayList<>();
for (EntityDto dto : dtos) {
try {
classes.add(getClassForType(dto.getName()));
} catch (ClassNotFoundException e) {
logError(e.getMessage(), e);
}
}
return classes;
}
@Override
public String getPackageRoot() {
return "org.motechproject.mds.entity";
}
public void updateDataProvider() {
setBody(mdsDataProviderBuilder.generateDataProvider());
// we unregister the service, then register again
if (serviceRegistration != null) {
serviceRegistration.unregister();
serviceRegistration = null;
}
// only register if we actually have entities
if (CollectionUtils.isNotEmpty(mdsDataProviderBuilder.getEntityService().getEntitiesWithLookups())) {
serviceRegistration = bundleContext.registerService(DataProvider.class.getName(), this, null);
}
}
private void registerDataProvider() {
Resource resource = resourceLoader.getResource("task-data-provider.json");
if (resource != null) {
setBody(resource);
}
}
@Autowired
public void setMdsDataProviderBuilder(MDSDataProviderBuilder mdsDataProviderBuilder) {
this.mdsDataProviderBuilder = mdsDataProviderBuilder;
}
@Autowired
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
|
package org.jetbrains.plugins.github.api;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.net.ssl.CertificateManager;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.plugins.github.exceptions.*;
import org.jetbrains.plugins.github.util.GithubAuthData;
import org.jetbrains.plugins.github.util.GithubSettings;
import org.jetbrains.plugins.github.util.GithubUrlUtil;
import org.jetbrains.plugins.github.util.GithubUtil;
import sun.security.validator.ValidatorException;
import javax.net.ssl.SSLHandshakeException;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
import java.util.List;
import static org.jetbrains.plugins.github.api.GithubApiUtil.createDataFromRaw;
import static org.jetbrains.plugins.github.api.GithubApiUtil.fromJson;
public class GithubConnection {
private static final Logger LOG = GithubUtil.LOG;
private static final HttpRequestInterceptor PREEMPTIVE_BASIC_AUTH = new PreemptiveBasicAuthInterceptor();
@NotNull private final String myHost;
@NotNull private final CloseableHttpClient myClient;
private final boolean myReusable;
private volatile HttpUriRequest myRequest;
private volatile boolean myAborted;
@TestOnly
public GithubConnection(@NotNull GithubAuthData auth) {
this(auth, false);
}
public GithubConnection(@NotNull GithubAuthData auth, boolean reusable) {
myHost = auth.getHost();
myClient = createClient(auth);
myReusable = reusable;
}
private enum HttpVerb {
GET, POST, DELETE, HEAD, PATCH
}
@Nullable
public JsonElement getRequest(@NotNull String path,
@NotNull Header... headers) throws IOException {
return request(path, null, Arrays.asList(headers), HttpVerb.GET).getJsonElement();
}
@Nullable
public JsonElement postRequest(@NotNull String path,
@Nullable String requestBody,
@NotNull Header... headers) throws IOException {
return request(path, requestBody, Arrays.asList(headers), HttpVerb.POST).getJsonElement();
}
@Nullable
public JsonElement patchRequest(@NotNull String path,
@Nullable String requestBody,
@NotNull Header... headers) throws IOException {
return request(path, requestBody, Arrays.asList(headers), HttpVerb.PATCH).getJsonElement();
}
@Nullable
public JsonElement deleteRequest(@NotNull String path,
@NotNull Header... headers) throws IOException {
return request(path, null, Arrays.asList(headers), HttpVerb.DELETE).getJsonElement();
}
@NotNull
public Header[] headRequest(@NotNull String path,
@NotNull Header... headers) throws IOException {
return request(path, null, Arrays.asList(headers), HttpVerb.HEAD).getHeaders();
}
public void abort() {
if (myAborted) return;
myAborted = true;
HttpUriRequest request = myRequest;
if (request != null) request.abort();
}
public void close() throws IOException {
myClient.close();
}
@NotNull
private static CloseableHttpClient createClient(@NotNull GithubAuthData auth) {
HttpClientBuilder builder = HttpClients.custom();
return builder
.setDefaultRequestConfig(createRequestConfig(auth))
.setDefaultConnectionConfig(createConnectionConfig(auth))
.setDefaultCredentialsProvider(createCredentialsProvider(auth))
.setDefaultHeaders(createHeaders(auth))
.addInterceptorFirst(PREEMPTIVE_BASIC_AUTH)
.setSslcontext(CertificateManager.getInstance().getSslContext())
.setHostnameVerifier((X509HostnameVerifier)CertificateManager.HOSTNAME_VERIFIER)
.build();
}
@NotNull
private static RequestConfig createRequestConfig(@NotNull GithubAuthData auth) {
RequestConfig.Builder builder = RequestConfig.custom();
int timeout = GithubSettings.getInstance().getConnectionTimeout();
builder
.setConnectTimeout(timeout)
.setSocketTimeout(timeout);
final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
boolean useProxy = auth.isUseProxy() && proxySettings.USE_HTTP_PROXY;
proxySettings.setProxy(builder, useProxy);
return builder.build();
}
@NotNull
private static ConnectionConfig createConnectionConfig(@NotNull GithubAuthData auth) {
return ConnectionConfig.custom()
.setCharset(Consts.UTF_8)
.build();
}
@NotNull
private static CredentialsProvider createCredentialsProvider(@NotNull GithubAuthData auth) {
CredentialsProvider provider = new BasicCredentialsProvider();
// Basic authentication
GithubAuthData.BasicAuth basicAuth = auth.getBasicAuth();
if (basicAuth != null) {
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
}
final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
//proxySettings.USE_HTTP_PROXY
boolean useProxy = auth.isUseProxy() && proxySettings.USE_HTTP_PROXY;
proxySettings.setProxyCredentials(provider, useProxy);
return provider;
}
@NotNull
private static Collection<? extends Header> createHeaders(@NotNull GithubAuthData auth) {
List<Header> headers = new ArrayList<Header>();
GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
if (tokenAuth != null) {
headers.add(new BasicHeader("Authorization", "token " + tokenAuth.getToken()));
}
GithubAuthData.BasicAuth basicAuth = auth.getBasicAuth();
if (basicAuth != null && basicAuth.getCode() != null) {
headers.add(new BasicHeader("X-GitHub-OTP", basicAuth.getCode()));
}
return headers;
}
@NotNull
private ResponsePage request(@NotNull String path,
@Nullable String requestBody,
@NotNull Collection<Header> headers,
@NotNull HttpVerb verb) throws IOException {
if (myAborted) throw new GithubOperationCanceledException();
if (EventQueue.isDispatchThread() && !ApplicationManager.getApplication().isUnitTestMode()) {
LOG.warn("Network operation in EDT"); // TODO: fix
}
CloseableHttpResponse response = null;
try {
String uri = GithubUrlUtil.getApiUrl(myHost) + path;
response = doREST(uri, requestBody, headers, verb);
if (myAborted) throw new GithubOperationCanceledException();
checkStatusCode(response, requestBody);
HttpEntity entity = response.getEntity();
if (entity == null) {
return createResponse(response);
}
JsonElement ret = parseResponse(entity.getContent());
if (ret.isJsonNull()) {
return createResponse(response);
}
String newPath = null;
Header pageHeader = response.getFirstHeader("Link");
if (pageHeader != null) {
for (HeaderElement element : pageHeader.getElements()) {
NameValuePair rel = element.getParameterByName("rel");
if (rel != null && "next".equals(rel.getValue())) {
String urlString = element.toString();
int begin = urlString.indexOf('<');
int end = urlString.lastIndexOf('>');
if (begin == -1 || end == -1) {
LOG.error("Invalid 'Link' header", "{" + pageHeader.toString() + "}");
break;
}
String url = urlString.substring(begin + 1, end);
String newUrl = GithubUrlUtil.removeProtocolPrefix(url);
int index = newUrl.indexOf('/');
newPath = newUrl.substring(index);
break;
}
}
}
return createResponse(ret, newPath, response);
}
catch (SSLHandshakeException e) { // User canceled operation from CertificateManager
if (e.getCause() instanceof ValidatorException) {
LOG.info("Host SSL certificate is not trusted", e);
throw new GithubOperationCanceledException("Host SSL certificate is not trusted", e);
}
throw e;
}
catch (IOException e) {
if (myAborted) throw new GithubOperationCanceledException("Operation canceled", e);
throw e;
}
finally {
myRequest = null;
if (response != null) {
response.close();
}
if (!myReusable) {
myClient.close();
}
}
}
@NotNull
private CloseableHttpResponse doREST(@NotNull final String uri,
@Nullable final String requestBody,
@NotNull final Collection<Header> headers,
@NotNull final HttpVerb verb) throws IOException {
HttpRequestBase request;
switch (verb) {
case POST:
request = new HttpPost(uri);
if (requestBody != null) {
((HttpPost)request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
}
break;
case PATCH:
request = new HttpPatch(uri);
if (requestBody != null) {
((HttpPatch)request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
}
break;
case GET:
request = new HttpGet(uri);
break;
case DELETE:
request = new HttpDelete(uri);
break;
case HEAD:
request = new HttpHead(uri);
break;
default:
throw new IllegalStateException("Unknown HttpVerb: " + verb.toString());
}
for (Header header : headers) {
request.addHeader(header);
}
myRequest = request;
return myClient.execute(request);
}
private static void checkStatusCode(@NotNull CloseableHttpResponse response, @Nullable String body) throws IOException {
int code = response.getStatusLine().getStatusCode();
switch (code) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NO_CONTENT:
return;
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PAYMENT_REQUIRED:
case HttpStatus.SC_FORBIDDEN:
String message = getErrorMessage(response);
Header headerOTP = response.getFirstHeader("X-GitHub-OTP");
if (headerOTP != null) {
for (HeaderElement element : headerOTP.getElements()) {
if ("required".equals(element.getName())) {
throw new GithubTwoFactorAuthenticationException(message);
}
}
}
if (message.contains("API rate limit exceeded")) {
throw new GithubRateLimitExceededException(message);
}
throw new GithubAuthenticationException("Request response: " + message);
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
if (body != null) {
LOG.info(body);
}
throw new GithubStatusCodeException(code + ": " + getErrorMessage(response), code);
default:
throw new GithubStatusCodeException(code + ": " + getErrorMessage(response), code);
}
}
@NotNull
private static String getErrorMessage(@NotNull CloseableHttpResponse response) {
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
GithubErrorMessageRaw error = fromJson(parseResponse(entity.getContent()), GithubErrorMessageRaw.class);
return response.getStatusLine().getReasonPhrase() + " - " + error.getMessage();
}
}
catch (IOException e) {
LOG.info(e);
}
return response.getStatusLine().getReasonPhrase();
}
@NotNull
private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException {
Reader reader = new InputStreamReader(githubResponse, "UTF-8");
try {
return new JsonParser().parse(reader);
}
catch (JsonParseException jse) {
throw new GithubJsonException("Couldn't parse GitHub response", jse);
}
finally {
reader.close();
}
}
public static class PagedRequest<T> {
@Nullable private String myNextPage;
@NotNull private final Collection<Header> myHeaders;
@NotNull private final Class<T> myResult;
@NotNull private final Class<? extends DataConstructor[]> myRawArray;
@SuppressWarnings("NullableProblems")
public PagedRequest(@NotNull String path,
@NotNull Class<T> result,
@NotNull Class<? extends DataConstructor[]> rawArray,
@NotNull Header... headers) {
myNextPage = path;
myResult = result;
myRawArray = rawArray;
myHeaders = Arrays.asList(headers);
}
@NotNull
public List<T> next(@NotNull GithubConnection connection) throws IOException {
if (myNextPage == null) {
throw new NoSuchElementException();
}
String page = myNextPage;
myNextPage = null;
ResponsePage response = connection.request(page, null, myHeaders, HttpVerb.GET);
if (response.getJsonElement() == null) {
throw new GithubConfusingException("Empty response");
}
if (!response.getJsonElement().isJsonArray()) {
throw new GithubJsonException("Wrong json type: expected JsonArray", new Exception(response.getJsonElement().toString()));
}
myNextPage = response.getNextPage();
List<T> result = new ArrayList<T>();
for (DataConstructor raw : fromJson(response.getJsonElement().getAsJsonArray(), myRawArray)) {
result.add(createDataFromRaw(raw, myResult));
}
return result;
}
public boolean hasNext() {
return myNextPage != null;
}
@NotNull
public List<T> getAll(@NotNull GithubConnection connection) throws IOException {
List<T> result = new ArrayList<T>();
while (hasNext()) {
result.addAll(next(connection));
}
return result;
}
}
private ResponsePage createResponse(@NotNull CloseableHttpResponse response) throws GithubOperationCanceledException {
if (myAborted) throw new GithubOperationCanceledException();
return new ResponsePage(null, null, response.getAllHeaders());
}
private ResponsePage createResponse(@NotNull JsonElement ret, @Nullable String path, @NotNull CloseableHttpResponse response)
throws GithubOperationCanceledException {
if (myAborted) throw new GithubOperationCanceledException();
return new ResponsePage(ret, path, response.getAllHeaders());
}
private static class ResponsePage {
@Nullable private final JsonElement myResponse;
@Nullable private final String myNextPage;
@NotNull private final Header[] myHeaders;
public ResponsePage(@Nullable JsonElement response, @Nullable String next, @NotNull Header[] headers) {
myResponse = response;
myNextPage = next;
myHeaders = headers;
}
@Nullable
public JsonElement getJsonElement() {
return myResponse;
}
@Nullable
public String getNextPage() {
return myNextPage;
}
@NotNull
public Header[] getHeaders() {
return myHeaders;
}
}
private static class PreemptiveBasicAuthInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
CredentialsProvider provider = (CredentialsProvider)context.getAttribute(HttpClientContext.CREDS_PROVIDER);
Credentials credentials = provider.getCredentials(AuthScope.ANY);
if (credentials != null) {
request.addHeader(new BasicScheme(Consts.UTF_8).authenticate(credentials, request, context));
}
}
}
}
|
package org.jetbrains.idea.svn;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.api.NodeKind;
import org.jetbrains.idea.svn.api.Revision;
import org.jetbrains.idea.svn.api.Url;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationManager;
import org.jetbrains.idea.svn.commandLine.SvnBindException;
import org.jetbrains.idea.svn.history.PropertyRevision;
import org.jetbrains.idea.svn.history.SimplePropertyRevision;
import org.jetbrains.idea.svn.info.Info;
import org.jetbrains.idea.svn.properties.PropertyData;
import org.jetbrains.idea.svn.status.Status;
import org.jetbrains.idea.svn.status.StatusType;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile;
import static org.jetbrains.idea.svn.SvnUtil.append;
import static org.jetbrains.idea.svn.SvnUtil.getRelativePath;
import static org.jetbrains.idea.svn.history.SvnLazyPropertyContentRevision.getPropertyList;
class SvnChangeProviderContext implements StatusReceiver {
private static final Logger LOG = Logger.getInstance(SvnChangeProviderContext.class);
@NotNull private final ChangelistBuilder myChangelistBuilder;
@NotNull private final List<SvnChangedFile> myCopiedFiles = new ArrayList<>();
@NotNull private final List<SvnChangedFile> myDeletedFiles = new ArrayList<>();
// for files moved in a subtree, which were the targets of merge (for instance).
@NotNull private final Map<String, Status> myTreeConflicted = new HashMap<>();
@NotNull private final Map<FilePath, Url> myCopyFromURLs = new HashMap<>();
@NotNull private final SvnVcs myVcs;
private final SvnBranchConfigurationManager myBranchConfigurationManager;
@NotNull private final List<File> filesToRefresh = new ArrayList<>();
@Nullable private final ProgressIndicator myProgress;
SvnChangeProviderContext(@NotNull SvnVcs vcs, @NotNull ChangelistBuilder changelistBuilder, @Nullable ProgressIndicator progress) {
myVcs = vcs;
myChangelistBuilder = changelistBuilder;
myProgress = progress;
myBranchConfigurationManager = SvnBranchConfigurationManager.getInstance(myVcs.getProject());
}
@Override
public void process(FilePath path, Status status) throws SvnBindException {
if (status != null) {
processStatusFirstPass(path, status);
}
}
@Override
public void processIgnored(@NotNull FilePath path) {
myChangelistBuilder.processIgnoredFile(path);
}
@Override
public void processUnversioned(@NotNull FilePath path) {
myChangelistBuilder.processUnversionedFile(path);
}
@Override
public void processCopyRoot(VirtualFile file, Url url, WorkingCopyFormat format, Url rootURL) {
}
@Override
public void bewareRoot(VirtualFile vf, Url url) {
}
@Override
public void finish() {
LocalFileSystem.getInstance().refreshIoFiles(filesToRefresh, true, false, null);
}
@NotNull
public ChangelistBuilder getBuilder() {
return myChangelistBuilder;
}
public void reportTreeConflict(@NotNull Status status) {
myTreeConflicted.put(status.getFile().getAbsolutePath(), status);
}
@Nullable
public Status getTreeConflictStatus(@NotNull File file) {
return myTreeConflicted.get(file.getAbsolutePath());
}
@NotNull
public List<SvnChangedFile> getCopiedFiles() {
return myCopiedFiles;
}
@NotNull
public List<SvnChangedFile> getDeletedFiles() {
return myDeletedFiles;
}
public boolean isDeleted(@NotNull FilePath path) {
for (SvnChangedFile deletedFile : myDeletedFiles) {
if (Comparing.equal(path, deletedFile.getFilePath())) {
return true;
}
}
return false;
}
public void checkCanceled() {
if (myProgress != null) {
myProgress.checkCanceled();
}
}
/**
* If the specified filepath or its parent was added with history, returns the URL of the copy source for this filepath.
*
* @param filePath the original filepath
* @return the copy source url, or null if the file isn't a copy of anything
*/
@Nullable
public Url getParentCopyFromURL(@NotNull FilePath filePath) throws SvnBindException {
Url result = null;
FilePath parent = filePath;
while (parent != null && !myCopyFromURLs.containsKey(parent)) {
parent = parent.getParentPath();
}
if (parent != null) {
Url copyFromUrl = myCopyFromURLs.get(parent);
result = parent == filePath ? copyFromUrl : append(copyFromUrl, getRelativePath(parent.getPath(), filePath.getPath()));
}
return result;
}
public void addCopiedFile(@NotNull FilePath filePath, @NotNull Status status, @NotNull Url copyFromURL) {
myCopiedFiles.add(new SvnChangedFile(filePath, status, copyFromURL));
ContainerUtil.putIfNotNull(filePath, status.getCopyFromUrl(), myCopyFromURLs);
}
void processStatusFirstPass(@NotNull FilePath filePath, @NotNull Status status) throws SvnBindException {
if (status.getRemoteLock() != null) {
myChangelistBuilder.processLogicallyLockedFolder(filePath.getVirtualFile(), status.getRemoteLock().toLogicalLock(false));
}
if (status.getLocalLock() != null) {
myChangelistBuilder.processLogicallyLockedFolder(filePath.getVirtualFile(), status.getLocalLock().toLogicalLock(true));
}
if (filePath.isDirectory() && status.isWorkingCopyLocked()) {
myChangelistBuilder.processLockedFolder(filePath.getVirtualFile());
}
if (status.is(StatusType.STATUS_ADDED, StatusType.STATUS_MODIFIED) && status.getCopyFromUrl() != null) {
addCopiedFile(filePath, status, status.getCopyFromUrl());
}
else if (status.is(StatusType.STATUS_DELETED)) {
myDeletedFiles.add(new SvnChangedFile(filePath, status));
}
else {
Url parentCopyFromURL = getParentCopyFromURL(filePath);
if (parentCopyFromURL != null) {
addCopiedFile(filePath, status, parentCopyFromURL);
}
else {
processStatus(filePath, status);
}
}
}
void processStatus(@NotNull FilePath filePath, @NotNull Status status) throws SvnBindException {
WorkingCopyFormat format = myVcs.getWorkingCopyFormat(filePath.getIOFile());
if (!WorkingCopyFormat.UNKNOWN.equals(format) && format.less(WorkingCopyFormat.ONE_DOT_SEVEN)) {
loadEntriesFile(filePath);
}
FileStatus fStatus = Status.convertStatus(status);
if (status.is(StatusType.STATUS_UNVERSIONED, StatusType.STATUS_NONE)) {
final VirtualFile file = filePath.getVirtualFile();
if (file != null) {
myChangelistBuilder.processUnversionedFile(filePath);
}
}
else if (status.is(StatusType.STATUS_MISSING)) {
myChangelistBuilder.processLocallyDeletedFile(new SvnLocallyDeletedChange(filePath, getState(status)));
}
else if (status.is(StatusType.STATUS_ADDED)) {
processChangeInList(null, CurrentContentRevision.create(filePath), fStatus, status);
}
else if (status.is(StatusType.STATUS_CONFLICTED, StatusType.STATUS_MODIFIED, StatusType.STATUS_REPLACED) ||
status.isProperty(StatusType.STATUS_MODIFIED, StatusType.STATUS_CONFLICTED)) {
processChangeInList(SvnContentRevision.createBaseRevision(myVcs, filePath, status), CurrentContentRevision.create(filePath), fStatus,
status);
checkSwitched(filePath, status, fStatus);
}
else if (status.is(StatusType.STATUS_DELETED)) {
processChangeInList(SvnContentRevision.createBaseRevision(myVcs, filePath, status), null, fStatus, status);
}
else if (status.is(StatusType.STATUS_IGNORED)) {
VirtualFile file = filePath.getVirtualFile();
if (file == null) {
file = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath.getPath());
}
if (file == null) {
LOG.error("No virtual file for ignored file: " + filePath.getPresentableUrl() + ", isNonLocal: " + filePath.isNonLocal());
}
else if (!myVcs.isWcRoot(filePath)) {
myChangelistBuilder.processIgnoredFile(filePath);
}
}
else if (fStatus == FileStatus.NOT_CHANGED || fStatus == FileStatus.SWITCHED) {
VirtualFile file = filePath.getVirtualFile();
if (file != null && FileDocumentManager.getInstance().isFileModified(file)) {
processChangeInList(SvnContentRevision.createBaseRevision(myVcs, filePath, status), CurrentContentRevision.create(filePath),
FileStatus.MODIFIED, status);
}
else if (status.getTreeConflict() != null) {
myChangelistBuilder.processChange(createChange(SvnContentRevision.createBaseRevision(myVcs, filePath, status),
CurrentContentRevision.create(filePath), FileStatus.MODIFIED, status),
SvnVcs.getKey());
}
checkSwitched(filePath, status, fStatus);
}
}
public void addModifiedNotSavedChange(@NotNull VirtualFile file) throws SvnBindException {
final FilePath filePath = VcsUtil.getFilePath(file);
final Info svnInfo = myVcs.getInfo(file);
if (svnInfo != null) {
Status.Builder svnStatus = new Status.Builder(virtualToIoFile(file));
svnStatus.setRevision(svnInfo.getRevision());
svnStatus.setNodeKind(NodeKind.from(filePath.isDirectory()));
processChangeInList(SvnContentRevision.createBaseRevision(myVcs, filePath, svnInfo.getRevision()),
CurrentContentRevision.create(filePath), FileStatus.MODIFIED, svnStatus.build());
}
}
private void processChangeInList(@Nullable ContentRevision beforeRevision,
@Nullable ContentRevision afterRevision,
@NotNull FileStatus fileStatus,
@NotNull Status status) throws SvnBindException {
Change change = createChange(beforeRevision, afterRevision, fileStatus, status);
myChangelistBuilder.processChangeInList(change, SvnUtil.getChangelistName(status), SvnVcs.getKey());
}
private void checkSwitched(@NotNull FilePath filePath, @NotNull Status status, @NotNull FileStatus convertedStatus) {
if (status.isSwitched() || (convertedStatus == FileStatus.SWITCHED)) {
final VirtualFile virtualFile = filePath.getVirtualFile();
if (virtualFile == null) return;
Url switchUrl = status.getUrl();
final VirtualFile vcsRoot = ProjectLevelVcsManager.getInstance(myVcs.getProject()).getVcsRootFor(virtualFile);
if (vcsRoot != null) { // it will be null if we walked into an excluded directory
String baseUrl = myBranchConfigurationManager.get(vcsRoot).getBaseName(switchUrl);
myChangelistBuilder.processSwitchedFile(virtualFile, baseUrl == null ? switchUrl.toDecodedString() : baseUrl, true);
}
}
}
/**
* Ensures that the contents of the 'entries' file is cached in the VFS, so that the VFS will send
* correct events when the 'entries' file is changed externally (to be received by SvnEntriesFileListener)
*
* @param filePath the path of a changed file.
*/
private void loadEntriesFile(@NotNull FilePath filePath) {
final FilePath parentPath = filePath.getParentPath();
if (parentPath == null) {
return;
}
refreshDotSvnAndEntries(parentPath);
if (filePath.isDirectory()) {
refreshDotSvnAndEntries(filePath);
}
}
private void refreshDotSvnAndEntries(@NotNull FilePath filePath) {
final File svn = new File(filePath.getPath(), SvnUtil.SVN_ADMIN_DIR_NAME);
filesToRefresh.add(svn);
filesToRefresh.add(new File(svn, SvnUtil.ENTRIES_FILE_NAME));
}
// seems here we can only have a tree conflict; which can be marked on either path (?)
// .. ok try to merge states
@NotNull
Change createMovedChange(@NotNull ContentRevision before,
@NotNull ContentRevision after,
@Nullable Status copiedStatus,
@NotNull Status deletedStatus) throws SvnBindException {
// todo no convertion needed for the contents status?
ConflictedSvnChange change =
new ConflictedSvnChange(before, after, ConflictState.mergeState(getState(copiedStatus), getState(deletedStatus)),
((copiedStatus != null) && (copiedStatus.getTreeConflict() != null)) ? after.getFile() : before.getFile());
change.setBeforeDescription(deletedStatus.getTreeConflict());
if (copiedStatus != null) {
change.setAfterDescription(copiedStatus.getTreeConflict());
patchWithPropertyChange(change, copiedStatus, deletedStatus);
}
return change;
}
@NotNull
private Change createChange(@Nullable ContentRevision before,
@Nullable ContentRevision after,
@NotNull FileStatus fStatus,
@NotNull Status svnStatus) throws SvnBindException {
ConflictedSvnChange change =
new ConflictedSvnChange(before, after, fStatus, getState(svnStatus), after == null ? before.getFile() : after.getFile());
change.setIsPhantom(svnStatus.is(StatusType.STATUS_DELETED) && !svnStatus.getRevision().isValid());
change.setBeforeDescription(svnStatus.getTreeConflict());
patchWithPropertyChange(change, svnStatus, null);
return change;
}
private void patchWithPropertyChange(@NotNull Change change, @NotNull Status svnStatus, @Nullable Status deletedStatus)
throws SvnBindException {
if (!svnStatus.isProperty(StatusType.STATUS_CONFLICTED, StatusType.CHANGED, StatusType.STATUS_ADDED, StatusType.STATUS_DELETED,
StatusType.STATUS_MODIFIED, StatusType.STATUS_REPLACED, StatusType.MERGED)) {
return;
}
PropertyRevision before = createBeforePropertyRevision(change, svnStatus, deletedStatus);
PropertyRevision after = createAfterPropertyRevision(change, svnStatus);
FileStatus status = deletedStatus != null ? FileStatus.MODIFIED : Status.convertPropertyStatus(svnStatus.getPropertyStatus());
change.addAdditionalLayerElement(SvnChangeProvider.PROPERTY_LAYER, new Change(before, after, status));
}
@Nullable
private PropertyRevision createBeforePropertyRevision(@NotNull Change change,
@NotNull Status svnStatus,
@Nullable Status deletedStatus) throws SvnBindException {
if (svnStatus.isProperty(StatusType.STATUS_ADDED) && deletedStatus == null) return null;
FilePath path = ChangesUtil.getFilePath(change);
File file = deletedStatus != null ? deletedStatus.getFile() : path.getIOFile();
List<PropertyData> properties = getPropertyList(myVcs, file, Revision.BASE);
return new SimplePropertyRevision(properties, path, getRevisionNumber(change.getBeforeRevision()));
}
@Nullable
private PropertyRevision createAfterPropertyRevision(@NotNull Change change, @NotNull Status svnStatus) throws SvnBindException {
if (svnStatus.isProperty(StatusType.STATUS_DELETED)) return null;
FilePath path = ChangesUtil.getFilePath(change);
List<PropertyData> properties = getPropertyList(myVcs, path.getIOFile(), Revision.WORKING);
return new SimplePropertyRevision(properties, path, getRevisionNumber(change.getAfterRevision()));
}
@Nullable
private static String getRevisionNumber(@Nullable ContentRevision revision) {
return revision != null ? revision.getRevisionNumber().asString() : null;
}
@NotNull
private ConflictState getState(@Nullable Status svnStatus) {
ConflictState result = svnStatus != null ? ConflictState.from(svnStatus) : ConflictState.none;
if (result.isTree()) {
//noinspection ConstantConditions
reportTreeConflict(svnStatus);
}
return result;
}
}
|
package com.netflix.priam.defaultimpl;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.SelectRequest;
import com.amazonaws.services.simpledb.model.SelectResult;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.common.collect.Lists;
import com.netflix.priam.IConfiguration;
import com.netflix.priam.ICredential;
import com.netflix.priam.utils.SystemUtils;
@Singleton
public class PriamConfiguration implements IConfiguration
{
private static final String PRIAM_PRE = "priam";
private static final String CONFIG_CASS_HOME_DIR = PRIAM_PRE + ".cass.home";
private static final String CONFIG_CASS_START_SCRIPT = PRIAM_PRE + ".cass.startscript";
private static final String CONFIG_CASS_STOP_SCRIPT = PRIAM_PRE + ".cass.stopscript";
private static final String CONFIG_CLUSTER_NAME = PRIAM_PRE + ".clustername";
private static final String CONFIG_SEED_PROVIDER_NAME = PRIAM_PRE + ".seed.provider";
private static final String CONFIG_LOAD_LOCAL_PROPERTIES = PRIAM_PRE + ".localbootstrap.enable";
private static final String CONFIG_MAX_HEAP_SIZE = PRIAM_PRE + ".heap.size.";
private static final String CONFIG_DATA_LOCATION = PRIAM_PRE + ".data.location";
private static final String CONFIG_MR_ENABLE = PRIAM_PRE + ".multiregion.enable";
private static final String CONFIG_CL_LOCATION = PRIAM_PRE + ".commitlog.location";
private static final String CONFIG_JMX_LISTERN_PORT_NAME = PRIAM_PRE + ".jmx.port";
private static final String CONFIG_AVAILABILITY_ZONES = PRIAM_PRE + ".zones.available";
private static final String CONFIG_SAVE_CACHE_LOCATION = PRIAM_PRE + ".cache.location";
private static final String CONFIG_NEW_MAX_HEAP_SIZE = PRIAM_PRE + ".heap.newgen.size.";
private static final String CONFIG_DIRECT_MAX_HEAP_SIZE = PRIAM_PRE + ".direct.memory.size.";
private static final String CONFIG_THRIFT_LISTERN_PORT_NAME = PRIAM_PRE + ".thrift.port";
private static final String CONFIG_STORAGE_LISTERN_PORT_NAME = PRIAM_PRE + ".storage.port";
private static final String CONFIG_SSL_STORAGE_LISTERN_PORT_NAME = PRIAM_PRE + ".ssl.storage.port";
private static final String CONFIG_CL_BK_LOCATION = PRIAM_PRE + ".backup.commitlog.location";
private static final String CONFIG_THROTTLE_UPLOAD_PER_SECOND = PRIAM_PRE + ".upload.throttle";
private static final String CONFIG_IN_MEMORY_COMPACTION_LIMIT = PRIAM_PRE + ".memory.compaction.limit";
private static final String CONFIG_COMPACTION_THROUHPUT = PRIAM_PRE + ".compaction.throughput";
private static final String CONFIG_MAX_HINT_WINDOW_IN_MS = PRIAM_PRE + ".hint.window";
private static final String CONFIG_HINT_DELAY = PRIAM_PRE + ".hint.delay";
private static final String CONFIG_BOOTCLUSTER_NAME = PRIAM_PRE + ".bootcluster";
private static final String CONFIG_ENDPOINT_SNITCH = PRIAM_PRE + ".endpoint_snitch";
private static final String CONFIG_MEMTABLE_TOTAL_SPACE = PRIAM_PRE + ".memtabletotalspace";
// Backup and Restore
private static final String CONFIG_BACKUP_THREADS = PRIAM_PRE + ".backup.threads";
private static final String CONFIG_RESTORE_PREFIX = PRIAM_PRE + ".restore.prefix";
private static final String CONFIG_INCR_BK_ENABLE = PRIAM_PRE + ".backup.incremental.enable";
private static final String CONFIG_CL_BK_ENABLE = PRIAM_PRE + ".backup.commitlog.enable";
private static final String CONFIG_AUTO_RESTORE_SNAPSHOTNAME = PRIAM_PRE + ".restore.snapshot";
private static final String CONFIG_BUCKET_NAME = PRIAM_PRE + ".s3.bucket";
private static final String CONFIG_BACKUP_HOUR = PRIAM_PRE + ".backup.hour";
private static final String CONFIG_S3_BASE_DIR = PRIAM_PRE + ".s3.base_dir";
private static final String CONFIG_RESTORE_THREADS = PRIAM_PRE + ".restore.threads";
private static final String CONFIG_RESTORE_CLOSEST_TOKEN = PRIAM_PRE + ".restore.closesttoken";
private static final String CONFIG_RESTORE_KEYSPACES = PRIAM_PRE + ".restore.keyspaces";
private static final String CONFIG_BACKUP_CHUNK_SIZE = PRIAM_PRE + ".backup.chunksizemb";
private static final String CONFIG_BACKUP_RETENTION = PRIAM_PRE + ".backup.retention";
private static final String CONFIG_BACKUP_RACS = PRIAM_PRE + ".backup.racs";
private static final String CONFIG_MULTITHREADED_COMPACTION = PRIAM_PRE + ".multithreaded.compaction";
private static final String CONFIG_STREAMING_THROUGHPUT_MB = PRIAM_PRE + ".streaming.throughput.mb";
private static final String CONFIG_PARTITIONER = PRIAM_PRE + ".partitioner";
private static final String CONFIG_KEYCACHE_SIZE = PRIAM_PRE + ".keyCache.size";
private static final String CONFIG_KEYCACHE_COUNT= PRIAM_PRE + ".keyCache.count";
private static final String CONFIG_ROWCACHE_SIZE = PRIAM_PRE + ".rowCache.size";
private static final String CONFIG_ROWCACHE_COUNT= PRIAM_PRE + ".rowCache.count";
// Amazon specific
private static final String CONFIG_ASG_NAME = PRIAM_PRE + ".az.asgname";
private static final String CONFIG_REGION_NAME = PRIAM_PRE + ".az.region";
private static final String CONFIG_ACL_GROUP_NAME = PRIAM_PRE + ".acl.groupname";
private final String RAC = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/placement/availability-zone");
private final String PUBLIC_HOSTNAME = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/public-hostname").trim();
private final String PUBLIC_IP = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/public-ipv4").trim();
private final String INSTANCE_ID = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/instance-id").trim();
private final String INSTANCE_TYPE = SystemUtils.getDataFromUrl("http://169.254.169.254/latest/meta-data/instance-type").trim();
private static String ASG_NAME = System.getenv("ASG_NAME");
private static String REGION = System.getenv("EC2_REGION");
// Defaults
private final String DEFAULT_CLUSTER_NAME = "cass_cluster";
private final String DEFAULT_DATA_LOCATION = "/var/lib/cassandra/data";
private final String DEFAULT_COMMIT_LOG_LOCATION = "/var/lib/cassandra/commitlog";
private final String DEFAULT_CACHE_LOCATION = "/var/lib/cassandra/saved_caches";
private final String DEFAULT_ENDPOINT_SNITCH = "org.apache.cassandra.locator.Ec2Snitch";
private final String DEFAULT_SEED_PROVIDER = "com.netflix.priam.cassandra.extensions.NFSeedProvider";
private final String DEFAULT_PARTITIONER = "org.apache.cassandra.dht.RandomPartitioner";
// rpm based. Can be modified for tar based.
private final String DEFAULT_CASS_HOME_DIR = "/etc/cassandra";
private final String DEFAULT_CASS_START_SCRIPT = "/etc/init.d/cassandra start";
private final String DEFAULT_CASS_STOP_SCRIPT = "/etc/init.d/cassandra stop";
private final String DEFAULT_BACKUP_LOCATION = "backup";
private final String DEFAULT_BUCKET_NAME = "cassandra-archive";
private String DEFAULT_AVAILABILITY_ZONES = "";
private final String DEFAULT_MAX_DIRECT_MEM = "50G";
private final String DEFAULT_MAX_HEAP = "8G";
private final String DEFAULT_MAX_NEWGEN_HEAP = "2G";
private final int DEFAULT_JMX_PORT = 7199;
private final int DEFAULT_THRIFT_PORT = 9160;
private final int DEFAULT_STORAGE_PORT = 7000;
private final int DEFAULT_SSL_STORAGE_PORT = 7001;
private final int DEFAULT_BACKUP_HOUR = 12;
private final int DEFAULT_BACKUP_THREADS = 2;
private final int DEFAULT_RESTORE_THREADS = 8;
private final int DEFAULT_BACKUP_CHUNK_SIZE = 10;
private final int DEFAULT_BACKUP_RETENTION = 0;
private PriamProperties config;
private static final Logger logger = LoggerFactory.getLogger(PriamConfiguration.class);
private static class Attributes
{
public final static String APP_ID = "appId"; // ASG
public final static String PROPERTY = "property";
public final static String PROPERTY_VALUE = "value";
public final static String REGION = "region";
}
private static final String DOMAIN = "PriamProperties";
private static String ALL_QUERY = "select * from " + DOMAIN + " where " + Attributes.APP_ID + "='%s'";
private final ICredential provider;
@Inject
public PriamConfiguration(ICredential provider)
{
this.provider = provider;
}
@Override
public void intialize()
{
setupEnvVars();
setDefaultRACList(REGION);
populateProps();
SystemUtils.createDirs(getBackupCommitLogLocation());
SystemUtils.createDirs(getCommitLogLocation());
SystemUtils.createDirs(getCacheLocation());
SystemUtils.createDirs(getDataFileLocation());
}
private void setupEnvVars()
{
// Search in java opt properties
REGION = StringUtils.isBlank(REGION) ? System.getProperty("EC2_REGION") : REGION;
// Infer from zone
if (StringUtils.isBlank(REGION))
REGION = RAC.substring(0, RAC.length() - 1);
ASG_NAME = StringUtils.isBlank(ASG_NAME) ? System.getProperty("ASG_NAME") : ASG_NAME;
if (StringUtils.isBlank(ASG_NAME))
ASG_NAME = populateASGName(REGION, INSTANCE_ID);
logger.info(String.format("REGION set to %s, ASG Name set to %s", REGION, ASG_NAME));
}
/**
* Query amazon to get ASG name. Currently not available as part of instance
* info api.
*/
private String populateASGName(String region, String instanceId)
{
AmazonEC2 client = new AmazonEC2Client(provider.getCredentials());
client.setEndpoint("ec2." + region + ".amazonaws.com");
DescribeInstancesRequest desc = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult res = client.describeInstances(desc);
for (Reservation resr : res.getReservations())
{
for (Instance ins : resr.getInstances())
{
for (com.amazonaws.services.ec2.model.Tag tag : ins.getTags())
{
if (tag.getKey().equals("aws:autoscaling:groupName"))
return tag.getValue();
}
}
}
return null;
}
/**
* Get the fist 3 available zones in the region
*/
public void setDefaultRACList(String region){
AmazonEC2 client = new AmazonEC2Client(provider.getCredentials());
client.setEndpoint("ec2." + region + ".amazonaws.com");
DescribeAvailabilityZonesResult res = client.describeAvailabilityZones();
List<String> zone = Lists.newArrayList();
for(AvailabilityZone reg : res.getAvailabilityZones()){
if( reg.getState().equals("available") )
zone.add(reg.getZoneName());
if( zone.size() == 3)
break;
}
DEFAULT_AVAILABILITY_ZONES = StringUtils.join(zone, ",");
}
private void populateProps()
{
// End point is us-east-1
AmazonSimpleDBClient simpleDBClient = new AmazonSimpleDBClient(provider.getCredentials());
config = new PriamProperties();
config.put(CONFIG_ASG_NAME, ASG_NAME);
config.put(CONFIG_REGION_NAME, REGION);
String nextToken = null;
String appid = ASG_NAME.lastIndexOf('-') > 0 ? ASG_NAME.substring(0, ASG_NAME.indexOf('-')): ASG_NAME;
logger.info(String.format("appid used to fetch properties is: %s",appid));
do
{
SelectRequest request = new SelectRequest(String.format(ALL_QUERY, appid));
request.setNextToken(nextToken);
SelectResult result = simpleDBClient.select(request);
nextToken = result.getNextToken();
Iterator<Item> itemiter = result.getItems().iterator();
while (itemiter.hasNext())
addProperty(itemiter.next());
} while (nextToken != null);
}
private void addProperty(Item item)
{
Iterator<Attribute> attrs = item.getAttributes().iterator();
String prop = "";
String value = "";
String dc = "";
while (attrs.hasNext())
{
Attribute att = attrs.next();
if (att.getName().equals(Attributes.PROPERTY))
prop = att.getValue();
else if (att.getName().equals(Attributes.PROPERTY_VALUE))
value = att.getValue();
else if (att.getName().equals(Attributes.REGION))
dc = att.getValue();
}
// Ignore, if not this region
if (StringUtils.isNotBlank(dc) && !dc.equals(REGION))
return;
// Override only if region is specified
if (config.contains(prop) && StringUtils.isBlank(dc))
return;
config.put(prop, value);
}
@Override
public String getCassStartupScript()
{
return config.getProperty(CONFIG_CASS_START_SCRIPT, DEFAULT_CASS_START_SCRIPT);
}
@Override
public String getCassStopScript()
{
return config.getProperty(CONFIG_CASS_STOP_SCRIPT, DEFAULT_CASS_STOP_SCRIPT);
}
@Override
public String getCassHome()
{
return config.getProperty(CONFIG_CASS_HOME_DIR, DEFAULT_CASS_HOME_DIR);
}
@Override
public String getBackupLocation()
{
return config.getProperty(CONFIG_S3_BASE_DIR, DEFAULT_BACKUP_LOCATION);
}
@Override
public String getBackupPrefix()
{
return config.getProperty(CONFIG_BUCKET_NAME, DEFAULT_BUCKET_NAME);
}
@Override
public int getBackupRetentionDays()
{
return config.getInteger(CONFIG_BACKUP_RETENTION, DEFAULT_BACKUP_RETENTION);
}
@Override
public List<String> getBackupRacs()
{
return config.getList(CONFIG_BACKUP_RACS);
}
@Override
public String getRestorePrefix()
{
return config.getProperty(CONFIG_RESTORE_PREFIX);
}
@Override
public List<String> getRestoreKeySpaces()
{
return config.getList(CONFIG_RESTORE_KEYSPACES);
}
@Override
public String getDataFileLocation()
{
return config.getProperty(CONFIG_DATA_LOCATION, DEFAULT_DATA_LOCATION);
}
@Override
public String getCacheLocation()
{
return config.getProperty(CONFIG_SAVE_CACHE_LOCATION, DEFAULT_CACHE_LOCATION);
}
@Override
public String getCommitLogLocation()
{
return config.getProperty(CONFIG_CL_LOCATION, DEFAULT_COMMIT_LOG_LOCATION);
}
@Override
public String getBackupCommitLogLocation()
{
return config.getProperty(CONFIG_CL_BK_LOCATION, "");
}
@Override
public long getBackupChunkSize()
{
long size = config.getLong(CONFIG_BACKUP_CHUNK_SIZE, DEFAULT_BACKUP_CHUNK_SIZE);
return size*1024*1024L;
}
@Override
public boolean isCommitLogBackup()
{
return config.getBoolean(CONFIG_CL_BK_ENABLE, false);
}
@Override
public int getJmxPort()
{
return config.getInteger(CONFIG_JMX_LISTERN_PORT_NAME, DEFAULT_JMX_PORT);
}
@Override
public int getThriftPort()
{
return config.getInteger(CONFIG_THRIFT_LISTERN_PORT_NAME, DEFAULT_THRIFT_PORT);
}
@Override
public int getStoragePort()
{
return config.getInteger(CONFIG_STORAGE_LISTERN_PORT_NAME, DEFAULT_STORAGE_PORT);
}
@Override
public int getSSLStoragePort()
{
return config.getInteger(CONFIG_SSL_STORAGE_LISTERN_PORT_NAME, DEFAULT_SSL_STORAGE_PORT);
}
@Override
public String getSnitch()
{
return config.getProperty(CONFIG_ENDPOINT_SNITCH, DEFAULT_ENDPOINT_SNITCH);
}
@Override
public String getAppName()
{
return config.getProperty(CONFIG_CLUSTER_NAME, DEFAULT_CLUSTER_NAME);
}
@Override
public String getRac()
{
return RAC;
}
@Override
public List<String> getRacs()
{
return config.getList(CONFIG_AVAILABILITY_ZONES, DEFAULT_AVAILABILITY_ZONES);
}
@Override
public String getHostname()
{
return PUBLIC_HOSTNAME;
}
@Override
public String getInstanceName()
{
return INSTANCE_ID;
}
@Override
public String getHeapSize()
{
return config.getProperty(CONFIG_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_HEAP);
}
@Override
public String getHeapNewSize()
{
return config.getProperty(CONFIG_NEW_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_NEWGEN_HEAP);
}
@Override
public String getMaxDirectMemory()
{
return config.getProperty(CONFIG_DIRECT_MAX_HEAP_SIZE + INSTANCE_TYPE, DEFAULT_MAX_DIRECT_MEM);
}
@Override
public int getBackupHour()
{
return config.getInteger(CONFIG_BACKUP_HOUR, DEFAULT_BACKUP_HOUR);
}
@Override
public String getRestoreSnapshot()
{
return config.getProperty(CONFIG_AUTO_RESTORE_SNAPSHOTNAME, "");
}
@Override
public String getDC()
{
return config.getProperty(CONFIG_REGION_NAME, "");
}
@Override
public void setDC(String region)
{
config.setProperty(CONFIG_REGION_NAME, region);
}
@Override
public boolean isMultiDC()
{
return config.getBoolean(CONFIG_MR_ENABLE, false);
}
@Override
public int getMaxBackupUploadThreads()
{
return config.getInteger(CONFIG_BACKUP_THREADS, DEFAULT_BACKUP_THREADS);
}
@Override
public int getMaxBackupDownloadThreads()
{
return config.getInteger(CONFIG_RESTORE_THREADS, DEFAULT_RESTORE_THREADS);
}
@Override
public boolean isRestoreClosestToken()
{
return config.getBoolean(CONFIG_RESTORE_CLOSEST_TOKEN, false);
}
@Override
public String getASGName()
{
return config.getProperty(CONFIG_ASG_NAME, "");
}
@Override
public String getACLGroupName()
{
return config.getProperty(CONFIG_ACL_GROUP_NAME, this.getAppName());
}
@Override
public boolean isIncrBackup()
{
return config.getBoolean(CONFIG_INCR_BK_ENABLE, true);
}
@Override
public String getHostIP()
{
return PUBLIC_IP;
}
@Override
public int getUploadThrottle()
{
return config.getInteger(CONFIG_THROTTLE_UPLOAD_PER_SECOND, Integer.MAX_VALUE);
}
@Override
public boolean isLocalBootstrapEnabled()
{
return config.getBoolean(CONFIG_LOAD_LOCAL_PROPERTIES, false);
}
@Override
public int getInMemoryCompactionLimit()
{
return config.getInteger(CONFIG_IN_MEMORY_COMPACTION_LIMIT, 128);
}
@Override
public int getCompactionThroughput()
{
return config.getInteger(CONFIG_COMPACTION_THROUHPUT, 8);
}
@Override
public int getMaxHintWindowInMS()
{
return config.getInteger(CONFIG_MAX_HINT_WINDOW_IN_MS, 8);
}
@Override
public int getHintHandoffDelay()
{
return config.getInteger(CONFIG_HINT_DELAY, 1);
}
@Override
public String getBootClusterName()
{
return config.getProperty(CONFIG_BOOTCLUSTER_NAME, "");
}
@Override
public String getSeedProviderName()
{
return config.getProperty(CONFIG_SEED_PROVIDER_NAME, DEFAULT_SEED_PROVIDER);
}
private class PriamProperties extends Properties
{
private static final long serialVersionUID = 1L;
public int getInteger(String prop, int defaultValue)
{
return getProperty(prop) == null ? defaultValue : Integer.parseInt(getProperty(prop));
}
public long getLong(String prop, long defaultValue)
{
return getProperty(prop) == null ? defaultValue : Long.parseLong(getProperty(prop));
}
public boolean getBoolean(String prop, boolean defaultValue)
{
return getProperty(prop) == null ? defaultValue : Boolean.parseBoolean(getProperty(prop));
}
public List<String> getList(String prop)
{
if (getProperty(prop) == null)
return Lists.newArrayList();
return getTrimmedStringList(getProperty(prop).split(","));
}
public List<String> getList(String prop, String defaultValue)
{
if (getProperty(prop) == null)
return getTrimmedStringList(defaultValue.split(","));
return getList(prop);
}
}
@Override
/**
* Defaults to 0, means dont set it in yaml
*/
public int getMemtableTotalSpaceMB()
{
return config.getInteger(CONFIG_MEMTABLE_TOTAL_SPACE, 1024);
}
@Override
public int getStreamingThroughputMB()
{
return config.getInteger(CONFIG_STREAMING_THROUGHPUT_MB, 400);
}
@Override
public boolean getMultithreadedCompaction()
{
return config.getBoolean(CONFIG_MULTITHREADED_COMPACTION, false);
}
public String getPartitioner()
{
return config.getProperty(CONFIG_PARTITIONER, DEFAULT_PARTITIONER);
}
public String getKeyCacheSizeInMB()
{
return config.getProperty(CONFIG_KEYCACHE_SIZE, null);
}
public String getKeyCacheKeysToSave()
{
return config.getProperty(CONFIG_KEYCACHE_COUNT, null);
}
public String getRowCacheSizeInMB()
{
return config.getProperty(CONFIG_ROWCACHE_SIZE, null);
}
public String getRowCacheKeysToSave()
{
return config.getProperty(CONFIG_ROWCACHE_COUNT, null);
}
private List<String> getTrimmedStringList(String[] strings) {
List<String> list = Lists.newArrayList();
for(String s : strings) {
list.add(StringUtils.strip(s));
}
return list;
}
}
|
// $Id: AtlantiBoard.java,v 1.12 2001/10/18 18:42:33 mdb Exp $
package com.threerings.venison;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.samskivert.swing.Controller;
import com.samskivert.swing.util.SwingUtil;
import com.samskivert.util.CollectionUtil;
import com.threerings.presents.dobj.DSet;
/**
* Displays the tiles that make up the Venison board.
*/
public class VenisonBoard
extends JPanel implements TileCodes, VenisonCodes
{
/** The command posted when a tile is placed by the user on the
* board. */
public static final String TILE_PLACED_CMD = "tile_placed";
/**
* Constructs a Venison board.
*/
public VenisonBoard ()
{
// create mouse adapters that will let us know when interesting
// mouse events happen
addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent evt) {
VenisonBoard.this.mouseClicked(evt);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved (MouseEvent evt) {
VenisonBoard.this.mouseMoved(evt);
}
});
}
/**
* Sets the piecen color to use when creating new piecens.
*/
public void setNewPiecenColor (int color)
{
_newPiecenColor = color;
}
/**
* Sets the tiles to be displayed by this board. Any previous tiles
* are forgotten and the new tiles are initialized according to their
* geometry to set up initial claim groups.
*
* @param tset the set of {@link VenisonTile} objects to be displayed
* by this board.
*/
public void setTiles (DSet tset)
{
// clear out our old tiles list
_tiles.clear();
// copy the tiles from the set into our local list
CollectionUtil.addAll(_tiles, tset.elements());
// sort the list
Collections.sort(_tiles);
// recompute our desired dimensions and then have our parent
// adjust to our changed size
computeDimensions();
}
/**
* Sets the piecens to be placed on the appropriate tiles of the
* board. This should only be done when first entering the game room
* and subsequent piecen placement should be done via {@link
* #placePiecen}.
*/
public void setPiecens (DSet piecens)
{
// just iterate over the set placing each of the piecens in turn
Iterator iter = piecens.elements();
while (iter.hasNext()) {
placePiecen((Piecen)iter.next());
}
}
/**
* Instructs the board to add the specified tile to the display. The
* tile will have its claims inherited accordingly.
*/
public void addTile (VenisonTile tile)
{
Log.info("Adding tile to board " + tile + ".");
// if we add a tile that is the same as our most recently placed
// tile, leave the placed tile. otherwise clear it out
if (!tile.equals(_placedTile)) {
_placedTile = null;
}
// add the tile
_tiles.add(tile);
// reference this as our most recently placed tile
_lastPlacedTile = tile;
// resort the list
Collections.sort(_tiles);
// have the new tile inherit its claim groups
TileUtil.inheritClaims(_tiles, tile);
// recompute our desired dimensions and then have our parent
// adjust to our changed size
computeDimensions();
}
/**
* Places the specified piecen on the appropriate tile and updates
* claim groups as necessary.
*/
public void placePiecen (Piecen piecen)
{
// if we still have a placed tile, we get rid of it
_placedTile = null;
Log.info("Placing " + piecen + ".");
// locate the tile associated with this piecen
int tidx = _tiles.indexOf(piecen);
if (tidx != -1) {
VenisonTile tile = (VenisonTile)_tiles.get(tidx);
// set the piecen on the tile (supplying our tile list so that
// the necessary claim group adjustments can be made)
tile.setPiecen(piecen, _tiles);
// and repaint
repaint();
} else {
Log.warning("Requested to place piecen for which we could " +
"find no associated tile! [piecen=" + piecen + "].");
}
}
/**
* When a piecen is removed (after scoring it), this method should be
* called to update the board display.
*/
public void clearPiecen (Object key)
{
// locate the tile associated with this piecen key
int tsize = _tiles.size();
for (int i = 0; i < tsize; i++) {
VenisonTile tile = (VenisonTile)_tiles.get(i);
if (tile.getKey().equals(key)) {
// clear the piecen out of the tile
tile.clearPiecen();
// and repaint
repaint();
// and get on out
return;
}
}
Log.warning("Requested to clear piecen for which we could " +
"find no associated tile! [key=" + key + "].");
}
/**
* Turn off the ability to place a piecen on the most recently played
* tile. This function assumes that the mouse will not be over a valid
* piecen placement at the time this function is called (it expects
* that it will be over a button of some sort that says something to
* the effect of "skip placement for this turn").
*/
public void cancelPiecenPlacement ()
{
_placingPiecen = false;
}
/**
* If we freed up a placeable piecen that we didn't have when we
* placed our tile, this can be called to reenable piecen placement.
*/
public void enablePiecenPlacement ()
{
_placingPiecen = true;
}
public void setTileToBePlaced (VenisonTile tile)
{
// make a copy of this tile so that we can play with it
_placingTile = (VenisonTile)tile.clone();;
// update our internal state based on this new placing tile
if (_placingTile != null) {
updatePlacingInfo(true);
}
// and repaint
repaint();
}
/**
* Returns the last tile placed by the user.
*/
public VenisonTile getPlacedTile ()
{
return _placedTile;
}
// documentation inherited
public void layout ()
{
super.layout();
// compute our translation coordinates based on our size
_tx = (getWidth() - TILE_WIDTH * _width)/2;
_ty = (getHeight() - TILE_HEIGHT * _height)/2;
}
// documentation inherited
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// center the tile display if we are bigger than we need to be
g.translate(_tx, _ty);
// iterate over our tiles, painting each of them
int tsize = _tiles.size();
for (int i = 0; i < tsize; i++) {
VenisonTile tile = (VenisonTile)_tiles.get(i);
tile.paint(g2, _origX, _origY);
}
// if we have a placing tile, draw that one as well
if (_placingTile != null && _validPlacement) {
// if the current position is valid, draw the placing tile
_placingTile.paint(g2, _origX, _origY);
// draw a green rectangle around the placing tile
g.setColor(Color.blue);
int sx = (_placingTile.x + _origX) * TILE_WIDTH;
int sy = (_placingTile.y + _origY) * TILE_HEIGHT;
g.drawRect(sx, sy, TILE_WIDTH, TILE_HEIGHT);
}
// if we have a recently placed tile, draw that one as well
if (_placedTile != null) {
// draw the tile
_placedTile.paint(g2, _origX, _origY);
// draw a white rectangle around the placed tile
g.setColor(Color.white);
int sx = (_placedTile.x + _origX) * TILE_WIDTH;
int sy = (_placedTile.y + _origY) * TILE_HEIGHT;
g.drawRect(sx, sy, TILE_WIDTH, TILE_HEIGHT);
}
// draw a white rectangle around the last placed
if (_lastPlacedTile != null) {
g.setColor(Color.white);
int sx = (_lastPlacedTile.x + _origX) * TILE_WIDTH;
int sy = (_lastPlacedTile.y + _origY) * TILE_HEIGHT;
g.drawRect(sx, sy, TILE_WIDTH, TILE_HEIGHT);
}
// undo our translations
g.translate(-_tx, -_ty);
}
/** Called by our adapter when the mouse moves. */
protected void mouseMoved (MouseEvent evt)
{
// we always want to know about our last mouse coordinates
_mouseX = evt.getX() - _tx;
_mouseY = evt.getY() - _ty;
if (_placingTile != null) {
// if we have a tile to be placed, update its coordinates
if (updatePlacingInfo(false)) {
repaint();
}
} else if (_placedTile != null && _placingPiecen) {
// if we have a recently placed tile, we're doing piecen
// placement; first convert the mouse coords into tile coords
int mx = _mouseX - (_placedTile.x + _origX) * TILE_WIDTH;
int my = _mouseY - (_placedTile.y + _origY) * TILE_HEIGHT;
boolean changed = false;
// now see if we're inside the placing tile
if (mx >= 0 && mx < TILE_WIDTH && my >= 0 && my < TILE_HEIGHT) {
int fidx = _placedTile.getFeatureIndex(mx, my);
// if the feature is not already claimed, we can put a
// piece there to indicate that it can be claimed
if (_placedTile.claims[fidx] == 0) {
if (_placedTile.piecen == null ||
_placedTile.piecen.featureIndex != fidx) {
Piecen p = new Piecen(_newPiecenColor, 0, 0, fidx);
_placedTile.setPiecen(p, null);
changed = true;
}
} else {
// we may need to clear out a piecen since we've moved
if (_placedTile.piecen != null) {
_placedTile.clearPiecen();
changed = true;
}
}
} else {
// we may need to clear out a piecen since we've moved
if (_placedTile.piecen != null) {
_placedTile.clearPiecen();
changed = true;
}
}
if (changed) {
repaint();
}
}
}
/** Called by our adapter when the mouse is clicked. */
protected void mouseClicked (MouseEvent evt)
{
int modifiers = evt.getModifiers();
// if this is a right button click, and we're in piecen placing
// mode, generate a PLACE_NOTHING notification instead
if (_placingPiecen && (modifiers & MouseEvent.BUTTON3_MASK) != 0) {
// stop piecen placement
_placingPiecen = false;
// clear out any placed piecen because we're placing nothing
if (_placedTile != null && _placedTile.piecen != null) {
_placedTile.piecen = null;
repaint();
}
// post the action
Controller.postAction(this, PLACE_NOTHING);
} else {
// ignore non-button one presses other than cancel piecen
// placement
if ((modifiers & MouseEvent.BUTTON1_MASK) == 0) {
return;
}
}
// if we have a placing tile and it's in a valid position, we want
// to dispatch an action letting the controller know that the user
// placed it
if (_placingTile != null && _validPlacement) {
// move the placing tile to the placed tile
_placedTile = _placingTile;
_placingTile = null;
// inherit claims on the placed tile
TileUtil.inheritClaims(_tiles, _placedTile);
// post the action
Controller.postAction(this, TILE_PLACED);
// move into placing piecen mode
_placingPiecen = true;
// recompute our dimensions (which will relayout or repaint)
computeDimensions();
}
// if we're placing a piecen and the piecen is in a valid
// position, we want to dispatch an action letting the controller
// know that the user placed it
if (_placingPiecen && _placedTile != null &&
_placedTile.piecen != null) {
// clear out placing piecen mode
_placingPiecen = false;
// post the action
Controller.postAction(this, PIECEN_PLACED);
}
}
/**
* Updates the coordinates and orientation of the placing tile based
* on the last known coordinates of the mouse and returns true if the
* coordinates or orientation changed from their previous values.
*/
protected boolean updatePlacingInfo (boolean force)
{
boolean changed = false;
// convert mouse coordinates into tile coordinates and offset them
// by the origin
int x = divFloor(_mouseX, TILE_WIDTH) - _origX;
int y = divFloor(_mouseY, TILE_HEIGHT) - _origY;
// if these are different than the values currently in the placing
// tile, update the tile coordinates
if (_placingTile.x != x || _placingTile.y != y || force) {
// update the coordinates of the tile
_placingTile.x = x;
_placingTile.y = y;
// we've changed the display, so make a note of it
changed = true;
// we also need to recompute the valid orientations for the
// tile in this new position
_validOrients = TileUtil.computeValidOrients(_tiles, _placingTile);
// if we've changed positions, clear out our valid placement
// flag
_validPlacement = false;
}
// determine if we should change the orientation based on the
// position of the mouse within the tile boundaries
int rx = _mouseX % TILE_WIDTH;
int ry = _mouseY % TILE_HEIGHT;
int orient = coordToOrient(rx, ry);
// orientation
for (int i = 0; i < 4; i++) {
int candOrient = (orient+i)%4;
if (_validOrients[candOrient]) {
if (_placingTile.orientation != candOrient) {
_placingTile.orientation = candOrient;
changed = true;
}
_validPlacement = true;
break;
}
}
return changed;
}
/**
* Converts mouse coordinates which are relative to a particular tile,
* into an orientation based on the position within that tile. A tile
* is divided up into four quadrants by lines connecting its four
* corners. If the tile is in a quadrant closes to an edge, it is
* converted to the orientation corresponding with that edge.
*
* @param rx the mouse coordinates modulo tile width.
* @param ry the mouse coordinates modulo tile height.
*
* @return the orientation desired for the tile in which the mouse
* resides.
*/
protected int coordToOrient (int rx, int ry)
{
if (rx > ry) {
if (rx > (TILE_HEIGHT - ry)) {
return EAST;
} else {
return NORTH;
}
} else {
if (rx > (TILE_HEIGHT - ry)) {
return SOUTH;
} else {
return WEST;
}
}
}
/** Divides the two integers returning the floor of the divided value
* rather than its truncation. */
protected static int divFloor (int value, int divisor)
{
return (int)Math.floor((double)value/divisor);
}
// documentation inherited
public Dimension getPreferredSize ()
{
if (_tiles.size() == 0) {
return new Dimension(100, 100);
} else {
return new Dimension(TILE_WIDTH * _width, TILE_HEIGHT * _height);
}
}
/**
* Determines how big we want to be based on where the tiles have been
* laid out. This will cause the component to be re-layed out if the
* dimensions change or repainted if not.
*/
protected void computeDimensions ()
{
int maxX = 0, maxY = 0;
int minX = 0, minY = 0;
// if we have a recently placed tile, start with that one
if (_placedTile != null) {
minX = maxX = _placedTile.x;
minY = maxY = _placedTile.y;
}
// figure out what our boundaries are
int tsize = _tiles.size();
for (int i = 0; i < tsize; i++) {
VenisonTile tile = (VenisonTile)_tiles.get(i);
if (tile.x > maxX) {
maxX = tile.x;
} else if (tile.x < minX) {
minX = tile.x;
}
if (tile.y > maxY) {
maxY = tile.y;
} else if (tile.y < minY) {
minY = tile.y;
}
}
// spread our bounds out by one
minX -= 1; minY -= 1;
maxX += 1; maxY += 1;
// keep track of these to know if we've change dimensions
int oldOrigX = _origX, oldOrigY = _origY;
int oldWidth = _width, oldHeight = _height;
// now we can compute our width and the origin offset
_origX = -minX;
_origY = -minY;
_width = maxX - minX + 1;
_height = maxY - minY + 1;
if (_origX != oldOrigX || _origY != oldOrigY ||
oldWidth != _width || oldHeight != _height) {
// if the dimensions changed, we need to relayout
revalidate();
} else {
// otherwise just repaint
repaint();
}
}
/** Test code. */
public static void main (String[] args)
{
JFrame frame = new JFrame("Board test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
VenisonBoard board = new VenisonBoard();
TestDSet set = new TestDSet();
set.addTile(new VenisonTile(CITY_TWO, true, WEST, 0, 0));
set.addTile(new VenisonTile(CITY_TWO, false, WEST, -1, 1));
set.addTile(new VenisonTile(CITY_ONE, false, SOUTH, -1, -1));
VenisonTile zero = new VenisonTile(CURVED_ROAD, false, WEST, 0, 2);
set.addTile(zero);
VenisonTile one = new VenisonTile(TWO_CITY_TWO, false, NORTH, 0, 1);
set.addTile(one);
set.addTile(new VenisonTile(CITY_THREE, false, WEST, 1, 1));
set.addTile(new VenisonTile(CITY_THREE_ROAD, false, EAST, 1, 2));
set.addTile(new VenisonTile(CITY_THREE, false, NORTH, -1, 0));
VenisonTile two = new VenisonTile(CITY_ONE, false, EAST, -2, 0);
set.addTile(two);
board.setTiles(set);
VenisonTile placing = new VenisonTile(CITY_TWO, false, NORTH, 0, 0);
board.setTileToBePlaced(placing);
// set a feature group to test propagation
List tiles = new ArrayList();
CollectionUtil.addAll(tiles, set.elements());
Collections.sort(tiles);
zero.setPiecen(new Piecen(Piecen.GREEN, 0, 0, 2), tiles);
one.setPiecen(new Piecen(Piecen.BLUE, 0, 0, 0), tiles);
two.setPiecen(new Piecen(Piecen.RED, 0, 0, 1), tiles);
Log.info("Incomplete road: " +
TileUtil.computeFeatureScore(tiles, zero, 2));
Log.info("Completed city: " +
TileUtil.computeFeatureScore(tiles, two, 1));
Log.info("Incomplete city: " +
TileUtil.computeFeatureScore(tiles, one, 2));
frame.getContentPane().add(board, BorderLayout.CENTER);
frame.pack();
SwingUtil.centerWindow(frame);
frame.show();
}
protected static class TestDSet extends DSet
{
public TestDSet ()
{
super(VenisonTile.class);
}
public void addTile (VenisonTile tile)
{
add(tile);
}
}
/** A reference to our tile set. */
protected ArrayList _tiles = new ArrayList();
/** The tile currently being placed by the user. */
protected VenisonTile _placingTile;
/** The last tile being placed by the user. */
protected VenisonTile _placedTile;
/** The last tile placed on the board via {@link #addTile}. */
protected VenisonTile _lastPlacedTile;
/** A flag indicating whether or not we're placing a piecen. */
protected boolean _placingPiecen = false;
/** Whether or not the current position and orientation of the placing
* tile is valid. */
protected boolean _validPlacement = false;
/** An array indicating which of the four directions are valid
* placements based on the current position of the placing tile. */
protected boolean[] _validOrients;
/** The color to use when creating new piecens. */
protected int _newPiecenColor = Piecen.BLUE;
/** Our render offset in pixels. */
protected int _tx, _ty;
/** The offset in tile coordinates of the origin. */
protected int _origX, _origY;
/** The width and height of the board in tile coordinates. */
protected int _width, _height;
/** The last known position of the mouse. */
protected int _mouseX, _mouseY;
}
|
package ninja;
public class Results {
public static Result status(int statusCode) {
Result result = new Result(statusCode);
return result;
}
public static Result ok() {
return status(Result.SC_200_OK);
}
public static Result notFound() {
return status(Result.SC_404_NOT_FOUND);
}
public static Result forbidden() {
return status(Result.SC_403_FORBIDDEN);
}
public static Result badRequest() {
return status(Result.SC_400_BAD_REQUEST);
}
public static Result noContent() {
return status(Result.SC_204_NO_CONTENT);
}
public static Result internalServerError() {
return status(Result.SC_500_INTERNAL_SERVER_ERROR);
}
public static Result redirect(String url) {
Result result = status(Result.SC_307_TEMPORARY_REDIRECT);
result.addHeader(Result.LOCATION, url);
return result;
}
public static Result html() {
Result result = status(Result.SC_200_OK);
result.contentType(Result.TEXT_HTML);
return result;
}
public static Result contentType(String contentType) {
Result result = status(Result.SC_200_OK);
result.contentType(contentType);
return result;
}
public static Result html(int statusCode) {
Result result = status(statusCode);
result.contentType(Result.TEXT_HTML);
return result;
}
public static Result html(Object renderable) {
Result result = status(Result.SC_200_OK);
result.contentType(Result.TEXT_HTML);
result.render(renderable);
return result;
}
public static Result json(int statusCode) {
Result result = status(statusCode);
result.contentType(Result.APPLICATON_JSON);
return result;
}
public static Result json() {
Result result = status(Result.SC_200_OK);
result.contentType(Result.APPLICATON_JSON);
return result;
}
public static Result json(Object renderable) {
Result result = status(Result.SC_200_OK);
result.contentType(Result.APPLICATON_JSON);
result.render(renderable);
return result;
}
public static Result xml() {
Result result = status(Result.SC_200_OK);
result.contentType(Result.APPLICATION_XML);
return result;
}
public static Result TODO() {
Result result = status(Result.SC_501_NOT_IMPLEMENTED);
result.contentType(Result.APPLICATON_JSON);
return result;
}
public static AsyncResult async() {
return new AsyncResult();
}
}
|
package com.threerings.venison;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import com.samskivert.swing.Controller;
import com.samskivert.swing.ControllerProvider;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.VGroupLayout;
import com.threerings.resource.ResourceManager;
import com.threerings.media.ImageManager;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.client.PlaceView;
import com.threerings.parlor.util.ParlorContext;
import com.threerings.micasa.client.ChatPanel;
/**
* The top-level user interface component for the Venison game display.
*/
public class VenisonPanel
extends JPanel implements PlaceView, ControllerProvider, VenisonCodes
{
/** A reference to the board that is accessible to the controller. */
public VenisonBoard board;
/** A reference to our _noplace button. */
public JButton noplace;
/**
* Constructs a new Venison game display.
*/
public VenisonPanel (ParlorContext ctx, VenisonController controller)
{
// give ourselves a wee bit of a border
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
HGroupLayout gl = new HGroupLayout(HGroupLayout.STRETCH);
gl.setOffAxisPolicy(HGroupLayout.STRETCH);
setLayout(gl);
// create the board
board = new VenisonBoard();
// create a scroll area to contain the board
JScrollPane scrolly = new JScrollPane(board);
add(scrolly);
// create our side panel
VGroupLayout sgl = new VGroupLayout(VGroupLayout.STRETCH);
sgl.setOffAxisPolicy(VGroupLayout.STRETCH);
sgl.setJustification(VGroupLayout.TOP);
JPanel sidePanel = new JPanel(sgl);
// add a big fat label because we love it!
JLabel vlabel = new JLabel("Venison!");
vlabel.setFont(new Font("Helvetica", Font.BOLD, 24));
vlabel.setForeground(Color.black);
sidePanel.add(vlabel, VGroupLayout.FIXED);
// add a player info view to the side panel
sidePanel.add(new JLabel("Scores:"), VGroupLayout.FIXED);
sidePanel.add(new PlayerInfoView(), VGroupLayout.FIXED);
// add a turn indicator to the side panel
sidePanel.add(new JLabel("Current turn:"), VGroupLayout.FIXED);
sidePanel.add(new TurnIndicatorView(), VGroupLayout.FIXED);
// add a "place nothing" button
noplace = new JButton("Place nothing");
noplace.setEnabled(false);
noplace.setActionCommand(PLACE_NOTHING);
noplace.addActionListener(Controller.DISPATCHER);
sidePanel.add(noplace, VGroupLayout.FIXED);
// add a chat box
ChatPanel chat = new ChatPanel(ctx);
chat.removeSendButton();
sidePanel.add(chat);
// add a "back" button
JButton back = new JButton("Back to lobby");
back.setActionCommand(BACK_TO_LOBBY);
back.addActionListener(Controller.DISPATCHER);
sidePanel.add(back, VGroupLayout.FIXED);
// add our side panel to the main display
add(sidePanel, HGroupLayout.FIXED);
// we'll need this later to provide it
_controller = controller;
// we can't create our image manager until we have access to our
// containing frame
addAncestorListener(new AncestorListener() {
public void ancestorAdded (AncestorEvent event) {
// create our image manager
JRootPane rpane = getRootPane();
VenisonTile.setImageManager(
new ImageManager(_rmgr, (Frame)rpane.getParent()));
}
public void ancestorMoved (AncestorEvent event) {
}
public void ancestorRemoved (AncestorEvent event) {
}
});
}
// documentation inherited
public void willEnterPlace (PlaceObject plobj)
{
Log.info("Panel entered place.");
}
// documentation inherited
public void didLeavePlace (PlaceObject plobj)
{
Log.info("Panel left place.");
}
// documentation inherited
public Controller getController ()
{
return _controller;
}
/** A reference to our controller that we need to implement the {@link
* ControllerProvider} interface. */
protected VenisonController _controller;
// this stuff is all a bit of a hack right now. by all rights, the
// venison app should set up the resource manager, because it knows
// about that sort of stuff, and make it available via the venison
// context and we may have some better place for the image manager to
// live and the tile set would be fetched through the tile
// manager. but it's late and i want to get this working, so fooey.
/** Our resource manager. */
protected static ResourceManager _rmgr = new ResourceManager("rsrc");
}
|
package org.openprovenance.prov.json;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import org.openprovenance.prov.notation.Utility;
import org.openprovenance.prov.xml.Activity;
import org.openprovenance.prov.xml.ActivityRef;
import org.openprovenance.prov.xml.AgentRef;
import org.openprovenance.prov.xml.Document;
import org.openprovenance.prov.xml.EntityRef;
import org.openprovenance.prov.xml.GenerationRef;
import org.openprovenance.prov.xml.ProvFactory;
import org.openprovenance.prov.xml.Statement;
import org.openprovenance.prov.xml.UsageRef;
import org.openprovenance.prov.xml.Used;
import org.openprovenance.prov.xml.WasEndedBy;
import org.openprovenance.prov.xml.WasGeneratedBy;
import org.openprovenance.prov.xml.WasInvalidatedBy;
import org.openprovenance.prov.xml.WasStartedBy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
/**
* A JSON decoder for PROV-JSON
* Accepts a PROV-JSON string, produces a {@link Document}
* @author tdh
*
*/
public class ProvJSONDecoder {
/**
* @param args
*/
public static void main(String[] args) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Document.class, new ProvDocumentDeserializer());
Gson gson = gsonBuilder.create();
try {
Document provDoc = gson.fromJson(new BufferedReader(new FileReader(args[0])), Document.class);
Utility u = new Utility();
String provN = u.convertBeanToASN(provDoc);
System.out.println(provN);
} catch (Exception e) {
e.printStackTrace();
}
}
}
enum ProvStatement {
ENTITY,
ACTIVITY,
AGENT,
GENERATION,
USAGE,
COMMUNICATION,
START,
END,
INVALIDATION,
ATTRIBUTION,
ASSOCIATION,
DERIVATION,
DELEGATION,
ALTERNATE,
SPECIALIZATION,
MENTION,
COLLECTION,
MEMBERSHIP,
BUNDLE
}
class ProvDocumentDeserializer implements JsonDeserializer<Document> {
private static final String PROV_JSON_PREFIX = "prefix";
private static final String PROV_JSON_ENTITY = "entity";
private static final String PROV_JSON_ACTIVITY = "activity";
private static final String PROV_JSON_GENERATION = "wasGeneratedBy";
private static final String PROV_JSON_USAGE = "used";
private static final String PROV_JSON_COMMUNICATION = "wasInformedBy";
private static final String PROV_JSON_START = "wasStartedBy";
private static final String PROV_JSON_END = "wasEndedBy";
private static final String PROV_JSON_INVALIDATION = "wasInvalidatedBy";
private static final String PROV_JSON_DERIVATION = "wasDerivedFrom";
private static final String PROV_JSON_AGENT = "agent";
private static final String PROV_JSON_ATTRIBUTION = "wasAttributedTo";
private static final String PROV_JSON_ASSOCIATION = "wasAssociatedWith";
private static final String PROV_JSON_DELEGATION = "actedOnBehalfOf";
private static final String PROV_JSON_ALTERNATE = "alternateOf";
private static final String PROV_JSON_SPECIALIZATION = "specializationOf";
private static final String PROV_JSON_MENTION = "mentionOf";
private static final String PROV_JSON_COLLECTION = "collection";
private static final String PROV_JSON_MEMBERSHIP = "memberOf";
private static final String PROV_JSON_BUNDLE = "bundle";
private static final Map<String, ProvStatement> provTypeMap;
static {
Map<String, ProvStatement> map = new Hashtable<String, ProvStatement>();
map.put(PROV_JSON_ENTITY, ProvStatement.ENTITY);
map.put(PROV_JSON_ACTIVITY, ProvStatement.ACTIVITY);
map.put(PROV_JSON_GENERATION, ProvStatement.GENERATION);
map.put(PROV_JSON_USAGE, ProvStatement.USAGE);
map.put(PROV_JSON_COMMUNICATION, ProvStatement.COMMUNICATION);
map.put(PROV_JSON_START, ProvStatement.START);
map.put(PROV_JSON_END, ProvStatement.END);
map.put(PROV_JSON_INVALIDATION, ProvStatement.INVALIDATION);
map.put(PROV_JSON_DERIVATION, ProvStatement.DERIVATION);
map.put(PROV_JSON_AGENT, ProvStatement.AGENT);
map.put(PROV_JSON_ATTRIBUTION, ProvStatement.ATTRIBUTION);
map.put(PROV_JSON_ASSOCIATION, ProvStatement.ASSOCIATION);
map.put(PROV_JSON_DELEGATION, ProvStatement.DELEGATION);
map.put(PROV_JSON_ALTERNATE, ProvStatement.ALTERNATE);
map.put(PROV_JSON_SPECIALIZATION, ProvStatement.SPECIALIZATION);
map.put(PROV_JSON_MENTION, ProvStatement.MENTION);
map.put(PROV_JSON_COLLECTION, ProvStatement.COLLECTION);
map.put(PROV_JSON_MEMBERSHIP, ProvStatement.MEMBERSHIP);
map.put(PROV_JSON_BUNDLE, ProvStatement.BUNDLE);
provTypeMap = Collections.unmodifiableMap(map);
}
private final ProvFactory pf = new ProvFactory();
@Override
public Document deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject provJSONDoc = json.getAsJsonObject();
// Initialise namespaces
Hashtable<String, String> namespaces = new Hashtable<String, String>();
JsonObject prefixes = getObjectAndRemove(provJSONDoc, PROV_JSON_PREFIX);
if (prefixes != null) {
for (Map.Entry<String, JsonElement> pair: prefixes.entrySet()) {
namespaces.put(pair.getKey(), pair.getValue().getAsString());
}
pf.setNamespaces(namespaces);
}
// Decoding structures
List<Statement> statements = new ArrayList<Statement>();
for (Map.Entry<String, JsonElement> sPair: provJSONDoc.entrySet()) {
String statementType = sPair.getKey();
JsonObject statementMap = sPair.getValue().getAsJsonObject();
statements.addAll(decodeElements(statementType, statementMap));
}
// Create the document
Document doc = pf.newDocument();
doc.setNss(namespaces);
doc.getEntityOrActivityOrWasGeneratedBy().addAll(statements);
return doc;
}
private List<Statement> decodeElements(String statementType, JsonObject statementMap) {
List<Statement> statements = new ArrayList<Statement>();
for (Map.Entry<String, JsonElement> pair: statementMap.entrySet()) {
String idStr = pair.getKey();
JsonObject attributeMap = pair.getValue().getAsJsonObject();
Statement statement = decodeElement(statementType, idStr, attributeMap);
statements.add(statement);
}
return statements;
}
private Statement decodeElement(String statementType, String idStr, JsonObject attributeMap) {
Statement statement;
QName id;
if (idStr.startsWith("_:")) {
id = null;
}
else {
id = pf.stringToQName(idStr);
}
// Decoding attributes
switch (provTypeMap.get(statementType)) {
case ENTITY:
statement = pf.newEntity(id);
break;
case ACTIVITY:
XMLGregorianCalendar startTime = optionalTime("prov:startTime", attributeMap);
XMLGregorianCalendar endTime = optionalTime("prov:endTime", attributeMap);
Activity a = pf.newActivity(id);
if (startTime != null) {
a.setStartTime(startTime);
}
if (endTime != null) {
a.setEndTime(endTime);
}
statement = a;
break;
case AGENT:
statement = pf.newAgent(id);
break;
case ALTERNATE:
EntityRef alternate1 = entityRef("prov:alternate1", attributeMap);
EntityRef alternate2 = entityRef("prov:alternate2", attributeMap);
statement = pf.newAlternateOf(alternate2, alternate1);
break;
case ASSOCIATION:
ActivityRef activity = activityRef("prov:activity", attributeMap);
AgentRef agent = agentRef("prov:agent", attributeMap);
statement = pf.newWasAssociatedWith(id, activity, agent);
break;
case ATTRIBUTION:
EntityRef entity = entityRef("prov:entity", attributeMap);
agent = agentRef("prov:agent", attributeMap);
statement = pf.newWasAttributedTo(id, entity, agent);
break;
// TODO: Implement bundle decoding
// case BUNDLE:
// break;
// case COLLECTION:
// break;
case COMMUNICATION:
ActivityRef informed = activityRef("prov:informed", attributeMap);
ActivityRef informant = activityRef("prov:informant", attributeMap);
statement = pf.newWasInformedBy(id, informed, informant);
break;
case DELEGATION:
AgentRef delegate = agentRef("prov:delegate", attributeMap);
AgentRef responsible = agentRef("prov:responsible", attributeMap);
activity = optionalActivityRef("prov:activity", attributeMap);
statement = pf.newActedOnBehalfOf(id, delegate, responsible, activity);
break;
case DERIVATION:
EntityRef generatedEntity = entityRef("prov:generatedEntity", attributeMap);
EntityRef usedEntity = entityRef("prov:usedEntity", attributeMap);
activity = optionalActivityRef("prov:activity", attributeMap);
GenerationRef generation = optionalGenerationRef("prov:generation", attributeMap);
UsageRef usage = optionalUsageRef("prov:usage", attributeMap);
statement = pf.newWasDerivedFrom(id, generatedEntity, usedEntity, activity, generation, usage);
break;
case END:
activity = activityRef("prov:activity", attributeMap);
EntityRef trigger = optionalEntityRef("prov:trigger", attributeMap);
ActivityRef ender = optionalActivityRef("prov:ender", attributeMap);
XMLGregorianCalendar time = optionalTime("prov:time", attributeMap);
WasEndedBy wEB = pf.newWasEndedBy(id, activity, trigger);
if (ender != null)
wEB.setEnder(ender);
if (time != null) {
wEB.setTime(time);
}
statement = wEB;
break;
case GENERATION:
entity = entityRef("prov:entity", attributeMap);
activity = optionalActivityRef("prov:activity", attributeMap);
time = optionalTime("prov:time", attributeMap);
WasGeneratedBy wGB = pf.newWasGeneratedBy(id);
wGB.setEntity(entity);
if (activity != null)
wGB.setActivity(activity);
if (time != null) {
wGB.setTime(time);
}
statement = wGB;
break;
case INVALIDATION:
entity = entityRef("prov:entity", attributeMap);
activity = optionalActivityRef("prov:activity", attributeMap);
time = optionalTime("prov:time", attributeMap);
WasInvalidatedBy wIB = pf.newWasInvalidatedBy(id, entity, activity);
if (time != null) {
wIB.setTime(time);
}
statement = wIB;
break;
case MEMBERSHIP:
EntityRef collection = entityRef("prov:collection", attributeMap);
entity = entityRef("prov:entity", attributeMap);
statement = pf.newMembership(collection, entity);
break;
case MENTION:
EntityRef specificEntity = entityRef("prov:specificEntity", attributeMap);
EntityRef generalEntity = entityRef("prov:generalEntity", attributeMap);
EntityRef bundle = entityRef("prov:bundle", attributeMap);
statement = pf.newMentionOf(specificEntity, generalEntity, bundle);
break;
case SPECIALIZATION:
specificEntity = entityRef("prov:specificEntity", attributeMap);
generalEntity = entityRef("prov:generalEntity", attributeMap);
statement = pf.newSpecializationOf(specificEntity, generalEntity);
break;
case START:
activity = activityRef("prov:activity", attributeMap);
trigger = optionalEntityRef("prov:trigger", attributeMap);
ActivityRef starter = optionalActivityRef("prov:starter", attributeMap);
time = optionalTime("prov:time", attributeMap);
WasStartedBy wSB = pf.newWasStartedBy(id, activity, trigger);
if (starter != null)
wSB.setStarter(starter);
if (time != null) {
wSB.setTime(time);
}
statement = wSB;
break;
case USAGE:
activity = activityRef("prov:activity", attributeMap);
entity = optionalEntityRef("prov:entity", attributeMap);
time = optionalTime("prov:time", attributeMap);
Used wUB = pf.newUsed(id);
wUB.setActivity(activity);
if (entity != null)
wUB.setEntity(entity);
if (time != null) {
wUB.setTime(time);
}
statement = wUB;
break;
default:
statement = null;
break;
}
// TODO: implement prov:type decoding
// TODO: implement prov:label decoding
// TODO: implement arbitrary attribute decoding
return statement;
}
private String popString(JsonObject jo, String memberName) {
return jo.remove(memberName).getAsString();
}
private EntityRef entityRef(String attributeName, JsonObject attributeMap) {
return pf.newEntityRef(popString(attributeMap, attributeName));
}
private ActivityRef activityRef(String attributeName, JsonObject attributeMap) {
return pf.newActivityRef(popString(attributeMap, attributeName));
}
private AgentRef agentRef(String attributeName, JsonObject attributeMap) {
return pf.newAgentRef(popString(attributeMap, attributeName));
}
private EntityRef optionalEntityRef(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return entityRef(attributeName, attributeMap);
else
return null;
}
private ActivityRef optionalActivityRef(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return activityRef(attributeName, attributeMap);
else
return null;
}
private AgentRef optionalAgentRef(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return agentRef(attributeName, attributeMap);
else
return null;
}
private GenerationRef optionalGenerationRef(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return pf.newGenerationRef(popString(attributeMap, attributeName));
else
return null;
}
private UsageRef optionalUsageRef(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return pf.newUsageRef(popString(attributeMap, attributeName));
else
return null;
}
private XMLGregorianCalendar optionalTime(String attributeName, JsonObject attributeMap) {
if (attributeMap.has(attributeName))
return pf.newISOTime(popString(attributeMap, attributeName));
else
return null;
}
private JsonObject getObjectAndRemove(JsonObject jsonObject, String memberName) {
if (jsonObject.has(memberName)) {
JsonObject result = jsonObject.getAsJsonObject(memberName);
jsonObject.remove(memberName);
return result;
}
else return null;
}
}
|
package groovy.lang;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the variable bindings of a script which can be altered
* from outside the script object or created outside of a script and passed
* into it.
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class Binding extends GroovyObjectSupport {
private Map variables;
public Binding() {
variables = new HashMap();
}
public Binding(Map variables) {
this.variables = variables;
}
/**
* A helper constructor used in main(String[]) method calls
*
* @param args are the command line arguments from a main()
*/
public Binding(String[] args) {
this();
setVariable("args", args);
}
/**
* @param name the name of the variable to lookup
* @return the variable value
*/
public Object getVariable(String name) {
Object result = variables.get(name);
if (result == null && !variables.containsKey(name)) {
throw new MissingPropertyException("The property '" + name + "' is missing from the binding.",
name, Binding.class);
}
return result;
}
/**
* Sets the value of the given variable
* @param name the name of the variable to set
* @param value the new value for the given variable
*/
public void setVariable(String name, Object value) {
variables.put(name, value);
}
public Map getVariables() {
return variables;
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public Object getProperty(String property) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
return super.getProperty(property);
}
catch (MissingPropertyException e) {
return getVariable(property);
}
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public void setProperty(String property, Object newValue) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
super.setProperty(property, newValue);
}
catch (MissingPropertyException e) {
setVariable(property, newValue);
}
}
}
|
package com.jetbrains.python.inspections;
import com.google.common.collect.ImmutableMap;
import com.intellij.codeInspection.LocalInspectionToolSession;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.HashMap;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
/**
* @author Alexey.Ivanov
*/
public class PyStringFormatInspection extends PyInspection {
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.inspections.PyStringFormatInspection");
@Nls
@NotNull
@Override
public String getDisplayName() {
return PyBundle.message("INSP.NAME.str.format");
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly, @NotNull LocalInspectionToolSession session) {
return new Visitor(holder, session);
}
public static class Visitor extends PyInspectionVisitor {
private static class Inspection {
private static final ImmutableMap<Character, String> FORMAT_CONVERSIONS = ImmutableMap.<Character, String>builder()
.put('d', "int or long")
.put('i', "int or long")
.put('o', "int or long")
.put('u', "int or long")
.put('x', "int or long")
.put('X', "int or long")
.put('e', "float")
.put('E', "float")
.put('f', "float")
.put('F', "float")
.put('g', "float")
.put('G', "float")
.put('c', "str")
.put('r', "str")
.put('s', "str")
.build();
private final Map<String, Boolean> myUsedMappingKeys = new HashMap<String, Boolean>();
private int myExpectedArguments = 0;
private boolean myProblemRegister = false;
private final Visitor myVisitor;
private final TypeEvalContext myTypeEvalContext;
private final Map<String, String> myFormatSpec = new HashMap<String, String>();
public Inspection(Visitor visitor, TypeEvalContext typeEvalContext) {
myVisitor = visitor;
myTypeEvalContext = typeEvalContext;
}
// return number of arguments or -1 if it can not be computed
private int inspectArguments(@Nullable final PyExpression rightExpression, final PsiElement problemTarget) {
final Class[] SIMPLE_RHS_EXPRESSIONS = {
PyLiteralExpression.class, PySubscriptionExpression.class, PyBinaryExpression.class, PyConditionalExpression.class
};
final Class[] LIST_LIKE_EXPRESSIONS = {PyListLiteralExpression.class, PyListCompExpression.class};
final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(problemTarget);
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
if (PyUtil.instanceOf(rightExpression, SIMPLE_RHS_EXPRESSIONS)) {
if (myFormatSpec.get("1") != null) {
assert rightExpression != null;
PyType right_type = myTypeEvalContext.getType(rightExpression);
if (right_type instanceof PySubscriptableType) {
PySubscriptableType tuple_type = (PySubscriptableType)right_type;
for (int i=0; i <= tuple_type.getElementCount(); i += 1) {
PyType a_type = tuple_type.getElementType(i);
if (a_type != null) {
checkTypeCompatible(problemTarget, a_type, PyTypeParser.getTypeByName(problemTarget,
myFormatSpec.get(String.valueOf(i+1))));
}
}
return tuple_type.getElementCount();
}
else checkExpressionType(rightExpression, myFormatSpec.get("1"), problemTarget);
}
return 1;
}
else if (rightExpression instanceof PyReferenceExpression) {
if ("self.__dict__".equals(rightExpression.getText())) return -1;
final PsiElement pyElement = ((PyReferenceExpression)rightExpression).followAssignmentsChain(resolveContext).getElement();
if (!(pyElement instanceof PyExpression)) {
return -1;
}
if (pyElement instanceof PyDictLiteralExpression) {
return inspectDict(rightExpression, problemTarget, true);
}
return inspectArguments((PyExpression)pyElement, problemTarget);
}
else if (rightExpression instanceof PyCallExpression) {
final PyCallExpression.PyMarkedCallee markedFunction = ((PyCallExpression)rightExpression).resolveCallee(resolveContext);
if (markedFunction != null && !markedFunction.isImplicitlyResolved()) {
final Callable callable = markedFunction.getCallable();
// TODO: Switch to Callable.getReturnType()
if (callable instanceof PyFunction && myTypeEvalContext.maySwitchToAST((PyFunction) callable)) {
PyStatementList statementList = ((PyFunction)callable).getStatementList();
if (statementList == null) {
return -1;
}
PyReturnStatement[] returnStatements = PyUtil.getAllChildrenOfType(statementList, PyReturnStatement.class);
int expressionsSize = -1;
for (PyReturnStatement returnStatement : returnStatements) {
if (returnStatement.getExpression() instanceof PyCallExpression) {
return -1;
}
List<PyExpression> expressionList = PyUtil.flattenedParensAndTuples(returnStatement.getExpression());
if (expressionsSize < 0) {
expressionsSize = expressionList.size();
}
if (expressionsSize != expressionList.size()) {
return -1;
}
}
return expressionsSize;
}
}
return -1;
}
else if (rightExpression instanceof PyParenthesizedExpression) {
final PyExpression rhs = ((PyParenthesizedExpression)rightExpression).getContainedExpression();
return inspectArguments(rhs, rhs);
}
else if (rightExpression instanceof PyTupleExpression) {
final PyExpression[] expressions = ((PyTupleExpression)rightExpression).getElements();
int i = 1;
for (PyExpression expression : expressions) {
final String formatSpec = myFormatSpec.get(Integer.toString(i));
if (formatSpec != null) {
checkExpressionType(expression, formatSpec, expression);
}
++i;
}
return expressions.length;
}
else if (rightExpression instanceof PyDictLiteralExpression) {
return inspectDict(rightExpression, problemTarget, false);
}
else if (PyUtil.instanceOf(rightExpression, LIST_LIKE_EXPRESSIONS)) {
if (myFormatSpec.get("1") != null) {
checkTypeCompatible(problemTarget, builtinCache.getStrType(),
PyTypeParser.getTypeByName(problemTarget, myFormatSpec.get("1")));
return 1;
}
}
else if (rightExpression instanceof PySliceExpression) {
if (myFormatSpec.get("1") != null) {
PyType type = ((PySliceExpression)rightExpression).getOperand().getType(myTypeEvalContext);
if (type != null) {
if ("list".equals(type.getName()) || "str".equals(type.getName())) {
checkTypeCompatible(problemTarget, builtinCache.getStrType(),
PyTypeParser.getTypeByName(problemTarget, myFormatSpec.get("1")));
return 1;
}
}
PySliceItem sliceItem = ((PySliceExpression)rightExpression).getSliceItem();
if (sliceItem != null) {
PyExpression lower = sliceItem.getLowerBound();
PyExpression upper = sliceItem.getUpperBound();
PyExpression stride = sliceItem.getStride();
if (upper instanceof PyNumericLiteralExpression) {
BigInteger lowerVal;
if (lower instanceof PyNumericLiteralExpression ) {
lowerVal = ((PyNumericLiteralExpression)lower).getBigIntegerValue();
}
else {
lowerVal = BigInteger.ZERO;
}
int count = (((PyNumericLiteralExpression)upper).getBigIntegerValue().subtract(lowerVal)).intValue();
int strideVal;
if (stride instanceof PyNumericLiteralExpression)
strideVal = ((PyNumericLiteralExpression)stride).getBigIntegerValue().intValue();
else
strideVal = 1;
int res = count/strideVal;
int residue = count%strideVal == 0 ? 0 : 1;
return res + residue;
}
}
return -1;
}
}
return -1;
}
private static Map<PyExpression, PyExpression> addSubscriptions(PsiFile file, String operand) {
Map<PyExpression, PyExpression> additionalExpressions = new HashMap<PyExpression,PyExpression>();
PySubscriptionExpression[] subscriptionExpressions = PyUtil.getAllChildrenOfType(file, PySubscriptionExpression.class);
for (PySubscriptionExpression expr : subscriptionExpressions) {
if (expr.getOperand().getText().equals(operand)) {
PsiElement parent = expr.getParent();
if (parent instanceof PyAssignmentStatement) {
if (expr.equals(((PyAssignmentStatement)parent).getLeftHandSideExpression())) {
PyExpression key = expr.getIndexExpression();
if (key != null) {
additionalExpressions.put(key, ((PyAssignmentStatement)parent).getAssignedValue());
}
}
}
}
}
return additionalExpressions;
}
// inspects dict expressions. Finds key-value pairs from subscriptions if addSubscriptions is true.
private int inspectDict(PyExpression rightExpression, PsiElement problemTarget, boolean addSubscriptions) {
PsiElement pyElement;
Map<PyExpression, PyExpression> additionalExpressions;
if (addSubscriptions) {
additionalExpressions = addSubscriptions(rightExpression.getContainingFile(),
rightExpression.getText());
pyElement = ((PyReferenceExpression)rightExpression).followAssignmentsChain(PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)).getElement();
}
else {
additionalExpressions = new HashMap<PyExpression,PyExpression>();
pyElement = rightExpression;
}
final PyKeyValueExpression[] expressions = ((PyDictLiteralExpression)pyElement).getElements();
if (myUsedMappingKeys.isEmpty()) {
if (myExpectedArguments > 0) {
if (myExpectedArguments == (expressions.length + additionalExpressions.size())) {
// probably "%s %s" % {'a':1, 'b':2}, with names forgotten in template
registerProblem(rightExpression, PyBundle.message("INSP.format.requires.no.mapping"));
}
else {
// "braces: %s" % {'foo':1} gives "braces: {'foo':1}", implicit str() kicks in
return 1;
}
}
else {
// "foo" % {whatever} is just "foo"
return 0;
}
}
for (PyKeyValueExpression expression : expressions) {
final PyExpression key = expression.getKey();
if (key instanceof PyStringLiteralExpression) {
final String name = ((PyStringLiteralExpression)key).getStringValue();
if (myUsedMappingKeys.get(name) != null) {
myUsedMappingKeys.put(name, true);
final PyExpression value = expression.getValue();
if (value != null) {
checkExpressionType(value, myFormatSpec.get(name), problemTarget);
}
}
}
}
for (Map.Entry<PyExpression, PyExpression> expression : additionalExpressions.entrySet()) {
final PyExpression key = expression.getKey();
if (key instanceof PyStringLiteralExpression) {
final String name = ((PyStringLiteralExpression)key).getStringValue();
if (myUsedMappingKeys.get(name) != null) {
myUsedMappingKeys.put(name, true);
final PyExpression value = expression.getValue();
if (value != null) {
checkExpressionType(value, myFormatSpec.get(name), problemTarget);
}
}
}
}
for (String key : myUsedMappingKeys.keySet()) {
if (!myUsedMappingKeys.get(key).booleanValue()) {
registerProblem(problemTarget, PyBundle.message("INSP.key.$0.has.no.arg", key));
break;
}
}
return (expressions.length + additionalExpressions.size());
}
private void registerProblem(@NotNull PsiElement problemTarget, @NotNull final String message) {
myProblemRegister = true;
myVisitor.registerProblem(problemTarget, message);
}
private void checkExpressionType(@NotNull final PyExpression expression, @NotNull final String expectedTypeName, PsiElement problemTarget) {
final PyType actual = myTypeEvalContext.getType(expression);
final PyType expected = PyTypeParser.getTypeByName(problemTarget, expectedTypeName);
if (actual != null && !(actual instanceof PyTypeReference)) {
checkTypeCompatible(problemTarget, actual, expected);
}
}
private void checkTypeCompatible(@NotNull final PsiElement problemTarget,
@Nullable final PyType actual,
@Nullable final PyType expected) {
if (expected != null && "str".equals(expected.getName())) {
return;
}
if (actual != null && !PyTypeChecker.match(expected, actual, myTypeEvalContext)) {
registerProblem(problemTarget, PyBundle.message("INSP.unexpected.type.$0", actual.getName()));
}
}
private void inspectFormat(@NotNull final PyStringLiteralExpression formatExpression) {
PyStringFormatParser parser = new PyStringFormatParser(formatExpression.getStringValue());
final List<PyStringFormatParser.SubstitutionChunk> chunks = parser.parseSubstitutions();
// 1. The '%' character
// Skip the first item in the sections, it's always empty
myExpectedArguments = chunks.size();
myUsedMappingKeys.clear();
// if use mapping keys
final boolean mapping = chunks.size() > 0 && chunks.get(0).getMappingKey() != null;
for (int i = 0; i < chunks.size(); ++i) {
PyStringFormatParser.SubstitutionChunk chunk = chunks.get(i);
// 2. Mapping key
String mappingKey = Integer.toString(i+1);
if (mapping) {
if (chunk.getMappingKey() == null || chunk.isUnclosedMapping()) {
registerProblem(formatExpression, PyBundle.message("INSP.too.few.keys"));
break;
}
mappingKey = chunk.getMappingKey();
myUsedMappingKeys.put(mappingKey, false);
}
// 4. Minimum field width
inspectWidth(formatExpression, chunk.getWidth());
// 5. Precision
inspectWidth(formatExpression, chunk.getPrecision());
// 7. Format specifier
if (FORMAT_CONVERSIONS.containsKey(chunk.getConversionType())) {
myFormatSpec.put(mappingKey, FORMAT_CONVERSIONS.get(chunk.getConversionType()));
continue;
}
registerProblem(formatExpression, PyBundle.message("INSP.no.format.specifier.char"));
}
}
private void inspectWidth(@NotNull final PyStringLiteralExpression formatExpression, String width) {
if ("*".equals(width)){
++myExpectedArguments;
if (myUsedMappingKeys.size() > 0) {
registerProblem(formatExpression, "Can't use \'*\' in formats when using a mapping");
}
}
}
public boolean isProblem() {
return myProblemRegister;
}
private void inspectValues(@Nullable final PyExpression rightExpression) {
if (rightExpression == null) {
return;
}
if (rightExpression instanceof PyParenthesizedExpression) {
inspectValues(((PyParenthesizedExpression)rightExpression).getContainedExpression());
}
else {
final PyType type = myTypeEvalContext.getType(rightExpression);
if (type != null) {
if (myUsedMappingKeys.size() > 0 && !("dict".equals(type.getName()))) {
registerProblem(rightExpression, PyBundle.message("INSP.format.requires.mapping"));
return;
}
}
inspectArgumentsNumber(rightExpression);
}
}
private void inspectArgumentsNumber(@NotNull final PyExpression rightExpression) {
final int arguments = inspectArguments(rightExpression, rightExpression);
if (myUsedMappingKeys.isEmpty() && arguments >= 0) {
if (myExpectedArguments < arguments) {
registerProblem(rightExpression, PyBundle.message("INSP.too.many.args.for.fmt.string"));
}
else if (myExpectedArguments > arguments) {
registerProblem(rightExpression, PyBundle.message("INSP.too.few.args.for.fmt.string"));
}
}
}
}
public Visitor(final ProblemsHolder holder, LocalInspectionToolSession session) {
super(holder, session);
}
@Override
public void visitPyBinaryExpression(final PyBinaryExpression node) {
if (node.getLeftExpression() instanceof PyStringLiteralExpression && node.isOperator("%")) {
final Inspection inspection = new Inspection(this, myTypeEvalContext);
final PyStringLiteralExpression literalExpression = (PyStringLiteralExpression)node.getLeftExpression();
inspection.inspectFormat(literalExpression);
if (inspection.isProblem()) {
return;
}
inspection.inspectValues(node.getRightExpression());
}
}
}
}
|
package net.java.sip.communicator.util;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
import net.java.sip.communicator.util.swing.*;
/**
* Utility methods for image manipulation.
*
* @author Sebastien Mazy
* @author Yana Stamcheva
* @author Lubomir Marinov
*/
public class ImageUtils
{
private static final Logger logger = Logger.getLogger(ImageUtils.class);
/**
* Returns a scaled image fitting within the given bounds while keeping the
* aspect ratio.
*
* @param image the image to scale
* @param width maximum width of the scaled image
* @param height maximum height of the scaled image
* @return the scaled image
*/
public static Image scaleImageWithinBounds( Image image,
int width,
int height)
{
int initialWidth = image.getWidth(null);
int initialHeight = image.getHeight(null);
Image scaledImage;
int scaleHint = Image.SCALE_SMOOTH;
double originalRatio =
(double) initialWidth / initialHeight;
double areaRatio = (double) width / height;
if(originalRatio > areaRatio)
scaledImage = image.getScaledInstance(width, -1, scaleHint);
else
scaledImage = image.getScaledInstance(-1, height, scaleHint);
return scaledImage;
}
/**
* Returns the scaled icon.
* @param image the image to scale
* @param width the desired width after the scale
* @param height the desired height after the scale
* @return the scaled icon
*/
public static ImageIcon scaleIconWithinBounds(Image image, int width,
int height)
{
return new ImageIcon(scaleImageWithinBounds(image, width, height));
}
/**
* Creates a rounded avatar image.
*
* @param image image of the initial avatar image.
* @param width the desired result width
* @param height the desired result height
* @return the rounded corner image
*/
public static Image getScaledRoundedImage(Image image, int width, int height)
{
ImageIcon scaledImage =
ImageUtils.scaleIconWithinBounds(image, width, height);
int scaledImageWidth = scaledImage.getIconWidth();
int scaledImageHeight = scaledImage.getIconHeight();
if(scaledImageHeight <= 0 ||
scaledImageWidth <= 0)
return null;
RoundRectangle2D roundRect
= new RoundRectangle2D.Double(
0, 0, scaledImageWidth, scaledImageHeight, 10, 10);
int type = BufferedImage.TYPE_INT_ARGB_PRE;
BufferedImage dstImage
= new BufferedImage(scaledImageWidth, scaledImageHeight, type);
Graphics2D g = dstImage.createGraphics();
try
{
AntialiasingManager.activateAntialiasing(g);
g.setClip(roundRect);
g.drawImage(scaledImage.getImage(), 0, 0, null);
}
finally
{
g.dispose();
}
return dstImage;
}
/**
* Returns the scaled image in byte array.
* @param image the image to scale
* @param width the desired width after the scale
* @param height the desired height after the scale
* @return the scaled image in byte array
*/
public static byte[] getScaledInstanceInBytes(
Image image, int width, int height)
{
byte[] scaledBytes = null;
BufferedImage scaledImage
= (BufferedImage) getScaledRoundedImage(image, width, height);
if (scaledImage != null)
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
try
{
ImageIO.write(scaledImage, "png", outStream);
scaledBytes = outStream.toByteArray();
}
catch (IOException e)
{
logger.debug("Could not scale image in bytes.", e);
}
}
return scaledBytes;
}
/**
* Returns a scaled rounded icon from the given <tt>image</tt>, scaled
* within the given <tt>width</tt> and <tt>height</tt>.
* @param image the image to scale
* @param width the maximum width of the scaled icon
* @param height the maximum height of the scaled icon
* @return a scaled rounded icon
*/
public static ImageIcon getScaledRoundedIcon(Image image, int width,
int height)
{
Image scaledImage = getScaledRoundedImage(image, width, height);
if (scaledImage != null)
return new ImageIcon(scaledImage);
return null;
}
/**
* Creates a rounded corner scaled image.
*
* @param imageBytes The bytes of the image to be scaled.
* @param width The maximum width of the scaled image.
* @param height The maximum height of the scaled image.
*
* @return The rounded corner scaled image.
*/
public static ImageIcon getScaledRoundedIcon( byte[] imageBytes,
int width,
int height)
{
if (imageBytes == null || !(imageBytes.length > 0))
return null;
ImageIcon imageIcon = null;
try
{
Image image = null;
// sometimes ImageIO fails, will fall back to awt Toolkit
try
{
image = ImageIO.read(new ByteArrayInputStream(imageBytes));
} catch (Exception e)
{
try
{
image = Toolkit.getDefaultToolkit().createImage(imageBytes);
} catch (Exception e1)
{
// if it fails throw the original exception
throw e;
}
}
if(image != null)
imageIcon = getScaledRoundedIcon(image, width, height);
else
logger.trace("Unknown image format or error reading image");
}
catch (Exception e)
{
logger.debug("Could not create image.", e);
}
return imageIcon;
}
/**
* Returns the buffered image corresponding to the given url image path.
*
* @param imagePath the path indicating, where we can find the image.
*
* @return the buffered image corresponding to the given url image path.
*/
public static BufferedImage getBufferedImage(URL imagePath)
{
BufferedImage image = null;
if (imagePath != null)
{
try
{
image = ImageIO.read(imagePath);
}
catch (IOException ex)
{
logger.debug("Failed to load image:" + imagePath, ex);
}
}
return image;
}
}
|
package net.mcft.copy.backpacks.proxy;
import java.util.Map;
import java.util.Map.Entry;
import net.mcft.copy.backpacks.WearableBackpacks;
import net.mcft.copy.backpacks.api.BackpackHelper;
import net.mcft.copy.backpacks.api.BackpackRegistry;
import net.mcft.copy.backpacks.api.IBackpack;
import net.mcft.copy.backpacks.api.IBackpackData;
import net.mcft.copy.backpacks.api.IBackpackProperties;
import net.mcft.copy.backpacks.container.SlotArmorBackpack;
import net.mcft.copy.backpacks.entity.BackpackProperties;
import net.mcft.copy.core.container.ContainerBase;
import net.mcft.copy.core.container.ContainerRegistry;
import net.mcft.copy.core.misc.BlockLocation;
import net.mcft.copy.core.misc.EquipmentSlot;
import net.mcft.copy.core.util.EntityUtils;
import net.mcft.copy.core.util.RandomUtils;
import net.mcft.copy.core.util.StackUtils;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.living.LivingSpawnEvent.SpecialSpawn;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class CommonProxy {
public void init() {
MinecraftForge.EVENT_BUS.register(this);
FMLCommonHandler.instance().bus().register(this);
ContainerRegistry.register(ContainerBase.class);
// TODO: Register entities to spawn with backpacks.
// BackpackRegistry.registerBackpackEntity(EntityZombie.class, backpack, 1.0 / 800);
// BackpackRegistry.registerBackpackEntity(EntitySkeleton.class, backpack, 1.0 / 1200);
// BackpackRegistry.registerBackpackEntity(EntityPigZombie.class, backpack, 1.0 / 1000);
// BackpackRegistry.registerBackpackEntity(EntityEnderman.class, backpack, 1.0 / 80);
}
@SubscribeEvent
public void onEntityContructing(EntityConstructing event) {
if (!(event.entity instanceof EntityLivingBase)) return;
EntityLivingBase entity = (EntityLivingBase)event.entity;
// Give entities that can support backpacks the backpack properties.
if (BackpackRegistry.canEntityWearBackpacks(entity))
EntityUtils.createProperties(entity, BackpackProperties.class);
}
@SubscribeEvent
public void onPlayerInteract(PlayerInteractEvent event) {
// When players sneak-right-click the ground with an
// empty hand, place down their equipped backpack.
EntityPlayer player = event.entityPlayer;
if ((event.action != Action.RIGHT_CLICK_BLOCK) || !player.isSneaking() ||
(player.getEquipmentInSlot(EquipmentSlot.HELD) != null)) return;
ItemStack backpack = BackpackHelper.getEquippedBackpack(player);
if (backpack == null) return;
backpack.tryPlaceItemIntoWorld(player, player.worldObj,
event.x, event.y, event.z, event.face,
0.5F, 0.5F, 0.5F);
if (backpack.stackSize <= 0) {
BlockLocation block = BlockLocation.get(player.worldObj, event.x, event.y + 1, event.z);
TileEntity tileEntity = block.getTileEntity();
if (tileEntity instanceof IBackpackProperties) {
IBackpack backpackType = BackpackHelper.getBackpackType(backpack);
IBackpackData backpackData = BackpackHelper.getEquippedBackpackData(player);
if ((backpackData == null) && !player.worldObj.isRemote) {
WearableBackpacks.log.error("Backpack data was null when placing down backpack");
backpackData = backpackType.createBackpackData();
}
IBackpackProperties backpackTileEntity = (IBackpackProperties)tileEntity;
backpackTileEntity.setBackpackStack(StackUtils.copy(backpack, 1));
backpackTileEntity.setBackpackData(backpackData);
backpackType.onUnequip(player, cast(tileEntity));
if (!player.worldObj.isRemote) {
BackpackHelper.setEquippedBackpack(player, null, null);
player.inventoryContainer.detectAndSendChanges();
}
} else WearableBackpacks.log.error("TileEntity at {} is not an IBackpackTileEntity", block);
}
}
/** Just a helper method to get the TileEntity to also be an IBackpackProperties. */
private static <T extends TileEntity & IBackpackProperties> T cast(TileEntity tileEntity) { return (T)tileEntity; }
@SubscribeEvent
public void onEntityInteract(EntityInteractEvent event) {
// When players right click equipped backpacks, interact with them.
if (!(event.target instanceof EntityLivingBase)) return;
EntityPlayer player = event.entityPlayer;
EntityLivingBase target = (EntityLivingBase)event.target;
ItemStack backpack = BackpackHelper.getEquippedBackpack(target);
if ((backpack == null) || !BackpackHelper.canInteractWithEquippedBackpack(player, target)) return;
IBackpack backpackType = BackpackHelper.getBackpackType(backpack);
IBackpackProperties properties = BackpackHelper.getBackpackProperties(target);
if ((properties.getBackpackData() == null) && !player.worldObj.isRemote) {
WearableBackpacks.log.error("Backpack data was null when placing accessing equipped backpack");
properties.setBackpackData(backpackType.createBackpackData());
}
backpackType.onEquippedInteract(player, target);
}
@SubscribeEvent
public void onSpecialSpawn(SpecialSpawn event) {
// When an entity spawns naturally, check to see
// if it should spawn with a backpack.
EntityLivingBase entity = event.entityLiving;
Map<Item, Double> chances = BackpackRegistry.entities.get(entity.getClass());
if ((chances == null) || chances.isEmpty()) return;
for (Entry<Item, Double> entry : chances.entrySet())
if (RandomUtils.getBoolean(entry.getValue())) {
ItemStack stack = new ItemStack(entry.getKey());
IBackpack backpackType = BackpackHelper.getBackpackType(stack);
IBackpackData data = backpackType.createBackpackData();
BackpackHelper.setEquippedBackpack(entity, stack, data);
backpackType.onSpawnedWith(entity);
}
}
@SubscribeEvent
public void onLivingUpdate(LivingUpdateEvent event) {
// Update equipped backpacks and check
// if they've been removed somehow.
EntityLivingBase entity = event.entityLiving;
if (!BackpackRegistry.canEntityWearBackpacks(entity)) return;
EntityPlayer player = ((entity instanceof EntityPlayer) ? (EntityPlayer)entity : null);
ItemStack backpack = BackpackHelper.getEquippedBackpack(entity);
BackpackProperties properties =
(BackpackProperties)BackpackHelper.getBackpackProperties(entity);
properties.update();
if (backpack != null) {
IBackpack backpackItem = BackpackHelper.getBackpackType(backpack);
backpackItem.onEquippedTick(entity);
replaceChestArmorSlot(player, backpack);
if (entity.worldObj.isRemote)
BackpackHelper.updateLidTicks(properties, entity.posX, entity.posY + 1.0, entity.posZ);
} else if ((BackpackHelper.getEquippedBackpackData(entity) != null) &&
(properties.getLastBackpackType() != null)) {
// Backpack has been removed somehow.
properties.getLastBackpackType().onFaultyRemoval(entity);
properties.setLastBackpackType(null);
}
}
@SubscribeEvent
public void onLivingDeath(LivingDeathEvent event) {
ItemStack backpack = BackpackHelper.getEquippedBackpack(event.entityLiving);
if (backpack != null)
BackpackHelper.getBackpackType(backpack).onDeath(event.entityLiving);
}
/** Replaces the chest armor slot with one that prevents
* backpacks from being taken out, if necessary. */
private static void replaceChestArmorSlot(EntityPlayer player, ItemStack backpack) {
if ((player == null) || (player.getEquipmentInSlot(EquipmentSlot.CHEST) != backpack)) return;
Slot slot = player.inventoryContainer.getSlot(6);
if (slot instanceof SlotArmorBackpack) return;
Slot newSlot = new SlotArmorBackpack(slot.inventory, slot.getSlotIndex(),
slot.xDisplayPosition, slot.yDisplayPosition);
newSlot.slotNumber = slot.slotNumber;
player.inventoryContainer.inventorySlots.set(slot.slotNumber, newSlot);
}
}
|
package org.apache.xerces.impl.xs;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.grammars.XMLGrammarLoader;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.Grammar;
import org.xml.sax.InputSource;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.xs.models.CMBuilder;
import org.apache.xerces.impl.xs.traversers.XSDHandler;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.util.DefaultErrorHandler;
import java.util.Locale;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* This class implements XMLGrammarLoader. It is designed to interact
* either with a proxy for a user application which wants to preparse schemas,
* or with our own Schema validator. It is hoped that none of these "external"
* classes will therefore need to communicate directly
* with XSDHandler in future.
* <p>This class only knows how to make XSDHandler do its thing.
* The caller must ensure that all its properties (schemaLocation, JAXPSchemaSource
* etc.) have been properly set.
*
* @author Neil Graham, IBM
* @version $Id$
*/
public class XMLSchemaLoader implements XMLGrammarLoader {
// Feature identifiers:
/** Feature identifier: schema full checking*/
protected static final String SCHEMA_FULL_CHECKING =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING;
/** Feature identifier: continue after fatal error. */
protected static final String CONTINUE_AFTER_FATAL_ERROR =
Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE;
// recognized features:
private static final String[] RECOGNIZED_FEATURES = {
SCHEMA_FULL_CHECKING,
CONTINUE_AFTER_FATAL_ERROR,
};
// property identifiers
/** Property identifier: symbol table. */
public static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
public static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: error handler. */
protected static final String ERROR_HANDLER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Property identifier: entity resolver. */
public static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Property identifier: grammar pool. */
public static final String XMLGRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Property identifier: schema location. */
protected static final String SCHEMA_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION;
/** Property identifier: no namespace schema location. */
protected static final String SCHEMA_NONS_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION;
/** Property identifier: JAXP schema source. */
protected static final String JAXP_SCHEMA_SOURCE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE;
// recognized properties
private static final String [] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
ERROR_HANDLER,
ENTITY_RESOLVER,
XMLGRAMMAR_POOL,
SCHEMA_LOCATION,
SCHEMA_NONS_LOCATION,
JAXP_SCHEMA_SOURCE,
};
// Data
// is Schema Full Checking enabled
private boolean fIsCheckedFully = false;
private SymbolTable fSymbolTable = null;
private XMLErrorReporter fErrorReporter = new XMLErrorReporter ();
private XMLEntityResolver fEntityResolver = null;
private XMLGrammarPool fGrammarPool = null;
private String fExternalSchemas = null;
private String fExternalNoNSSchema = null;
private Object fJAXPSource = null;
private Locale fLocale = Locale.getDefault();
private XSDHandler fSchemaHandler;
// the grammar bucket
private XSGrammarBucket fGrammarBucket;
private XSDeclarationPool fDeclPool = null;
private SubstitutionGroupHandler fSubGroupHandler;
private CMBuilder fCMBuilder;
// boolean that tells whether we've tested the JAXP property.
private boolean fJAXPProcessed = false;
// containers
private XSDDescription fXSDDescription = new XSDDescription();
// default constructor. Create objects we absolutely need:
public XMLSchemaLoader() {
this( new SymbolTable(), null, new XMLEntityManager(), null, null, null);
}
public XMLSchemaLoader(SymbolTable symbolTable) {
this( symbolTable, null, new XMLEntityManager(), null, null, null);
}
XMLSchemaLoader(XMLErrorReporter errorReporter,
XSGrammarBucket grammarBucket,
SubstitutionGroupHandler sHandler, CMBuilder builder) {
this(null, errorReporter, null, grammarBucket, sHandler, builder);
}
XMLSchemaLoader(SymbolTable symbolTable,
XMLErrorReporter errorReporter,
XMLEntityResolver entityResolver,
XSGrammarBucket grammarBucket,
SubstitutionGroupHandler sHandler,
CMBuilder builder) {
fSymbolTable = symbolTable;
if(errorReporter == null) {
errorReporter = new XMLErrorReporter ();
errorReporter.setProperty(ERROR_HANDLER, new DefaultErrorHandler());
}
fErrorReporter = errorReporter;
fEntityResolver = entityResolver;
if(grammarBucket == null ) {
grammarBucket = new XSGrammarBucket();
}
fGrammarBucket = grammarBucket;
if(sHandler == null) {
sHandler = new SubstitutionGroupHandler(fGrammarBucket);
}
fSubGroupHandler = sHandler;
if(builder == null) {
builder = new CMBuilder();
}
fCMBuilder = builder;
fSchemaHandler = new XSDHandler(fGrammarBucket);
fDeclPool = new XSDeclarationPool();
}
/**
* Returns a list of feature identifiers that are recognized by
* this XMLGrammarLoader. This method may return null if no features
* are recognized.
*/
public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone());
} // getRecognizedFeatures(): String[]
/**
* Returns the state of a feature.
*
* @param featureId The feature identifier.
*
* @throws XMLConfigurationException Thrown on configuration error.
*/
public boolean getFeature(String featureId)
throws XMLConfigurationException {
if(featureId.equals(SCHEMA_FULL_CHECKING)) {
return fIsCheckedFully;
} else if(featureId.equals(CONTINUE_AFTER_FATAL_ERROR)) {
return fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR);
}
throw new XMLConfigurationException(XMLConfigurationException.NOT_RECOGNIZED, featureId);
} // getFeature (String): boolean
/**
* Sets the state of a feature.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws XMLConfigurationException Thrown when a feature is not
* recognized or cannot be set.
*/
public void setFeature(String featureId,
boolean state) throws XMLConfigurationException {
if(featureId.equals(SCHEMA_FULL_CHECKING)) {
fIsCheckedFully = state;
} else if(featureId.equals(CONTINUE_AFTER_FATAL_ERROR)) {
fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, state);
} else {
throw new XMLConfigurationException(XMLConfigurationException.NOT_RECOGNIZED, featureId);
}
} // setFeature(String, boolean)
/**
* Returns a list of property identifiers that are recognized by
* this XMLGrammarLoader. This method may return null if no properties
* are recognized.
*/
public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone());
} // getRecognizedProperties(): String[]
/**
* Returns the state of a property.
*
* @param propertyId The property identifier.
*
* @throws XMLConfigurationException Thrown on configuration error.
*/
public Object getProperty(String propertyId)
throws XMLConfigurationException {
if(propertyId.equals( SYMBOL_TABLE)) {
return fSymbolTable;
} else if(propertyId.equals( ERROR_REPORTER)) {
return fErrorReporter;
} else if(propertyId.equals( ERROR_HANDLER)) {
return fErrorReporter.getErrorHandler();
} else if(propertyId.equals( ENTITY_RESOLVER)) {
return fEntityResolver;
} else if(propertyId.equals( XMLGRAMMAR_POOL)) {
return fGrammarPool;
} else if(propertyId.equals( SCHEMA_LOCATION)) {
return fExternalSchemas;
} else if(propertyId.equals( SCHEMA_NONS_LOCATION) ){
return fExternalNoNSSchema;
} else if(propertyId.equals( JAXP_SCHEMA_SOURCE)) {
return fJAXPSource;
}
throw new XMLConfigurationException(XMLConfigurationException.NOT_RECOGNIZED, propertyId);
} // getProperty(String): Object
/**
* Sets the state of a property.
*
* @param propertyId The property identifier.
* @param state The state of the property.
*
* @throws XMLConfigurationException Thrown when a property is not
* recognized or cannot be set.
*/
public void setProperty(String propertyId,
Object state) throws XMLConfigurationException, ClassCastException {
if(propertyId.equals( SYMBOL_TABLE)) {
fSymbolTable = (SymbolTable)state;
} else if(propertyId.equals( ERROR_REPORTER)) {
fErrorReporter = (XMLErrorReporter)state;
} else if(propertyId.equals( ERROR_HANDLER)) {
fErrorReporter.setProperty(propertyId, state);
} else if(propertyId.equals( ENTITY_RESOLVER)) {
fEntityResolver = (XMLEntityResolver)state;
} else if(propertyId.equals( XMLGRAMMAR_POOL)) {
fGrammarPool = (XMLGrammarPool)state;
} else if(propertyId.equals( SCHEMA_LOCATION)) {
fExternalSchemas = (String)state;
} else if(propertyId.equals( SCHEMA_NONS_LOCATION)) {
fExternalNoNSSchema = (String)state;
} else if(propertyId.equals( JAXP_SCHEMA_SOURCE)) {
fJAXPSource = state;
fJAXPProcessed = false;
} else
throw new XMLConfigurationException(XMLConfigurationException.NOT_RECOGNIZED, propertyId);
} // setProperty(String, Object)
/**
* Set the locale to use for messages.
*
* @param locale The locale object to use for localization of messages.
*
* @exception XNIException Thrown if the parser does not support the
* specified locale.
*/
public void setLocale(Locale locale) {
fLocale = locale;
} // setLocale(Locale)
/** Return the Locale the XMLGrammarLoader is using. */
public Locale getLocale() {
return fLocale;
} // getLocale(): Locale
/**
* Sets the error handler.
*
* @param errorHandler The error handler.
*/
public void setErrorHandler(XMLErrorHandler errorHandler) {
fErrorReporter.setProperty(ERROR_HANDLER, errorHandler);
} // setErrorHandler(XMLErrorHandler)
/** Returns the registered error handler. */
public XMLErrorHandler getErrorHandler() {
return fErrorReporter.getErrorHandler();
} // getErrorHandler(): XMLErrorHandler
/**
* Sets the entity resolver.
*
* @param entityResolver The new entity resolver.
*/
public void setEntityResolver(XMLEntityResolver entityResolver) {
fEntityResolver = entityResolver;
} // setEntityResolver(XMLEntityResolver)
/** Returns the registered entity resolver. */
public XMLEntityResolver getEntityResolver() {
return fEntityResolver;
} // getEntityResolver(): XMLEntityResolver
// reset all objects that "belong" to this one.
public void reset () {
fGrammarBucket.reset();
//we should retreive the initial grammar set given by the application
//to the parser and put it in local grammar bucket.
// make sure error reporter knows about schemas...
if(fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) {
fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter());
}
if(fGrammarPool != null) {
Grammar [] initialGrammars = fGrammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
for (int i = 0; i < initialGrammars.length; i++) {
// put this grammar into the bucket, along with grammars
// imported by it (directly or indirectly)
if (!fGrammarBucket.putGrammar((SchemaGrammar)(initialGrammars[i]), true)) {
// REVISIT: a conflict between new grammar(s) and grammars
// in the bucket. What to do? A warning? An exception?
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"GrammarConflict", null,
XMLErrorReporter.SEVERITY_WARNING);
}
}
fCMBuilder.setDeclPool(null);
} else {
fDeclPool.reset();
fCMBuilder.setDeclPool(fDeclPool);
}
fSchemaHandler.reset(fErrorReporter, fEntityResolver,
fSymbolTable, fGrammarPool);
if(fGrammarPool == null) {
fDeclPool.reset();
fSchemaHandler.setDeclPool(fDeclPool);
} else {
fSchemaHandler.setDeclPool(null);
}
fSubGroupHandler.reset();
} // reset()
/**
* Returns a Grammar object by parsing the contents of the
* entity pointed to by source.
*
* @param source the location of the entity which forms
* the starting point of the grammar to be constructed.
* @throws IOException When a problem is encountered reading the entity
* XNIException When a condition arises (such as a FatalError) that requires parsing
* of the entity be terminated.
*/
public Grammar loadGrammar(XMLInputSource source)
throws IOException, XNIException {
reset();
XSDDescription desc = new XSDDescription();
desc.fContextType = XSDDescription.CONTEXT_PREPARSE;
desc.setBaseSystemId(source.getBaseSystemId());
desc.setLiteralSystemId( source.getSystemId());
// none of the other fields make sense for preparsing
Hashtable locationPairs = new Hashtable();
if(!tokenizeSchemaLocationStr(fExternalSchemas, locationPairs)) {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"SchemaLocation",
new Object[]{fExternalSchemas},
XMLErrorReporter.SEVERITY_WARNING);
}
if(fExternalNoNSSchema != null) {
LocationArray noNs = new LocationArray();
noNs.addLocation(fExternalNoNSSchema);
locationPairs.put(XMLSymbols.EMPTY_STRING, noNs);
}
SchemaGrammar grammar = loadSchema(desc, source, locationPairs);
if(grammar != null && fGrammarPool != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, fGrammarBucket.getGrammars());
}
return grammar;
} // loadGrammar(XMLInputSource): Grammar
SchemaGrammar loadSchema(XSDDescription desc,
XMLInputSource source,
Hashtable locationPairs) throws IOException, XNIException {
// this should only be done once per invocation of this object;
// unless application alters JAXPSource in the mean time.
if(!fJAXPProcessed) {
processJAXPSchemaSource(locationPairs);
}
SchemaGrammar grammar = fSchemaHandler.parseSchema(source, desc, locationPairs);
// is full-checking enabled? If so, if we're preparsing we'll
// need to let XSConstraints have a go at the new grammar.
if(fIsCheckedFully) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter);
}
return grammar;
} // loadSchema(XSDDescription, XMLInputSource): SchemaGrammar
// this makes use of the schema location property values.
// we store the namespace/location pairs in a hashtable (use "" as the
// namespace of absent namespace). when resolving an entity, we first try
// to find in the hashtable whether there is a value for that namespace,
// if so, pass that location value to the user-defined entity resolver.
public static XMLInputSource resolveDocument(XSDDescription desc, Hashtable locationPairs,
XMLEntityResolver entityResolver) throws IOException {
String loc = null;
// we consider the schema location properties for import
if (desc.getContextType() == XSDDescription.CONTEXT_IMPORT ||
desc.fromInstance()) {
// use empty string as the key for absent namespace
String namespace = desc.getTargetNamespace();
String ns = namespace == null ? XMLSymbols.EMPTY_STRING : namespace;
// get the location hint for that namespace
LocationArray tempLA = (LocationArray)locationPairs.get(ns);
if(tempLA != null)
loc = tempLA.getFirstLocation();
}
// if it's not import, or if the target namespace is not set
// in the schema location properties, use location hint
if (loc == null) {
String[] hints = desc.getLocationHints();
if (hints != null && hints.length > 0)
loc = hints[0];
}
String expandedLoc = XMLEntityManager.expandSystemId(loc, desc.getBaseSystemId());
desc.setLiteralSystemId(loc);
desc.setExpandedSystemId(expandedLoc);
return entityResolver.resolveEntity(desc);
}
// this method takes a SchemaLocation string.
// If an error is encountered, false is returned;
// otherwise, true is returned. In either case, locations
// is augmented to include as many tokens as possible.
// @param schemaStr The schemaLocation string to tokenize
// @param locations Hashtable mapping namespaces to LocationArray objects holding lists of locaitons
// @return true if no problems; false if string could not be tokenized
public static boolean tokenizeSchemaLocationStr(String schemaStr, Hashtable locations) {
if (schemaStr!= null) {
StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r");
String namespace, location;
while (t.hasMoreTokens()) {
namespace = t.nextToken ();
if (!t.hasMoreTokens()) {
return false; // error!
}
location = t.nextToken();
LocationArray la = ((LocationArray)locations.get(namespace));
if(la == null) {
la = new LocationArray();
locations.put(namespace, la);
}
la.addLocation(location);
}
}
return true;
} // tokenizeSchemaLocation(String, Hashtable): boolean
/**
* Translate the various JAXP SchemaSource property types to XNI
* XMLInputSource. Valid types are: String, org.xml.sax.InputSource,
* InputStream, File, or Object[] of any of previous types.
* REVISIT: the JAXP 1.2 spec is less than clear as to whether this property
* should be available to imported schemas. I have assumed
* that it should. - NG
*/
private void processJAXPSchemaSource(Hashtable locationPairs) throws IOException {
if (fJAXPSource == null) {
return;
}
Class componentType = fJAXPSource.getClass().getComponentType();
XMLInputSource xis = null;
String sid = null;
if (componentType == null) {
// Not an array
fXSDDescription.reset();
xis = xsdToXMLInputSource(fJAXPSource);
sid = xis.getSystemId();
fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
if (sid != null) {
fXSDDescription.setLiteralSystemId(sid);
fXSDDescription.setExpandedSystemId(sid);
fXSDDescription.fLocationHints = new String[]{sid};
}
fJAXPProcessed = true;
fGrammarBucket.putGrammar(loadSchema(fXSDDescription, xis, locationPairs));
return ;
} else if ( (componentType != Object.class) &&
(componentType != String.class) &&
(componentType != File.class) &&
(componentType != InputStream.class) &&
(componentType != InputSource.class)
) {
// Not an Object[], String[], File[], InputStream[], InputSource[]
throw new XMLConfigurationException(
XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
"\" property cannot have an array of type {"+componentType.getName()+
"}. Possible types of the array supported are Object, String, File, "+
"InputStream, InputSource.");
}
// JAXP spec. allow []s of type String, File, InputStream,
// InputSource also, apart from [] of type Object.
Object[] objArr = (Object[]) fJAXPSource;
fJAXPProcessed = true;
for (int i = 0; i < objArr.length; i++) {
fXSDDescription.reset();
xis = xsdToXMLInputSource(objArr[i]);
sid = xis.getSystemId();
fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
if (sid != null) {
fXSDDescription.setLiteralSystemId(sid);
fXSDDescription.setExpandedSystemId(sid);
fXSDDescription.fLocationHints = new String[]{sid};
}
fGrammarBucket.putGrammar(loadSchema(fXSDDescription, xis, locationPairs));
}
}
private XMLInputSource xsdToXMLInputSource(
Object val)
{
if (val instanceof String) {
// String value is treated as a URI that is passed through the
// EntityResolver
String loc = (String) val;
if (fEntityResolver != null) {
fXSDDescription.reset();
fXSDDescription.setValues(null, loc, null, null);
XMLInputSource xis = null;
try {
xis = fEntityResolver.resolveEntity(fXSDDescription);
} catch (IOException ex) {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"schema_reference.4",
new Object[] { loc }, XMLErrorReporter.SEVERITY_ERROR);
}
if (xis == null) {
// REVISIT: can this happen?
// Treat value as a URI and pass in as systemId
return new XMLInputSource(null, loc, null);
}
return xis;
}
} else if (val instanceof InputSource) {
return saxToXMLInputSource((InputSource) val);
} else if (val instanceof InputStream) {
return new XMLInputSource(null, null, null,
(InputStream) val, null);
} else if (val instanceof File) {
File file = (File) val;
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException ex) {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
"schema_reference.4", new Object[] { file.toString() },
XMLErrorReporter.SEVERITY_ERROR);
}
return new XMLInputSource(null, null, null, is, null);
}
throw new XMLConfigurationException(
XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+
"\" property cannot have a value of type {"+val.getClass().getName()+
"}. Possible types of the value supported are String, File, InputStream, "+
"InputSource OR an array of these types.");
}
//Convert a SAX InputSource to an equivalent XNI XMLInputSource
private static XMLInputSource saxToXMLInputSource(InputSource sis) {
String publicId = sis.getPublicId();
String systemId = sis.getSystemId();
Reader charStream = sis.getCharacterStream();
if (charStream != null) {
return new XMLInputSource(publicId, systemId, null, charStream,
null);
}
InputStream byteStream = sis.getByteStream();
if (byteStream != null) {
return new XMLInputSource(publicId, systemId, null, byteStream,
sis.getEncoding());
}
return new XMLInputSource(publicId, systemId, null);
}
static class LocationArray{
int length ;
String [] locations = new String[2];
public void resize(int oldLength , int newLength){
String [] temp = new String[newLength] ;
System.arraycopy(locations, 0, temp, 0, Math.min(oldLength, newLength));
locations = temp ;
length = Math.min(oldLength, newLength);
}
public void addLocation(String location){
if(length >= locations.length ){
resize(length, Math.max(1, length*2));
}
locations[length++] = location;
}//setLocation()
public String [] getLocationArray(){
if(length < locations.length ){
resize(locations.length, length);
}
return locations;
}//getLocationArray()
public String getFirstLocation(){
return length > 0 ? locations[0] : null;
}
public int getLength(){
return length ;
}
} //locationArray
} // XMLGrammarLoader
|
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */
package org.biojava.bio.seq.db.biosql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.biojava.bio.BioError;
import org.biojava.bio.BioException;
import org.biojava.bio.BioRuntimeException;
import org.biojava.bio.seq.ComponentFeature;
import org.biojava.bio.seq.Feature;
import org.biojava.bio.seq.FeatureHolder;
import org.biojava.bio.seq.StrandedFeature;
import org.biojava.bio.seq.io.SeqIOListener;
import org.biojava.bio.symbol.FuzzyLocation;
import org.biojava.bio.symbol.Location;
import org.biojava.bio.symbol.LocationTools;
import org.biojava.bio.symbol.PointLocation;
import org.biojava.bio.symbol.RangeLocation;
import org.biojava.utils.ChangeVetoException;
/**
* Behind-the-scenes adaptor to the features sub-schema of BioSQL.
*
* @author Thomas Down
* @author Simon Foote (modifications for schema version 1.0)
* @author Len Trigg
* @since 1.3
*/
class FeaturesSQL {
private BioSQLSequenceDB seqDB;
FeaturesSQL(BioSQLSequenceDB seqDB) {
this.seqDB = seqDB;
}
// Feature retrieval
/**
* Get some features out of BioSQL and fire SeqIO events to the specified listener.
* Currently 4 modes:
*
* <ul>
* <li>Get all features on a bioentry (including children)</li>
* <li>Get all top-level features in a region</li>
* <li>Get all children of a specified parent</li>
* <li>Get a particular feature by ID</li>
* </ul>
*
* This is rather ugly, but it's well hidden. Not sure what the options would be for
* a cleaner API.
*/
public void retrieveFeatures(int bioentry_id,
SeqIOListener listener,
Location overlappingRegion,
int immediateChildrenOfParent,
int featureID)
throws SQLException, BioException
{
Connection conn = seqDB.getPool().takeConnection();
Map fmap = new HashMap();
Map qmap = new HashMap();
Map lmap = new HashMap();
PreparedStatement get_features = null;
if (overlappingRegion == null && immediateChildrenOfParent < 0 && featureID < 0) {
get_features = conn.prepareStatement(
"select seqfeature.seqfeature_id, " +
" seqfeature.type_term_id, " +
" seqfeature.source_term_id " +
" from seqfeature " +
" where seqfeature.bioentry_id = ?"
);
get_features.setInt(1, bioentry_id);
} else if (overlappingRegion != null) {
get_features = conn.prepareStatement(
"select seqfeature.seqfeature_id, " +
" seqfeature.type_term_id, " +
" seqfeature.source_term_id " +
" from location, seqfeature " +
" where seqfeature.bioentry_id = ? and " +
" location.seqfeature_id = seqfeature.seqfeature_id and " +
" location.end_pos >= ? and " +
" location.start_pos <= ? " +
" group by seqfeature.seqfeature_id, seqfeature.type_term_id, seqfeature.source_term_id"
);
get_features.setInt(1, bioentry_id);
get_features.setInt(2, overlappingRegion.getMin());
get_features.setInt(3, overlappingRegion.getMax());
} else if (immediateChildrenOfParent >= 0) {
get_features = conn.prepareStatement(
"select seqfeature.seqfeature_id, " +
" seqfeature.type_term_id, " +
" seqfeature.source_term_id " +
" from seqfeature, seqfeature_relationship " +
" where seqfeature.seqfeature_id = seqfeature_relationship.subject_seqfeature_id and " +
" seqfeature_relationship.object_seqfeature_id = ?"
);
get_features.setInt(1, immediateChildrenOfParent);
} else if (featureID >= 0) {
get_features = conn.prepareStatement(
"select seqfeature.seqfeature_id, " +
" seqfeature.type_term_id, " +
" seqfeature.source_term_id, " +
" seqfeature.bioentry_id " +
" from seqfeature " +
" where seqfeature.seqfeature_id = ?"
);
get_features.setInt(1, featureID);
} else {
throw new BioException("I'm afraid you can't do that!");
}
ResultSet rs = get_features.executeQuery();
while (rs.next()) {
int feature_id = rs.getInt(1);
StrandedFeature.Template templ = new StrandedFeature.Template();
templ.type = seqDB.getOntologyTerm(rs.getInt(2));
templ.source = seqDB.getOntologyTerm(rs.getInt(3));
templ.annotation = new BioSQLFeatureAnnotation(seqDB, feature_id);
// templ.annotation = new SmallAnnotation();
fmap.put(new Integer(feature_id), templ);
if (featureID >= 0 && bioentry_id < 0) {
bioentry_id = rs.getInt(4);
listener.addSequenceProperty("_biosql_internal.bioentry_id", new Integer(bioentry_id));
}
}
rs.close();
get_features.close();
// Fetch annotations (worth a try!)
PreparedStatement get_annotations = null;
if (overlappingRegion == null && immediateChildrenOfParent < 0 && featureID < 0) {
get_annotations = conn.prepareStatement(
"select seqfeature_qualifier_value.seqfeature_id, " +
" seqfeature_qualifier_value.term_id, " +
" seqfeature_qualifier_value.value " +
" from seqfeature, seqfeature_qualifier_value " +
" where seqfeature_qualifier_value.seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ?"
);
get_annotations.setInt(1, bioentry_id);
} else if (overlappingRegion != null) {
get_annotations = conn.prepareStatement(
"select seqfeature_qualifier_value.seqfeature_id, " +
" seqfeature_qualifier_value.term_id, " +
" seqfeature_qualifier_value.value " +
" from seqfeature, seqfeature_qualifier_value, location " +
" where seqfeature_qualifier_value.seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ? and" +
" location.seqfeature_id = seqfeature.seqfeature_id and " +
" location.end_pos >= ? and " +
" location.start_pos <= ? " +
" group by seqfeature_qualifier_value.seqfeature_id, " +
" seqfeature_qualifier_value.term_id, " +
" seqfeature_qualifier_value.value"
);
get_annotations.setInt(1, bioentry_id);
get_annotations.setInt(2, overlappingRegion.getMin());
get_annotations.setInt(3, overlappingRegion.getMax());
} else if (immediateChildrenOfParent >= 0) {
get_annotations = conn.prepareStatement(
"select seqfeature_qualifier_value.seqfeature_id, " +
" seqfeature_qualifier_value.term_id, " +
" seqfeature_qualifier_value.value " +
" from seqfeature_qualifier_value, seqfeature_relationship " +
" where seqfeature_qualifier_value.seqfeature_id = seqfeature_relationship.subject_seqfeature_id and " +
" seqfeature_relationship.object_seqfeature_id = ?"
);
get_annotations.setInt(1, immediateChildrenOfParent);
} else if (featureID >= 0) {
get_annotations = conn.prepareStatement(
"select seqfeature_qualifier_value.seqfeature_id, " +
" seqfeature_qualifier_value.term_id, " +
" seqfeature_qualifier_value.value " +
" from seqfeature_qualifier_value " +
" where seqfeature_qualifier_value.seqfeature_id = ?"
);
get_annotations.setInt(1, featureID);
}
rs = get_annotations.executeQuery();
while (rs.next()) {
Integer fid = new Integer(rs.getInt(1));
String key = seqDB.getOntologyTerm(rs.getInt(2));
String value = rs.getString(3).trim();
Feature.Template templ = (Feature.Template) fmap.get(fid);
try {
((BioSQLFeatureAnnotation) templ.annotation).initProperty(key, value);
} catch (ChangeVetoException ex) {
throw new BioError("Couldn't modify hidden FeatureHolder");
}
}
rs.close();
get_annotations.close();
// Fetch those crappy location qualifiers first...
/*
if (seqDB.isLocationQualifierSupported()) {
PreparedStatement get_location_crap = conn.prepareStatement(
"select location_qualifier_value.location_id, " +
" seqfeature_qualifier.qualifier_name, " +
" location_qualifier_value.qualifier_value, " +
" location_qualifier_value.qualifier_int_value " +
" from location_qualifier_value, location, seqfeature, seqfeature_qualifier " +
" where seqfeature.bioentry_id = ? and " +
" location.seqfeature_id = seqfeature.seqfeature_id and " +
" location_qualifier_value.location_id = location.location_id and " +
" seqfeature_qualifier.seqfeature_qualifier_id = location_qualifier_value.seqfeature_qualifier_id");
get_location_crap.setInt(1, bioentry_id);
rs = get_location_crap.executeQuery();
while (rs.next()) {
LocationQualifierMemento lqm = new LocationQualifierMemento();
int location_id = rs.getInt(1);
lqm.qualifier_name = rs.getString(2).trim(); // HACK due to stupid schema change
lqm.qualifier_value = rs.getString(3).trim();
lqm.qualifier_int = rs.getInt(4);
Integer location_id_boxed = new Integer(location_id);
List l = (List) qmap.get(location_id_boxed);
if (l == null) {
l = new ArrayList();
qmap.put(location_id_boxed, l);
}
l.add(lqm);
}
}
*/
// Fetch locations
PreparedStatement get_locations = null;
if (overlappingRegion == null && immediateChildrenOfParent < 0 && featureID < 0) {
get_locations = conn.prepareStatement(
"select location.location_id, " +
" location.seqfeature_id, " +
" location.start_pos, " +
" location.end_pos, " +
" location.strand " +
" from seqfeature, location " +
" where location.seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ?"
);
get_locations.setInt(1, bioentry_id);
} else if (overlappingRegion != null) {
get_locations = conn.prepareStatement(
"select location.location_id, " +
" location.seqfeature_id, " +
" location.start_pos, " +
" location.end_pos, " +
" location.strand " +
" from location, location as sfl2, seqfeature " +
" where location.seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ? and " +
" sfl2.seqfeature_id = seqfeature.seqfeature_id and " +
" sfl2.end_pos >= ? and " +
" sfl2.start_pos <= ? " +
" group by location.location_id, " +
" location.seqfeature_id, " +
" location.start_pos, " +
" location.end_pos, " +
" location.strand"
);
get_locations.setInt(1, bioentry_id);
get_locations.setInt(2, overlappingRegion.getMin());
get_locations.setInt(3, overlappingRegion.getMax());
} else if (immediateChildrenOfParent >= 0) {
get_locations = conn.prepareStatement(
"select location.location_id, " +
" location.seqfeature_id, " +
" location.start_pos, " +
" location.end_pos, " +
" location.strand " +
" from location, seqfeature_relationship " +
" where location.seqfeature_id = seqfeature_relationship.subject_seqfeature_id and " +
" seqfeature_relationship.object_seqfeature_id = ?"
);
get_locations.setInt(1, immediateChildrenOfParent);
} else if (featureID >= 0) {
get_locations = conn.prepareStatement(
"select location.location_id, " +
" location.seqfeature_id, " +
" location.start_pos, " +
" location.end_pos, " +
" location.strand " +
" from location " +
" where location.seqfeature_id = ?");
get_locations.setInt(1, featureID);
}
rs = get_locations.executeQuery();
while (rs.next()) {
Integer lid = new Integer(rs.getInt(1));
Integer fid = new Integer(rs.getInt(2));
int start = rs.getInt(3);
int end = rs.getInt(4);
int istrand = rs.getInt(5);
StrandedFeature.Strand strand = StrandedFeature.UNKNOWN;
if (istrand > 0) {
strand = StrandedFeature.POSITIVE;
} else if (istrand < 0) {
strand = StrandedFeature.NEGATIVE;
}
StrandedFeature.Template templ = (StrandedFeature.Template) fmap.get(fid);
if (templ.strand != null && templ.strand != strand) {
// throw new BioRuntimeException("Feature strands don't match");
// Really don't want to support these at all, but...
templ.strand = StrandedFeature.UNKNOWN;
} else {
templ.strand = strand;
}
Location bloc;
if (start == end) {
bloc = new PointLocation(start);
} else {
bloc = new RangeLocation(start, end);
}
List locationCrap = (List) qmap.get(lid);
if (locationCrap != null) {
int min_start = -1;
int min_end = -1;
int max_start = -1;
int max_end = -1;
boolean unknown_start = false;
boolean unknown_end = false;
boolean unbounded_start = false;
boolean unbounded_end = false;
boolean isFuzzy = false;
for (Iterator i = locationCrap.iterator(); i.hasNext(); ) {
LocationQualifierMemento lqm = (LocationQualifierMemento) i.next();
String qname = lqm.qualifier_name;
if ("min_start".equals(qname)) {
min_start = lqm.qualifier_int;
isFuzzy = true;
} else if ("max_start".equals(qname)) {
max_start = lqm.qualifier_int;
isFuzzy = true;
} else if ("min_end".equals(qname)) {
min_end = lqm.qualifier_int;
isFuzzy = true;
} else if ("max_end".equals(qname)) {
max_end = lqm.qualifier_int;
isFuzzy = true;
} else if ("start_pos_type".equals(qname)) {
if ("BEFORE".equalsIgnoreCase(lqm.qualifier_value)) {
unbounded_start = true;
isFuzzy = true;
}
} if ("end_pos_type".equals(qname)) {
if ("AFTER".equalsIgnoreCase(lqm.qualifier_value)) {
unbounded_end = true;
isFuzzy = true;
}
}
}
if (isFuzzy) {
if (unknown_start) {
min_start = Integer.MIN_VALUE;
max_start = Integer.MAX_VALUE;
}
if (unbounded_start) {
min_start = Integer.MIN_VALUE;
}
if (unknown_end) {
min_end = Integer.MIN_VALUE;
max_end = Integer.MAX_VALUE;
}
if (unbounded_end) {
max_end = Integer.MAX_VALUE;
}
if (min_start == -1) {
min_start = bloc.getMin();
}
if (max_start == -1) {
max_start = bloc.getMin();
}
if (min_end == -1) {
min_end = bloc.getMax();
}
if (max_end == -1) {
max_end = bloc.getMax();
}
bloc = new FuzzyLocation(min_start,
max_end,
max_start,
min_end,
FuzzyLocation.RESOLVE_INNER);
}
}
List ll = (List) lmap.get(fid);
if (ll == null) {
ll = new ArrayList();
lmap.put(fid, ll);
}
ll.add(bloc);
}
rs.close();
get_locations.close();
// Bind location information to features
for (Iterator i = fmap.entrySet().iterator(); i.hasNext(); ) {
Map.Entry me = (Map.Entry) i.next();
Integer fid = (Integer) me.getKey();
StrandedFeature.Template templ = (StrandedFeature.Template) me.getValue();
List ll = (List) lmap.get(fid);
if (ll == null) {
throw new BioRuntimeException("BioSQL SeqFeature doesn't have any associated location spans");
}
Location loc = null;
if (ll.size() == 1) {
loc = (Location) ll.get(0);
} else {
loc = LocationTools.union(ll);
}
templ.location = loc;
}
// Check hierarchy
Set toplevelFeatures = new HashSet(fmap.keySet());
Map featureHierarchy = new HashMap();
int specifiedParent = -1;
if (immediateChildrenOfParent < 0 && featureID < 0) {
PreparedStatement get_hierarchy;
if (overlappingRegion == null) {
get_hierarchy = conn.prepareStatement(
"select object_seqfeature_id, subject_seqfeature_id " +
" from seqfeature_relationship, seqfeature " +
" where object_seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ?"
);
get_hierarchy.setInt(1, bioentry_id);
} else {
get_hierarchy = conn.prepareStatement(
"select object_seqfeature_id, subject_seqfeature_id " +
" from seqfeature_relationship, seqfeature, location " +
" where object_seqfeature_id = seqfeature.seqfeature_id and " +
" seqfeature.bioentry_id = ? and " +
" location.seqfeature_id = object_seqfeature_id and " +
" location.end_pos >= ? and " +
" location.start_pos <= ? " +
" group by object_seqfeature_id, subject_seqfeature_id"
);
get_hierarchy.setInt(1, bioentry_id);
get_hierarchy.setInt(2, overlappingRegion.getMin());
get_hierarchy.setInt(3, overlappingRegion.getMax());
}
rs = get_hierarchy.executeQuery();
while (rs.next()) {
Integer parent = new Integer(rs.getInt(1));
Integer child = new Integer(rs.getInt(2));
toplevelFeatures.remove(child);
List cl = (List) featureHierarchy.get(parent);
if (cl == null) {
cl = new ArrayList();
featureHierarchy.put(parent, cl);
}
cl.add(child);
}
rs.close();
get_hierarchy.close();
} else if (immediateChildrenOfParent >= 0) {
specifiedParent = immediateChildrenOfParent;
} else if (featureID >= 0) {
PreparedStatement discover_parent = conn.prepareStatement(
"select object_seqfeature_id " +
" from seqfeature_relationship " +
" where object_seqfeature_id = ?"
);
discover_parent.setInt(1, featureID);
rs = discover_parent.executeQuery();
if (rs.next()) {
specifiedParent = rs.getInt(1);
}
rs.close();
discover_parent.close();
}
seqDB.getPool().putConnection(conn);
conn = null;
for (Iterator tlfi = toplevelFeatures.iterator(); tlfi.hasNext(); ) {
Integer fid = (Integer) tlfi.next();
Feature.Template templ = (Feature.Template) fmap.get(fid);
boolean childrenFetched = (immediateChildrenOfParent < 0);
if (overlappingRegion != null) {
if (!overlappingRegion.contains(templ.location)) {
childrenFetched = false;
}
}
fireFeatureTree(listener,
fid,
fmap,
featureHierarchy,
childrenFetched,
new Integer(specifiedParent)
);
}
}
private void fireFeatureTree(SeqIOListener listener,
Integer fid,
Map fmap,
Map featureHierarchy,
boolean childrenFetched,
Integer pid)
throws BioException
{
Feature.Template templ = (Feature.Template) fmap.get(fid);
listener.startFeature(templ);
listener.addFeatureProperty("_biosql_internal.feature_id", fid);
listener.addFeatureProperty("_biosql_internal.parent_id", pid);
if (childrenFetched) {
List children = (List) featureHierarchy.get(fid);
if (children == null) {
listener.addFeatureProperty("_biosql_internal.hint_childfree", Boolean.TRUE);
} else {
for (Iterator ci = children.iterator(); ci.hasNext(); ) {
Integer childID = (Integer) ci.next();
fireFeatureTree(listener, childID, fmap, featureHierarchy, childrenFetched, fid);
}
}
}
listener.endFeature();
}
private static class LocationQualifierMemento {
public String qualifier_name;
public String qualifier_value;
public int qualifier_int;
}
// Feature live updates
void setFeatureType(int feature_id, String type)
throws SQLException
{
Connection conn = null;
try {
conn = seqDB.getPool().takeConnection();
conn.setAutoCommit(false);
int seqfeature_key = seqDB.intern_ontology_term(conn, type);
PreparedStatement update_key = conn.prepareStatement("update seqfeature " +
" set type_term_id = ? " +
" where seqfeature_id = ?");
update_key.setInt(1, seqfeature_key);
update_key.setInt(2, feature_id);
update_key.executeUpdate();
conn.commit();
seqDB.getPool().putConnection(conn);
} catch (SQLException ex) {
boolean rolledback = false;
if (conn != null) {
try {
conn.rollback();
rolledback = true;
} catch (SQLException ex2) {}
}
throw ex;
}
}
void setFeatureSource(int feature_id, String source)
throws SQLException
{
Connection conn = null;
try {
conn = seqDB.getPool().takeConnection();
conn.setAutoCommit(false);
int seqfeature_source = seqDB.intern_ontology_term(conn, source);
PreparedStatement update_source = conn.prepareStatement("update seqfeature " +
" set source_term_id = ? " +
" where seqfeature_id = ?");
update_source.setInt(1, seqfeature_source);
update_source.setInt(2, feature_id);
update_source.executeUpdate();
conn.commit();
seqDB.getPool().putConnection(conn);
} catch (SQLException ex) {
boolean rolledback = false;
if (conn != null) {
try {
conn.rollback();
rolledback = true;
} catch (SQLException ex2) {}
}
throw ex;
}
}
void setFeatureLocation(int feature_id, Location location, StrandedFeature.Strand s)
throws SQLException
{
Connection conn = null;
try {
conn = seqDB.getPool().takeConnection();
conn.setAutoCommit(false);
PreparedStatement del_oldlocation = conn.prepareStatement(
"delete from location " +
" where seqfeature_id = ?"
);
del_oldlocation.setInt(1, feature_id);
del_oldlocation.executeUpdate();
del_oldlocation.close();
PreparedStatement add_locationspan = conn.prepareStatement(
"insert into location " +
" (seqfeature_id, start_pos, end_pos, strand, rank) " +
"values (?, ?, ?, ?, ?)"
);
int strandNum;
if (s == StrandedFeature.POSITIVE) {
strandNum = 1;
} else if (s== StrandedFeature.NEGATIVE) {
strandNum = -1;
} else {
strandNum = 0;
}
int rank = 0;
for (Iterator i = location.blockIterator(); i.hasNext(); ) {
Location bloc = (Location) i.next();
add_locationspan.setInt(1, feature_id);
add_locationspan.setInt(2, bloc.getMin());
add_locationspan.setInt(3, bloc.getMax());
add_locationspan.setInt(4, strandNum);
add_locationspan.setInt(5, ++rank);
add_locationspan.executeUpdate();
}
add_locationspan.close();
conn.commit();
seqDB.getPool().putConnection(conn);
} catch (SQLException ex) {
boolean rolledback = false;
if (conn != null) {
try {
conn.rollback();
rolledback = true;
} catch (SQLException ex2) {}
}
throw ex;
}
}
// Feature persistance
void persistFeatures(Connection conn, int bioentry_id, FeatureHolder features, int parent)
throws BioException, SQLException
{
// HashMap to track rank for each feature_type
// This allows the unique key constraint in seqfeature to be valid as
// bioentries can have multiple features of same type/source (ie. Genbank CDS)
// Not sure if this is the best way to do it or just increase the rank value each
// time no matter what the feature type is.
HashMap rankType = new HashMap();
for (Iterator fi = features.features(); fi.hasNext(); ) {
Feature f = (Feature) fi.next();
// Get next rank value for feature type
int rank = 0;
String fType = f.getType();
if (rankType.containsKey(fType)) {
rank = ((Integer) rankType.get(fType)).intValue() + 1;
rankType.put(fType, new Integer(rank));
} else {
rankType.put(fType, new Integer(0));
}
if (! (f instanceof ComponentFeature)) {
int id = persistFeature(conn, bioentry_id, f, parent, rank);
if (seqDB.isHierarchySupported()) {
persistFeatures(conn, bioentry_id, f, id);
}
}
}
}
int persistFeature(Connection conn,
int bioentry_id,
Feature f,
int parent_id,
int typeRank)
throws BioException, SQLException
{
int id = -1;
boolean locationWritten = false;
if (seqDB.isSPASupported()) {
if (f.getLocation().isContiguous()) {
Location loc = f.getLocation();
PreparedStatement add_feature = conn.prepareStatement(
"select create_seqfeature_onespan(?, ?, ?, ?, ?, ?)"
);
add_feature.setInt(1, bioentry_id);
add_feature.setString(2, f.getType());
add_feature.setString(3, f.getSource());
add_feature.setInt(4, loc.getMin());
add_feature.setInt(5, loc.getMax());
if (f instanceof StrandedFeature) {
StrandedFeature.Strand s = ((StrandedFeature) f).getStrand();
if (s == StrandedFeature.POSITIVE) {
add_feature.setInt(6, 1);
} else if (s== StrandedFeature.NEGATIVE) {
add_feature.setInt(6, -1);
} else {
add_feature.setInt(6, 0);
}
} else {
add_feature.setInt(6, 0);
}
ResultSet rs = add_feature.executeQuery();
if (rs.next()) {
id = rs.getInt(1);
}
add_feature.close();
locationWritten = true;
} else {
PreparedStatement add_feature = conn.prepareStatement(
"select create_seqfeature(?, ?, ?)"
);
add_feature.setInt(1, bioentry_id);
add_feature.setString(2, f.getType());
add_feature.setString(3, f.getSource());
ResultSet rs = add_feature.executeQuery();
if (rs.next()) {
id = rs.getInt(1);
}
add_feature.close();
}
} else {
int seqfeature_key = seqDB.intern_ontology_term(conn, f.getType());
int seqfeature_source = seqDB.intern_ontology_term(conn, f.getSource());
// Because of unique key constraints on seqfeature
// Need to select the maximum rank value for the bioentry,key,source value
// if rank is set to -1
if (typeRank < 0) {
PreparedStatement select_rank = conn.prepareStatement(
"select max(rank) from seqfeature where bioentry_id=?"
+ " and type_term_id=? and source_term_id=?");
select_rank.setInt(1, bioentry_id);
select_rank.setInt(2, seqfeature_key);
select_rank.setInt(3, seqfeature_source);
ResultSet rs = select_rank.executeQuery();
if (rs.next()) {
typeRank = rs.getInt(1) + 1;
}
}
PreparedStatement add_feature = conn.prepareStatement(
"insert into seqfeature "+
" (bioentry_id, type_term_id, source_term_id, rank) " +
"values (?, ?, ?, ?)"
);
add_feature.setInt(1, bioentry_id);
add_feature.setInt(2, seqfeature_key);
add_feature.setInt(3, seqfeature_source);
add_feature.setInt(4, typeRank);
add_feature.executeUpdate();
add_feature.close();
id = seqDB.getDBHelper().getInsertID(conn, "seqfeature", "seqfeature_id");
}
if (!locationWritten) {
PreparedStatement add_locationspan = conn.prepareStatement(
"insert into location " +
" (seqfeature_id, start_pos, end_pos, strand, rank) " +
"values (?, ?, ?, ?, ?)"
);
int strandNum;
if (f instanceof StrandedFeature) {
StrandedFeature.Strand s = ((StrandedFeature) f).getStrand();
if (s == StrandedFeature.POSITIVE) {
strandNum = 1;
} else if (s== StrandedFeature.NEGATIVE) {
strandNum = -1;
} else {
strandNum = 0;
}
} else {
strandNum = 0;
}
int rank = 0;
for (Iterator i = f.getLocation().blockIterator(); i.hasNext(); ) {
Location bloc = (Location) i.next();
add_locationspan.setInt(1, id);
add_locationspan.setInt(2, bloc.getMin());
add_locationspan.setInt(3, bloc.getMax());
add_locationspan.setInt(4, strandNum);
add_locationspan.setInt(5, ++rank);
add_locationspan.executeUpdate();
}
add_locationspan.close();
}
// Persist anything in the annotation bundle, as well.
for (Iterator ai = f.getAnnotation().asMap().entrySet().iterator(); ai.hasNext(); ) {
Map.Entry akv = (Map.Entry) ai.next();
persistProperty(conn, id, akv.getKey(), akv.getValue(), false);
}
// Persist link to parent
if (parent_id >= 0) {
PreparedStatement add_hierarchy = conn.prepareStatement(
"insert into seqfeature_relationship "+
" (object_seqfeature_id, subject_seqfeature_id, term_id) " +
"values (?, ?, ?)"
);
add_hierarchy.setInt(1, parent_id);
add_hierarchy.setInt(2, id);
add_hierarchy.setInt(3, seqDB.intern_ontology_term(conn, "contains"));
add_hierarchy.executeUpdate();
add_hierarchy.close();
}
return id;
}
void removeFeature(BioSQLFeature f)
throws ChangeVetoException
{
Connection conn = null;
try {
conn = seqDB.getPool().takeConnection();
conn.setAutoCommit(false);
removeFeature(conn, f);
conn.commit();
seqDB.getPool().putConnection(conn);
} catch (SQLException ex) {
boolean rolledback = false;
if (conn != null) {
try {
conn.rollback();
rolledback = true;
} catch (SQLException ex2) {}
}
throw new BioRuntimeException("Error removing from BioSQL tables"
+ (rolledback ? " (rolled back successfully)" : ""), ex);
}
}
private void removeFeature(Connection conn, BioSQLFeature f)
throws SQLException, ChangeVetoException
{
Iterator children = ((FeatureHolder) f).features();
while (children.hasNext()) {
Feature f2 = (Feature) children.next();
if (f2 instanceof BioSQLFeature) {
removeFeature(conn, (BioSQLFeature) f2);
}
}
int feature_id = f._getInternalID();
PreparedStatement delete_locs = conn.prepareStatement("delete from location " +
" where location.seqfeature_id = ?");
delete_locs.setInt(1, feature_id);
delete_locs.executeUpdate();
delete_locs.close();
PreparedStatement delete_fqv = conn.prepareStatement("delete from seqfeature_qualifier_value " +
" where seqfeature_qualifier_value.seqfeature_id = ?");
delete_fqv.setInt(1, feature_id);
delete_fqv.executeUpdate();
delete_fqv.close();
PreparedStatement delete_rel = conn.prepareStatement("delete from seqfeature_relationship " +
" where subject_seqfeature_id = ?");
delete_rel.setInt(1, feature_id);
delete_rel.executeUpdate();
delete_rel.close();
PreparedStatement delete_feature = conn.prepareStatement("delete from seqfeature " +
" where seqfeature_id = ?");
delete_feature.setInt(1, feature_id);
delete_feature.executeUpdate();
delete_feature.close();
}
/**
* Persist a property. Nothing is written if value is void
*/
void persistProperty(Connection conn,
int feature_id,
Object key,
Object value,
boolean removeFirst)
throws SQLException
{
String keyString = key.toString();
if (removeFirst) {
int id = seqDB.intern_ontology_term(conn, keyString);
PreparedStatement remove_old_value = conn.prepareStatement("delete from seqfeature_qualifier_value " +
" where seqfeature_id = ? and term_id = ?");
remove_old_value.setInt(1, feature_id);
remove_old_value.setInt(2, id);
remove_old_value.executeUpdate();
remove_old_value.close();
}
if (value != null) {
PreparedStatement insert_new;
if (seqDB.isSPASupported()) {
insert_new= conn.prepareStatement("insert into seqfeature_qualifier_value " +
" (seqfeature_id, term_id, rank, value) " +
"values (?, intern_ontology_term( ? ), ?, ?)");
if (value instanceof Collection) {
int cnt = 0;
for (Iterator i = ((Collection) value).iterator(); i.hasNext(); ) {
insert_new.setInt(1, feature_id);
insert_new.setString(2, keyString);
insert_new.setInt(3, ++cnt);
insert_new.setString(4, i.next().toString());
insert_new.executeUpdate();
}
} else {
insert_new.setInt(1, feature_id);
insert_new.setString(2, keyString);
insert_new.setInt(3, 1);
insert_new.setString(4, value.toString());
insert_new.executeUpdate();
}
insert_new.close();
} else {
insert_new = conn.prepareStatement("insert into seqfeature_qualifier_value " +
" (seqfeature_id, term_id, rank, value) " +
"values (?, ?, ?, ?)");
int sfq = seqDB.intern_ontology_term(conn, keyString);
if (value instanceof Collection) {
int cnt = 0;
for (Iterator i = ((Collection) value).iterator(); i.hasNext(); ) {
insert_new.setInt(1, feature_id);
insert_new.setInt(2, sfq);
insert_new.setInt(3, ++cnt);
insert_new.setString(4, i.next().toString());
insert_new.executeUpdate();
}
} else {
insert_new.setInt(1, feature_id);
insert_new.setInt(2, sfq);
insert_new.setInt(3, 1);
insert_new.setString(4, value.toString());
insert_new.executeUpdate();
}
insert_new.close();
}
}
}
void persistFeature(Feature f, int parent_id, int bioentry_id)
throws BioException
{
Connection conn = null;
try {
conn = seqDB.getPool().takeConnection();
conn.setAutoCommit(false);
// Set rank to -1, so will get looked up before feature added
int f_id = seqDB.getFeaturesSQL().persistFeature(conn, bioentry_id, f, parent_id, -1);
if (f instanceof BioSQLFeature) {
((BioSQLFeature) f)._setInternalID(f_id);
((BioSQLFeature) f)._setAnnotation(new BioSQLFeatureAnnotation(seqDB, f_id));
}
conn.commit();
seqDB.getPool().putConnection(conn);
} catch (SQLException ex) {
boolean rolledback = false;
if (conn != null) {
try {
conn.rollback();
rolledback = true;
} catch (SQLException ex2) {}
}
throw new BioException("Error adding BioSQL tables"
+ (rolledback ? " (rolled back successfully)" : ""), ex);
}
}
}
|
package no.deichman.services.entity;
import no.deichman.services.circulation.Item;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
/**
* Responsibility: provides an estimate for expected availability dates.
*/
final class Expectation {
private static final int ONE_WEEK_IN_DAYS = 7;
private static final int ONE_PLACE_ADJUSTMENT = 1;
private static final int HANDLING_TIME = 1;
private static final int TWO_WEEKS = 2;
private static final int FOUR_WEEKS = 4;
private static final int CUTOFF = 12;
Estimation estimate(int queuePlace, List<Item> items, boolean precedingZeroUser) {
Estimation estimation = new Estimation();
List<Item> reservableItems = reservableOf(items);
int availableItems = availableOf(reservableItems).size();
if (reservableItems.size() == 0) {
estimation.setError("No reservable items");
return estimation;
}
if (queuePlace == 0) {
estimation.setPending(true);
return estimation;
}
int adjustedQueuePlace = precedingZeroUser ? queuePlace : queuePlace - ONE_PLACE_ADJUSTMENT;
if (adjustedQueuePlace < availableItems) {
estimation.setPending(true);
return estimation;
}
int loanPeriod = getLoanPeriod(items.get(0).getType());
int estimate = (isDistantLoan(reservableItems.size(), adjustedQueuePlace, loanPeriod))
? 12 : guess(queuePlace, reservableItems, precedingZeroUser, loanPeriod);
estimation.setEstimatedWait((estimate < CUTOFF) ? estimate : CUTOFF);
return estimation;
}
private boolean isDistantLoan(int reservableItems, int adjustedQueuePlace, int loanPeriod) {
return (adjustedQueuePlace > reservableItems && (reservableItems / adjustedQueuePlace) * loanPeriod > 11);
}
private int getOffset(String onLoan) {
int offset = 0;
if (onLoan != null) {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime now = new DateTime();
int daysBetween = Days.daysBetween(now.toLocalDate(), dateTimeFormatter.parseDateTime(onLoan).toLocalDate()).getDays();
offset = (daysBetween < 1) ? 0 : (int) (Math.ceil(daysBetween / ONE_WEEK_IN_DAYS));
}
return offset;
}
private int getLoanPeriod(String itemType) {
if (itemType == null) {
return FOUR_WEEKS;
}
int period;
switch (itemType) {
case "FILM":
case "KART":
case "MUSIKK":
case "PERIODIKA":
period = TWO_WEEKS;
break;
case "BOK":
case "LYDBOK":
case "NOTER":
case "REALIA":
case "SPILL":
case "SPRAAKKURS":
default:
period = FOUR_WEEKS;
break;
}
return period;
}
private List<Item> reservableOf(List<Item> items) {
return items.stream().filter(Item::isReservable).collect(Collectors.toList());
}
private List<Item> availableOf(List<Item> items) {
return items.stream().filter(item -> item.getReturnDate() == null).collect(Collectors.toList());
}
private int guess(int queuePlace, List<Item> items, boolean zeroUser, int loanPeriod) {
int adjustedQueuePlace = (zeroUser) ? queuePlace + 1 : queuePlace;
Pair queueRowAndItem = getMatrixPosition(adjustedQueuePlace, items.size());
int queueRow = (int) queueRowAndItem.getLeft();
int relevantItem = (int) queueRowAndItem.getRight();
int weeksUntilNextRelevantStatusChange = getOffset(items.get(relevantItem).getReturnDate());
int adjustedQueueRow = (queueRow == 0) ? 0 : queueRow - 1;
int estimate = (queueRow == 1) ? weeksUntilNextRelevantStatusChange : (loanPeriod * adjustedQueueRow) + weeksUntilNextRelevantStatusChange;
return estimate + HANDLING_TIME;
}
private Pair getMatrixPosition(int queuePlace, int items) {
Pair<Integer, Integer> returnValue = null;
int b = (queuePlace + (items - (queuePlace % items))) / items;
int[][] matrix = new int[b][items];
int increment = 1;
for (int left = 0; left < b; left++) {
for (int right = 0; right < items; right++) {
matrix[left][right] = increment;
if (increment == queuePlace) {
returnValue = new ImmutablePair<>(left, right);
break;
}
increment++;
}
}
return returnValue;
}
}
|
package org.bouncycastle.bcpg;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Basic output stream.
*/
public class ArmoredOutputStream
extends OutputStream
{
private static final byte[] encodingTable =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v',
(byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
(byte)'7', (byte)'8', (byte)'9',
(byte)'+', (byte)'/'
};
/**
* encode the input data producing a base 64 encoded byte array.
*/
private void encode(
OutputStream out,
int[] data,
int len)
throws IOException
{
int d1, d2, d3;
switch (len)
{
case 0: /* nothing left to do */
break;
case 1:
d1 = data[0];
out.write(encodingTable[(d1 >>> 2) & 0x3f]);
out.write(encodingTable[(d1 << 4) & 0x3f]);
out.write('=');
out.write('=');
break;
case 2:
d1 = data[0];
d2 = data[1];
out.write(encodingTable[(d1 >>> 2) & 0x3f]);
out.write(encodingTable[((d1 << 4) | (d2 >>> 4)) & 0x3f]);
out.write(encodingTable[(d2 << 2) & 0x3f]);
out.write('=');
break;
case 3:
d1 = data[0];
d2 = data[1];
d3 = data[2];
out.write(encodingTable[(d1 >>> 2) & 0x3f]);
out.write(encodingTable[((d1 << 4) | (d2 >>> 4)) & 0x3f]);
out.write(encodingTable[((d2 << 2) | (d3 >>> 6)) & 0x3f]);
out.write(encodingTable[d3 & 0x3f]);
break;
default:
throw new IOException("unknown length in encode");
}
}
OutputStream out;
int[] buf = new int[3];
int bufPtr = 0;
CRC24 crc = new CRC24();
int chunkCount = 0;
boolean start = true;
boolean clearText = false;
boolean newLine = false;
String nl = System.getProperty("line.separator");
String type;
String headerStart = "
String headerTail = "
String footerStart = "
String footerTail = "
String version = "BCPG v@RELEASE_NAME@";
Hashtable headers = new Hashtable();
public ArmoredOutputStream(
OutputStream out)
{
this.out = out;
if (nl == null)
{
nl = "\r\n";
}
resetHeaders();
}
public ArmoredOutputStream(
OutputStream out,
Hashtable headers)
{
this(out);
Enumeration e = headers.keys();
while (e.hasMoreElements())
{
Object key = e.nextElement();
this.headers.put(key, headers.get(key));
}
}
/**
* Set an additional header entry.
*
* @param name the name of the header entry.
* @param value the value of the header entry.
*/
public void setHeader(
String name,
String value)
{
this.headers.put(name, value);
}
/**
* Reset the headers to only contain a Version string.
*/
public void resetHeaders()
{
headers.clear();
headers.put("Version", version);
}
/**
* Start a clear text signed message.
* @param hashAlgorithm
*/
public void beginClearText(
int hashAlgorithm)
throws IOException
{
String hash;
switch (hashAlgorithm)
{
case HashAlgorithmTags.SHA1:
hash = "SHA1";
break;
case HashAlgorithmTags.SHA256:
hash = "SHA256";
break;
case HashAlgorithmTags.SHA384:
hash = "SHA384";
break;
case HashAlgorithmTags.SHA512:
hash = "SHA512";
break;
case HashAlgorithmTags.MD2:
hash = "MD2";
break;
case HashAlgorithmTags.MD5:
hash = "MD5";
break;
case HashAlgorithmTags.RIPEMD160:
hash = "RIPEMD160";
break;
default:
throw new IOException("unknown hash algorithm tag in beginClearText: " + hashAlgorithm);
}
String armorHdr = "
String hdrs = "Hash: " + hash + nl + nl;
for (int i = 0; i != armorHdr.length(); i++)
{
out.write(armorHdr.charAt(i));
}
for (int i = 0; i != hdrs.length(); i++)
{
out.write(hdrs.charAt(i));
}
clearText = true;
newLine = true;
}
public void endClearText()
{
clearText = false;
}
private void writeHeaderEntry(
String name,
String value)
throws IOException
{
for (int i = 0; i != name.length(); i++)
{
out.write(name.charAt(i));
}
out.write(':');
out.write(' ');
for (int i = 0; i != value.length(); i++)
{
out.write(value.charAt(i));
}
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
}
public void write(
int b)
throws IOException
{
if (clearText)
{
out.write(b);
if (newLine)
{
newLine = false;
if (b == '-')
{
out.write(' ');
out.write('-'); // dash escape
}
}
if (b == '\n')
{
newLine = true;
}
return;
}
if (start)
{
boolean newPacket = (b & 0x40) != 0;
int tag = 0;
if (newPacket)
{
tag = b & 0x3f;
}
else
{
tag = (b & 0x3f) >> 2;
}
switch (tag)
{
case PacketTags.PUBLIC_KEY:
type = "PUBLIC KEY BLOCK";
break;
case PacketTags.SECRET_KEY:
type = "PRIVATE KEY BLOCK";
break;
case PacketTags.SIGNATURE:
type = "SIGNATURE";
break;
default:
type = "MESSAGE";
}
for (int i = 0; i != headerStart.length(); i++)
{
out.write(headerStart.charAt(i));
}
for (int i = 0; i != type.length(); i++)
{
out.write(type.charAt(i));
}
for (int i = 0; i != headerTail.length(); i++)
{
out.write(headerTail.charAt(i));
}
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
writeHeaderEntry("Version", (String)headers.get("Version"));
Enumeration e = headers.keys();
while (e.hasMoreElements())
{
String key = (String)e.nextElement();
if (!key.equals("Version"))
{
writeHeaderEntry(key, (String)headers.get(key));
}
}
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
start = false;
}
if (bufPtr == 3)
{
encode(out, buf, bufPtr);
bufPtr = 0;
if ((++chunkCount & 0xf) == 0)
{
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
}
}
crc.update(b);
buf[bufPtr++] = b & 0xff;
}
public void flush()
throws IOException
{
}
/**
* <b>Note</b>: close does nor close the underlying stream. So it is possible to write
* multiple objects using armoring to a single stream.
*/
public void close()
throws IOException
{
if (type != null)
{
encode(out, buf, bufPtr);
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
out.write('=');
int crcV = crc.getValue();
buf[0] = ((crcV >> 16) & 0xff);
buf[1] = ((crcV >> 8) & 0xff);
buf[2] = (crcV & 0xff);
encode(out, buf, 3);
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
for (int i = 0; i != footerStart.length(); i++)
{
out.write(footerStart.charAt(i));
}
for (int i = 0; i != type.length(); i++)
{
out.write(type.charAt(i));
}
for (int i = 0; i != footerTail.length(); i++)
{
out.write(footerTail.charAt(i));
}
for (int i = 0; i != nl.length(); i++)
{
out.write(nl.charAt(i));
}
out.flush();
type = null;
start = true;
}
}
}
|
package org.broad.igv.feature.tribble;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.cli_plugin.Argument;
import org.broad.igv.cli_plugin.LineFeatureDecoder;
import org.broad.igv.cli_plugin.LineFeatureEncoder;
import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.util.StringUtils;
import org.broad.igv.util.collections.MultiMap;
import htsjdk.tribble.Feature;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class IGVBEDCodec extends UCSCCodec<BasicFeature> implements LineFeatureEncoder<Feature>, LineFeatureDecoder<BasicFeature> {
private static final Logger log = Logger.getLogger(IGVBEDCodec.class);
static final Pattern BR_PATTERN = Pattern.compile("<br>");
static final Pattern EQ_PATTERN = Pattern.compile("=");
Genome genome;
public IGVBEDCodec() {
this(null);
}
public IGVBEDCodec(Genome genome) {
this(genome, FeatureType.BED);
}
public IGVBEDCodec(Genome genome, FeatureType featureType) {
super(BasicFeature.class, featureType);
this.genome = genome;
}
//@Override
public BasicFeature decode(String[] tokens) {
// The first 3 columns are non optional for BED. We will relax this
// and only require 2.
int tokenCount = tokens.length;
if (tokenCount < 2) {
return null;
}
String c = tokens[0];
String chr = genome == null ? c : genome.getCanonicalChrName(c);
//BED format, and IGV, use starting element as 0.
int start = Integer.parseInt(tokens[1]);
int end = start + 1;
if (tokenCount > 2) {
end = Integer.parseInt(tokens[2]);
}
BasicFeature feature = featureType == FeatureType.SPLICE_JUNCTION ?
new SpliceJunctionFeature(chr, start, end) :
new BasicFeature(chr, start, end);
// The rest of the columns are optional. Stop parsing upon encountering
// a non-expected value
// Name
if (tokenCount > 3) {
if (isGffTags()) {
MultiMap<String, String> atts = new MultiMap<String, String>();
tagHelper.parseAttributes(tokens[3], atts);
String name = tagHelper.getName(atts);
feature.setName(name);
String id = atts.get("ID");
if (id != null) {
FeatureDB.addFeature(id, feature, genome);
feature.setIdentifier(id);
} else {
feature.setIdentifier(name);
}
String alias = atts.get("Alias");
if (alias != null) {
FeatureDB.addFeature(alias, feature, genome);
}
String geneSymbols = atts.get("Symbol");
if (geneSymbols != null) {
String[] symbols = geneSymbols.split(",");
for (String sym : symbols) {
FeatureDB.addFeature(sym.trim(), feature, genome);
}
}
feature.setAttributes(atts);
} else {
String name = tokens[3].replaceAll("\"", "");
if (name.equals(".")) name = ""; // Convention
feature.setName(name);
feature.setIdentifier(name);
}
}
// Bed files are not always to-spec after the name field. Stop parsing when we find an unexpected column.
// Score
if (tokenCount > 4) {
try {
float score = Float.parseFloat(tokens[4]);
feature.setScore(score);
if (featureType == FeatureType.SPLICE_JUNCTION ) {
((SpliceJunctionFeature) feature).setJunctionDepth((int) score);
}
} catch (NumberFormatException numberFormatException) {
// Unexpected, but does not invalidate the previous values.
// Stop parsing the line here but keep the feature
// Don't log, would just slow parsing down.
return feature;
}
}
// Strand
if (tokenCount > 5) {
String strandString = tokens[5].trim();
char strand = (strandString.length() == 0)
? ' ' : strandString.charAt(0);
if (strand == '-') {
feature.setStrand(Strand.NEGATIVE);
} else if (strand == '+') {
feature.setStrand(Strand.POSITIVE);
} else {
feature.setStrand(Strand.NONE);
}
}
// Thick ends
if (tokenCount > 7) {
try {
int thickStart = Integer.parseInt(tokens[6]);
int thickEnd = Integer.parseInt(tokens[7]);
if (thickStart >= start && thickEnd <= end) {
feature.setThickStart(Integer.parseInt(tokens[6]));
feature.setThickEnd(Integer.parseInt(tokens[7]));
}
} catch (NumberFormatException e) {
return feature;
}
}
// Color
if (tokenCount > 8 && featureType != FeatureType.GAPPED_PEAK) {
String colorString = tokens[8];
if (colorString.trim().length() > 0 && !colorString.equals(".")) {
feature.setColor(ColorUtilities.stringToColor(colorString));
}
}
// Exons
if (tokenCount > 11) {
createExons(start, tokens, feature, chr, feature.getStrand());
//todo: some refactoring that allows this hack to be removed
if (featureType == FeatureType.SPLICE_JUNCTION ) {
SpliceJunctionFeature junctionFeature = (SpliceJunctionFeature) feature;
List<Exon> exons = feature.getExons();
junctionFeature.setJunctionStart(start + exons.get(0).getLength());
junctionFeature.setJunctionEnd(end - exons.get(1).getLength());
}
}
if (tokenCount > 14 && featureType == FeatureType.GAPPED_PEAK) {
MultiMap<String, String> attributes = new MultiMap<String, String>();
attributes.put("Signal Value", tokens[12]);
attributes.put("pValue (-log10)", tokens[13]);
attributes.put("qValue (-log10)", tokens[14]);
feature.setAttributes(attributes);
}
else if(tokenCount > 13 && featureType == FeatureType.SPLICE_JUNCTION ) {
try {
String [] startFlanking = tokens[12].split(",");
int [] startFlankingDeptyArray = new int[startFlanking.length];
for(int i=0; i<startFlanking.length; i++) {
startFlankingDeptyArray[i] = Integer.parseInt(startFlanking[i]);
}
String [] endFlanking = tokens[13].split(",");
int [] endFlankingDeptyArray = new int[endFlanking.length];
for(int i=0; i<endFlanking.length ;i++) {
endFlankingDeptyArray[i] = Integer.parseInt(endFlanking[i]);
}
((SpliceJunctionFeature) feature).setStartFlankingRegionDepthArray(startFlankingDeptyArray);
((SpliceJunctionFeature) feature).setEndFlankingRegionDepthArray(endFlankingDeptyArray);
} catch (NumberFormatException e) {
log.error("Error parsing flanking array", e);
}
}
return feature;
}
private String[] tokens = new String[50];
@Override
public BasicFeature decode(String nextLine) {
String trimLine = nextLine.trim();
if (trimLine.length() == 0) {
return null;
}
if (nextLine.startsWith("#") || nextLine.startsWith("track") || nextLine.startsWith("browser")) {
return null;
}
tokens = Globals.whitespacePattern.split(trimLine);
BasicFeature feature = decode(tokens);
feature.setRepresentation(nextLine);
return feature;
}
/**
* This function returns true iff the File potentialInput can be parsed by this
* codec.
* <p/>
* There is an assumption that there's never a situation where two different Codecs
* return true for the same file. If this occurs, the recommendation would be to error out.
* <p/>
* Note this function must never throw an error. All errors should be trapped
* and false returned.
*
* @param path the file to test for parsability with this codec
* @return true if potentialInput can be parsed, false otherwise
*/
@Override
public boolean canDecode(String path) {
return path.toLowerCase().endsWith(".bed") || path.toLowerCase().endsWith(".bed.gz");
}
private void createExons(int start, String[] tokens, BasicFeature gene, String chr,
Strand strand) throws NumberFormatException {
int cdStart = Integer.parseInt(tokens[6]);
int cdEnd = Integer.parseInt(tokens[7]);
int exonCount = Integer.parseInt(tokens[9]);
String[] exonSizes = Globals.commaPattern.split(tokens[10]);
String[] startsBuffer = Globals.commaPattern.split(tokens[11]);
int exonNumber = (strand == Strand.NEGATIVE ? exonCount : 1);
if (startsBuffer.length == exonSizes.length) {
for (int i = 0; i < startsBuffer.length; i++) {
int exonStart = start + Integer.parseInt(startsBuffer[i]);
int exonEnd = exonStart + Integer.parseInt(exonSizes[i]);
Exon exon = new Exon(chr, exonStart, exonEnd, strand);
exon.setCodingStart(cdStart);
exon.setCodingEnd(cdEnd);
gene.addExon(exon);
exon.setNumber(exonNumber);
if (strand == Strand.NEGATIVE) {
exonNumber
} else {
exonNumber++;
}
}
}
}
/**
* Encode a feature as a BED string.
*
* @param feature - feature to encode
* @return the encoded string
*/
public String encode(Feature feature) {
if(feature instanceof BasicFeature) {
String rep = ((BasicFeature) feature).getRepresentation();
if(rep != null) return rep;
}
StringBuffer buffer = new StringBuffer();
buffer.append(feature.getChr());
buffer.append("\t");
final int featureStart = feature.getStart();
buffer.append(String.valueOf(featureStart));
buffer.append("\t");
buffer.append(String.valueOf(feature.getEnd()));
BasicFeature basicFeature = null;
if (!(feature instanceof BasicFeature)) {
return buffer.toString();
} else {
basicFeature = (BasicFeature) feature;
}
boolean hasName = (basicFeature.getName() != null && basicFeature.getName().length() > 0) ||
(isGffTags() && basicFeature.getDescription() != null && basicFeature.getDescription().length() > 0);
if (hasName) {
buffer.append("\t");
if (isGffTags() && basicFeature.getDescription() != null) {
// mRNA<br>ID = LOC_Os01g01010.2<br>Name = LOC_Os01g01010.2<br>Parent = LOC_Os01g01010<br>
//ID=LOC_Os01g01010.1:exon_1;Parent=LOC_Os01g01010.1
String[] attrs = BR_PATTERN.split(basicFeature.getDescription());
buffer.append("\"");
for (String att : attrs) {
String[] kv = EQ_PATTERN.split(att, 2);
if (kv.length > 1) {
buffer.append(kv[0].trim());
buffer.append("=");
String value = kv[1].trim();
buffer.append(StringUtils.encodeURL(value));
buffer.append(";");
}
}
buffer.append("\"");
} else {
buffer.append(basicFeature.getName());
}
}
boolean more = !Float.isNaN(basicFeature.getScore()) || basicFeature.getStrand() != Strand.NONE ||
basicFeature.getColor() != null || basicFeature.getExonCount() > 0;
if (more) {
// Must have a non-whitespace name column to proceed
if(!hasName) {
buffer.append("\t.");
}
buffer.append("\t");
// UCSC scores are integers between 0 and 1000, but
float score = basicFeature.getScore();
if (Float.isNaN(score)) {
buffer.append("1000");
} else {
boolean isInt = (Math.floor(score) == score);
buffer.append(String.valueOf(isInt ? (int) score : score));
}
more = basicFeature.getStrand() != Strand.NONE || basicFeature.getColor() != null ||
(basicFeature.getThickStart() != basicFeature.getStart()) || basicFeature.getExonCount() > 0;
if (more) {
buffer.append("\t");
Strand strand = basicFeature.getStrand();
if (strand == Strand.NONE) buffer.append(" ");
else if (strand == Strand.POSITIVE) buffer.append("+");
else if (strand == Strand.NEGATIVE) buffer.append("-");
more = basicFeature.getColor() != null || basicFeature.getExonCount() > 0;
if (more) {
// Must continue if basicFeature has color or exons
java.util.List<Exon> exons = basicFeature.getExons();
int thickStart, thickEnd;
if (basicFeature.getColor() != null || exons != null) {
// Correct "thickStart" and "thickEnd"
if(exons != null && exons.size() > 0) {
thickStart = basicFeature.getEnd(); // This is not a typo
for (Exon ex : exons) {
if (!ex.isNonCoding()) {
thickStart = ex.getCdStart();
break;
}
}
thickEnd = basicFeature.getStart(); // Not a typo
for (int i = exons.size() - 1; i >= 0; i
Exon ex = exons.get(i);
if (!ex.isNonCoding()) {
thickEnd = ex.getCdEnd();
break;
}
}
}
else {
thickStart = ((BasicFeature) feature).getThickStart();
thickEnd = ((BasicFeature) feature).getThickEnd();
}
buffer.append("\t");
buffer.append(String.valueOf(thickStart));
buffer.append("\t");
buffer.append(String.valueOf(thickEnd));
buffer.append("\t");
java.awt.Color c = basicFeature.getColor();
buffer.append(c == null ? "." : ColorUtilities.colorToString(c));
buffer.append("\t");
if (exons != null && exons.size() > 0) {
buffer.append(String.valueOf(exons.size()));
buffer.append("\t");
for (Exon exon : exons) {
buffer.append(String.valueOf(exon.getLength()));
buffer.append(",");
}
buffer.append("\t");
for (Exon exon : exons) {
int exonStart = exon.getStart() - featureStart;
buffer.append(String.valueOf(exonStart));
buffer.append(",");
}
}
}
if(basicFeature instanceof SpliceJunctionFeature) {
SpliceJunctionFeature spliceJunctionFeature = (SpliceJunctionFeature) basicFeature;
int [] startFlanking = spliceJunctionFeature.getStartFlankingRegionDepthArray();
int [] endFlanking = spliceJunctionFeature.getEndFlankingRegionDepthArray();
if(startFlanking != null && startFlanking.length > 0 && endFlanking != null && endFlanking.length > 0) {
buffer.append("\t" + startFlanking[0]);
for(int i=1; i<startFlanking.length; i++) {
buffer.append("," + startFlanking[i]);
}
buffer.append("\t" + endFlanking[0]);
for(int i=1; i<endFlanking.length; i++) {
buffer.append("," + endFlanking[i]);
}
}
}
}
}
}
return buffer.toString();
}
@Override
public int getNumCols(String line) {
return line.split("\t").length;
}
@Override
public String getHeader() {
return null;
}
@Override
public void setInputs(List<String> commands, Map<Argument, Object> argumentMap, Argument argument) {
//pass
}
}
|
package org.d214.whs.wcc.app;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
@SuppressWarnings("serial")
public class WCC_PrototypeServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/json");
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append("\"one\",");
sb.append("\"two\",");
sb.append("\"three\",");
sb.append("\"four\",");
sb.append("\"five\"");
sb.append("]");
resp.getWriter().println(getUpcomingEvents());
//resp.getWriter().println(sb.toString());
//hello world
//new comment
}
private String getUpcomingEvents() {
StringBuffer jsonResponse = new StringBuffer("[");
Document doc;
try {
doc = Jsoup.connect("http://whs.d214.org/").get();
Elements eventItems = doc.select(".eventitem .descr .bold .bold");
for (Iterator iterator = eventItems.iterator(); iterator.hasNext();) {
Element element = (Element) iterator.next();
String elementText = element.text();
elementText = elementText.replace('"', '\'');
jsonResponse.append(String.format("\"%s\",", elementText));
}
jsonResponse.deleteCharAt(jsonResponse.length() - 1);
} catch (IOException e) {
jsonResponse.append("Error: Could not parse the whs site");
}
jsonResponse.append("]");
return jsonResponse.toString();
}
private String getDailyAnnouncements()
{
StringBuffer jsonResponse = new StringBuffer("[");
try
{
Document doc = Jsoup.connect("http://whs.d214.org/student_resources/daily_announcements.aspx").get();
Element table = doc.select(".bdywrpr .corwrpr-2clm-lr .cormain-2clm-lr table").first(); //still do
Iterator<Element> ite = table.select("td").iterator();
while (ite.hasNext())
{
ite.next();
String s = ite.next().text();
jsonResponse.append(s);
System.out.println(s);
}
jsonResponse.deleteCharAt(jsonResponse.length() - 1);
}
catch (Exception exc)
{
jsonResponse.append("There was an error retrieving the daily announcements.");
}
jsonResponse.append("]");
return jsonResponse.toString();
}
private String getTopNews()
{
StringBuffer jsonResponse = new StringBuffer("[");
try
{
Document doc = Jsoup.connect("http://whs.d214.org/").get();
//Elements table = doc.select("div#CT_Main_0_cache_pnlModule");
Element table = doc.select(".bdywrpr .corwrpr-3clm .wrpr2clm .cormain-hm #CT_Main_0_cache_pnlModule").first();
List<Node> childNodes = table.childNodes();
//Iterator<Element> ite = table.select("td").iterator();
Iterator<Node> ite = childNodes.iterator();
while (ite.hasNext())
{
//ite.next();
Node n = ite.next();
String s = n.nodeName();
String[] one;
String[] two;
jsonResponse.append(s);
System.out.println(s);
System.out.println("****");
}
jsonResponse.deleteCharAt(jsonResponse.length() - 1);
}
catch (Exception exc)
{
jsonResponse.append("There was an error retrieving the daily announcements.");
}
jsonResponse.append("]");
return jsonResponse.toString();
}
}
|
package org.griphyn.vdl.engine;
import java.util.ArrayList;
import java.util.HashMap;
import org.globus.swift.language.FormalParameter;
public class ProcedureSignature {
private String name;
private ArrayList inputArgs;
private ArrayList outputArgs;
private boolean anyNumOfInputArgs;
private boolean anyNumOfOutputArgs; /* this is maybe unnecessary*/
public ProcedureSignature(String name) {
this.name = name;
inputArgs = new ArrayList();
outputArgs = new ArrayList();
anyNumOfInputArgs = false;
anyNumOfOutputArgs = false;
}
public String getName() {
return name;
}
public void addInputArg(FormalArgumentSignature inputArg) {
inputArgs.add(inputArg);
}
public void addOutputArg(FormalArgumentSignature outputArg) {
outputArgs.add(outputArg);
}
public void setAnyNumOfInputArgs() {
anyNumOfInputArgs = true;
}
public void setAnyNumOfOutputArgs() {
anyNumOfOutputArgs = true;
}
public boolean getAnyNumOdInputArgs() {
return anyNumOfInputArgs;
}
public boolean getAnyNumOdOutputArgs() {
return anyNumOfOutputArgs;
}
public int sizeOfInputArray() {
return inputArgs.size();
}
public int sizeOfOutputArray() {
return outputArgs.size();
}
private static final FormalArgumentSignature[] FORMAL_ARGUMENT_SIGNATURE_ARRAY =
new FormalArgumentSignature[0];
public FormalArgumentSignature[] getInputArray() {
return (FormalArgumentSignature[])
inputArgs.toArray(FORMAL_ARGUMENT_SIGNATURE_ARRAY);
}
public FormalArgumentSignature[] getOutputArray() {
return (FormalArgumentSignature[])
outputArgs.toArray(FORMAL_ARGUMENT_SIGNATURE_ARRAY);
}
public FormalArgumentSignature getInputArray(int i) {
return (FormalArgumentSignature) inputArgs.get(i);
}
public FormalArgumentSignature getOutputArray(int i) {
return (FormalArgumentSignature) outputArgs.get(i);
}
public void setInputArgs(FormalParameter[] fp) {
for (int i = 0; i < fp.length; i++) {
FormalArgumentSignature fas = new FormalArgumentSignature(fp[i].getType().getLocalPart(),
fp[i].getName());
fas.setOptional(!fp[i].isNil());
this.addInputArg(fas);
}
}
public void setOutputArgs(FormalParameter[] fp) {
for (int i = 0; i < fp.length; i++) {
FormalArgumentSignature fas = new FormalArgumentSignature(fp[i].getType().getLocalPart(),
fp[i].getName());
/* fas.setOptional(!fp[i].isNil()); */
/* unnecessary because output arg can not be optional */
this.addOutputArg(fas);
}
}
public static HashMap makeProcedureSignatures() {
HashMap proceduresMap = new HashMap();
ProcedureSignature readData = new ProcedureSignature("readData");
FormalArgumentSignature rdInputArg = new FormalArgumentSignature(true);
readData.addInputArg(rdInputArg);
FormalArgumentSignature rdOutputArg = new FormalArgumentSignature(true);
readData.addOutputArg(rdOutputArg);
proceduresMap.put("readData", readData);
ProcedureSignature readData2 = new ProcedureSignature("readData2");
FormalArgumentSignature rd2InputArg = new FormalArgumentSignature(true);
readData2.addInputArg(rd2InputArg);
FormalArgumentSignature rd2OutputArg = new FormalArgumentSignature(true);
readData2.addOutputArg(rd2OutputArg);
proceduresMap.put("readData2", readData2);
ProcedureSignature print = new ProcedureSignature("print");
print.setAnyNumOfInputArgs();
proceduresMap.put("print", print);
ProcedureSignature trace = new ProcedureSignature("trace");
trace.setAnyNumOfInputArgs();
proceduresMap.put("trace", trace);
return proceduresMap;
}
public static HashMap makeFunctionSignatures () {
HashMap functionsMap = new HashMap();
ProcedureSignature arg = new ProcedureSignature("arg");
FormalArgumentSignature argIn1 = new FormalArgumentSignature("string");
arg.addInputArg(argIn1);
FormalArgumentSignature argIn2 = new FormalArgumentSignature("string");
argIn2.setOptional(true);
arg.addInputArg(argIn2);
FormalArgumentSignature argOut1 = new FormalArgumentSignature("string");
arg.addOutputArg(argOut1);
functionsMap.put(arg.getName(), arg);
ProcedureSignature extractint = new ProcedureSignature("extractint");
FormalArgumentSignature extractintIn1 = new FormalArgumentSignature(true); /* file can be specified as any type */
extractint.addInputArg(extractintIn1);
FormalArgumentSignature extractintOut1 = new FormalArgumentSignature("int");
extractint.addOutputArg(extractintOut1);
functionsMap.put(extractint.getName(), extractint);
ProcedureSignature filename = new ProcedureSignature("filename");
FormalArgumentSignature filenameIn1 = new FormalArgumentSignature(true); /* file can be specified as any type */
filename.addInputArg(filenameIn1);
FormalArgumentSignature filenameOut1 = new FormalArgumentSignature("string");
filename.addOutputArg(filenameOut1);
functionsMap.put(filename.getName(), filename);
ProcedureSignature filenames = new ProcedureSignature("filenames");
FormalArgumentSignature filenamesIn1 = new FormalArgumentSignature(true); /* file can be specified as any type */
filenames.addInputArg(filenamesIn1);
FormalArgumentSignature filenamesOut1 = new FormalArgumentSignature("string[]"); /* i think this is what it returns */
filenames.addOutputArg(filenamesOut1);
functionsMap.put(filenames.getName(), filenames);
ProcedureSignature regexp = new ProcedureSignature("regexp");
FormalArgumentSignature regexpIn1 = new FormalArgumentSignature("string");
regexp.addInputArg(regexpIn1);
FormalArgumentSignature regexpIn2 = new FormalArgumentSignature("string");
regexp.addInputArg(regexpIn2);
FormalArgumentSignature regexpIn3 = new FormalArgumentSignature("string");
regexp.addInputArg(regexpIn3);
FormalArgumentSignature regexpOut1 = new FormalArgumentSignature("string");
regexp.addOutputArg(regexpOut1);
functionsMap.put(regexp.getName(), regexp);
ProcedureSignature strcat = new ProcedureSignature("strcat");
strcat.setAnyNumOfInputArgs();
FormalArgumentSignature strcatOut1 = new FormalArgumentSignature("string");
strcat.addOutputArg(strcatOut1);
functionsMap.put(strcat.getName(), strcat);
ProcedureSignature strcut = new ProcedureSignature("strcut");
FormalArgumentSignature strcutIn1 = new FormalArgumentSignature("string");
strcut.addInputArg(strcutIn1);
FormalArgumentSignature strcutIn2 = new FormalArgumentSignature("string");
strcut.addInputArg(strcutIn2);
FormalArgumentSignature strcutOut1 = new FormalArgumentSignature("string");
strcut.addOutputArg(strcutOut1);
functionsMap.put(strcut.getName(), strcut);
ProcedureSignature strsplit = new ProcedureSignature("strsplit");
FormalArgumentSignature strsplitIn1 = new FormalArgumentSignature("string");
strsplit.addInputArg(strsplitIn1);
FormalArgumentSignature strsplitIn2 = new FormalArgumentSignature("string");
strsplit.addInputArg(strsplitIn2);
FormalArgumentSignature strsplitOut1 = new FormalArgumentSignature("string[]");
strsplit.addOutputArg(strsplitOut1);
functionsMap.put(strsplit.getName(), strsplit);
ProcedureSignature toint = new ProcedureSignature("toint");
FormalArgumentSignature tointIn1 = new FormalArgumentSignature("string");
toint.addInputArg(tointIn1);
FormalArgumentSignature toOut1 = new FormalArgumentSignature("int");
toint.addOutputArg(toOut1);
functionsMap.put(toint.getName(), toint);
return functionsMap;
}
public String toString() {
return outputArgs + " " + name + inputArgs;
}
}
|
package org.helioviewer.jhv.imagedata;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.ArrayList;
import org.helioviewer.jhv.math.MathUtils;
public class ImageFilter {
private static final int SII_MIN_K = 3;
private static final int SII_MAX_K = 5;
private static final double sigma0 = 100.0 / Math.PI;
private static final short[][] radii0 = {
{76, 46, 23, 0, 0},
{82, 56, 37, 19, 0},
{85, 61, 44, 30, 16}};
private static final float[][] weights0 = {
{0.1618f, 0.5502f, 0.9495f, 0, 0},
{0.0976f, 0.3376f, 0.6700f, 0.9649f, 0},
{0.0739f, 0.2534f, 0.5031f, 0.7596f, 0.9738f}};
// Box weights
private final float[] weights = new float[SII_MAX_K];
// Box radii
private final int[] radii = new int[SII_MAX_K];
// Number of boxes
private final int K;
private final float[] buffer;
public ImageFilter(double sigma, int _K, int N) {
K = _K;
int i = K - SII_MIN_K;
double sum = 0;
for (int k = 0; k < K; ++k) {
radii[k] = (int) (radii0[i][k] * (sigma / sigma0) + 0.5);
sum += weights0[i][k] * (2 * radii[k] + 1);
}
for (int k = 0; k < K; ++k)
weights[k] = (float) (weights0[i][k] / sum);
int pad = radii[0] + 1;
buffer = new float[N + 2 * pad];
}
private static int extension(int N, int n) {
while (true) {
if (n < 0)
n = -1 - n; // Reflect over n = -1/2
else if (n >= N)
n = 2 * N - 1 - n; // Reflect over n = N - 1/2
else
break;
}
return n;
}
private void gaussianConv(float[] dst, float[] src, int N, int stride, int offset) {
int pad = radii[0] + 1;
float accum = 0;
// Compute cumulative sum of src over n = -pad,..., N + pad - 1
for (int n = -pad; n < 0; ++n) {
accum += src[offset + stride * extension(N, n)];
buffer[pad + n] = accum;
}
for (int n = 0; n < N; ++n) {
accum += src[offset + stride * n];
buffer[pad + n] = accum;
}
for (int n = N; n < N + pad; ++n) {
accum += src[offset + stride * extension(N, n)];
buffer[pad + n] = accum;
}
// Compute stacked box filters
for (int n = 0; n < N; ++n) {
accum = weights[0] * (buffer[pad + n + radii[0]] - buffer[pad + n - radii[0] - 1]);
for (int k = 1; k < K; ++k)
accum += weights[k] * (buffer[pad + n + radii[k]] - buffer[pad + n - radii[k] - 1]);
dst[offset + stride * n] = accum;
}
}
private void gaussianConvImage(float[] dst, float[] src, int width, int height) {
// Filter each row
for (int y = 0; y < height; ++y)
gaussianConv(dst, src, width, 1, width * y);
// Filter each column
for (int x = 0; x < width; ++x)
gaussianConv(dst, dst, height, width, x);
}
private static final int _K = 3;
private static final float H = 0.7f;
private static final double KA = 0.7;
private static final double[] sigmas = {1, 4, 16, 64};
private static float Atan(double x) {
x = MathUtils.clip(x, -1, 1);
return (float) (x * ((Math.PI / 4 + 0.186982) - 0.191942 * x * x));
}
@SuppressWarnings("serial")
private static class ScaleTask extends RecursiveTask<float[]> {
private final float[] data;
private final int width;
private final int height;
private final int size;
private final int N;
private final double sigma;
ScaleTask(float[] _data, int _width, int _height, double _sigma) {
data = _data;
width = _width;
height = _height;
size = width * height;
N = Math.max(width, height);
sigma = _sigma;
}
@Override
protected float[] compute() {
ImageFilter filter = new ImageFilter(sigma, _K, N);
float[] conv = new float[size];
float[] conv2 = new float[size];
filter.gaussianConvImage(conv, data, width, height);
for (int i = 0; i < size; ++i) {
float v = data[i] - conv[i];
conv[i] = v;
conv2[i] = v * v;
}
filter.gaussianConvImage(conv2, conv2, width, height);
for (int i = 0; i < size; ++i) {
double v = Math.sqrt(conv2[i]);
if (v == 0)
v = 1;
conv[i] = Atan(KA * conv[i] / v);
}
return conv;
}
}
private static float[] multiScale(float[] data, int width, int height) {
ArrayList<ForkJoinTask<float[]>> tasks = new ArrayList<>(sigmas.length);
for (double sigma : sigmas)
tasks.add(new ScaleTask(data, width, height, sigma).fork());
int size = width * height;
float[] image = new float[size];
for (ForkJoinTask<float[]> task : tasks) {
float[] res = task.join();
for (int i = 0; i < size; ++i)
image[i] += res[i];
}
float min = 1e6f, max = -1e6f;
for (int i = 0; i < size; ++i) {
float v = image[i] / sigmas.length;
if (v > max)
max = v;
if (v < min)
min = v;
image[i] = v;
}
if (max == min)
return data;
float k = (1 - H) / (max - min);
for (int i = 0; i < size; ++i) {
image[i] = k * (image[i] - min) + H * data[i];
}
return image;
}
public static ByteBuffer mgn(ByteBuffer buf, int width, int height) {
int size = width * height;
float[] data = new float[size];
byte[] array = buf.array(); // always backed by array
for (int i = 0; i < size; ++i)
data[i] = ((array[i] + 256) & 0xFF) / 255f;
float[] image = multiScale(data, width, height);
byte[] out = new byte[size];
for (int i = 0; i < size; ++i)
out[i] = (byte) MathUtils.clip(image[i] * 255 + .5f, 0, 255);
return ByteBuffer.wrap(out);
}
public static ShortBuffer mgn(ShortBuffer buf, int width, int height) {
int size = width * height;
float[] data = new float[size];
short[] array = buf.array(); // always backed by array
for (int i = 0; i < size; ++i)
data[i] = ((array[i] + 65536) & 0xFFFF) / 65535f;
float[] image = multiScale(data, width, height);
short[] out = new short[size];
for (int i = 0; i < size; ++i)
out[i] = (short) MathUtils.clip(image[i] * 65535 + .5f, 0, 65535);
return ShortBuffer.wrap(out);
}
}
|
package net.sandius.rembulan.core;
/**
* A factory for creating {@link Upvalue} instances.
*/
public interface UpvalueFactory {
/**
* Creates a new Upvalue with the given initial value.
*
* @param initialValue initial value, may be null
* @return new instance of Upvalue with the given value
*/
Upvalue newUpvalue(Object initialValue);
}
|
package devopsdistilled.operp.client.commons.panes;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import devopsdistilled.operp.client.abstracts.SubTaskPane;
import devopsdistilled.operp.client.commons.panes.controllers.CreateContactInfoPaneController;
import devopsdistilled.operp.client.commons.panes.models.observers.CreateContactInfoPaneModelObserver;
import devopsdistilled.operp.server.data.entity.commons.PhoneType;
public class CreateContactInfoPane extends SubTaskPane implements
CreateContactInfoPaneModelObserver {
private CreateContactInfoPaneController controller;
private final JPanel pane;
private final JTextField emailField;
private final JTextField workNumField;
private final JTextField mobileNumField;
private final JTextField homeNumField;
private final JPanel addressPanel;
public CreateContactInfoPane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[grow][grow]", "[][grow][][][][][]"));
JLabel lblAddress = new JLabel("Address");
pane.add(lblAddress, "flowx,cell 0 0");
addressPanel = new JPanel();
pane.add(addressPanel, "cell 1 1,grow");
JLabel lblEmail = new JLabel("Email");
pane.add(lblEmail, "cell 0 2,alignx trailing");
emailField = new JTextField();
emailField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
controller.getModel().getContactInfo()
.setEmail(emailField.getText().trim());
}
});
pane.add(emailField, "cell 1 2,growx");
emailField.setColumns(10);
JLabel lblPhone = new JLabel("Phone");
pane.add(lblPhone, "cell 0 3");
JLabel lblWork = new JLabel("Work");
pane.add(lblWork, "cell 0 4,alignx trailing");
workNumField = new JTextField();
workNumField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
controller.getModel().getContactInfo().getPhoneNumbers()
.put(PhoneType.Work, workNumField.getText().trim());
}
});
pane.add(workNumField, "cell 1 4,growx");
workNumField.setColumns(10);
JLabel lblMobile = new JLabel("Mobile");
pane.add(lblMobile, "cell 0 5,alignx trailing");
mobileNumField = new JTextField();
mobileNumField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
controller.getModel().getContactInfo().getPhoneNumbers()
.put(PhoneType.Mobile, mobileNumField.getText().trim());
}
});
pane.add(mobileNumField, "cell 1 5,growx");
mobileNumField.setColumns(10);
JLabel lblHome = new JLabel("Home");
pane.add(lblHome, "cell 0 6,alignx trailing");
homeNumField = new JTextField();
homeNumField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
controller.getModel().getContactInfo().getPhoneNumbers()
.put(PhoneType.Work, mobileNumField.getText().trim());
}
});
pane.add(homeNumField, "cell 1 6,growx");
homeNumField.setColumns(10);
}
@Override
public JComponent getPane() {
return pane;
}
public void setController(CreateContactInfoPaneController controller) {
this.controller = controller;
}
}
|
/*
* $Id: ColumnDescriptor.java,v 1.12 2014-01-14 04:28:26 tlipkis Exp $
*/
package org.lockss.daemon.status;
import java.util.*;
/**
* Encapsulation of the info needed to describe a single column (name,
* display title, and type).
*
* Type information is used for formatting the values in that column. Specific
* requirements for each type are listed below.
*/
public class ColumnDescriptor {
/**
* Must have meaningful toString() method
*/
public static final int TYPE_INT=0;
/**
* Instanceof floating point number (Float, Double, etc.)
*/
public static final int TYPE_FLOAT=1;
/**
* Instanceof floating point number (Float, Double, etc.) and floatValue()
* must return between 0 and 1, inclusive
*/
public static final int TYPE_PERCENT=2;
/**
* Instanceof number (Integer, Long, Float, etc.)
*/
public static final int TYPE_TIME_INTERVAL=3;
/**
* Objects of this type must have meaningful toString() method
*/
public static final int TYPE_STRING=4;
/**
* Instanceof IPAddr
*/
public static final int TYPE_IP_ADDRESS=5;
/**
* Instanceof number (Integer, Long, Float, etc.)
*/
public static final int TYPE_DATE=6;
/**
* Like TYPE_PERCENT but formatted as
* Instanceof floating point number (Float, Double, etc.) and floatValue()
* must return between 0 and 1, inclusive
*/
public static final int TYPE_AGREEMENT=7;
private String columnName;
private String title;
private int type;
private String footNote;
protected boolean sortable = true;
protected Comparator comparator = null;
public ColumnDescriptor(String columnName, String title, int type) {
this.columnName = columnName;
this.title = title;
this.type = type;
}
public ColumnDescriptor(String columnName, String title,
int type, String footNote) {
this(columnName,title, type);
this.footNote = footNote;
}
public String getColumnName() {
return columnName;
}
public String getTitle() {
return title;
}
public int getType() {
return type;
}
public String getFootnote() {
return footNote;
}
public Comparator getComparator() {
return comparator;
}
public ColumnDescriptor setComparator(Comparator comparator) {
this.comparator = comparator;
return this;
}
public boolean isSortable() {
return sortable;
}
public ColumnDescriptor setSortable(boolean sortable) {
this.sortable = sortable;
return this;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[ColumnDescriptor:");
sb.append(columnName);
sb.append(", ");
sb.append(title);
sb.append(", ");
sb.append(type);
sb.append("]");
return sb.toString();
}
public boolean equals(Object obj) {
if (!(obj instanceof ColumnDescriptor)) {
return false;
}
ColumnDescriptor colDesc = (ColumnDescriptor) obj;
return (title.equals(colDesc.getTitle()) &&
type == colDesc.getType() &&
columnName.equals(colDesc.getColumnName()));
}
public int hashCode() {
return title.hashCode() * 3
+ columnName.hashCode() * 5
+ type * 7;
}
}
|
package org.lockss.extractor;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import java.io.*;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.util.*;
/**
* Pulls metadata from a .ris file in the format
* TY - JOUR
* T1 - Article Tile of the Article
* ...
* first line of data should always be the TY (reference type)
* there may be empty lines before the first line
*/
public class RisMetadataExtractor implements FileMetadataExtractor {
static Logger log = Logger.getLogger(RisMetadataExtractor.class);
private MultiMap risTagToMetadataField;
protected static final String REFTYPE_JOURNAL = "Journal";
protected static final String REFTYPE_BOOK = "Book";
protected static final String REFTYPE_OTHER = "Other";
private String delimiter = "-";
/**
*Create a RisMetadataExtractor with a default RIS Type To MetadataField map
*/
public RisMetadataExtractor(){
risTagToMetadataField = new MultiValueMap();
risTagToMetadataField.put("T1", MetadataField.FIELD_ARTICLE_TITLE);
risTagToMetadataField.put("AU", MetadataField.FIELD_AUTHOR);
risTagToMetadataField.put("JF", MetadataField.FIELD_PUBLICATION_TITLE);
risTagToMetadataField.put("DO", MetadataField.FIELD_DOI);
risTagToMetadataField.put("PB", MetadataField.FIELD_PUBLISHER);
risTagToMetadataField.put("VL", MetadataField.FIELD_VOLUME);
risTagToMetadataField.put("IS", MetadataField.FIELD_ISSUE);
risTagToMetadataField.put("SP", MetadataField.FIELD_START_PAGE);
risTagToMetadataField.put("EP", MetadataField.FIELD_END_PAGE);
risTagToMetadataField.put("DA", MetadataField.FIELD_DATE);
}
/**
* Create a RisMetadataExtractor with a RIS tag To MetadataField map of fieldMap
* overriding default fieldMap
* @param fieldMap
*/
public RisMetadataExtractor(MultiValueMap fieldMap){
risTagToMetadataField = fieldMap;
}
/**
* Create a RisMetadataExtractor with a RIS tag To MetadataField map of default
* fieldMap and adding the specified metadata field Ris tag pair
* @param risTag
* @param field
*/
public RisMetadataExtractor(String risTag, MetadataField field){
this();
addRisTag(risTag, field);
}
/**
* Add the specified metadata field Ris tag pair to the RIS tag To MetadataField map
* @param risTag
* @param field
*/
public void addRisTag(String risTag, MetadataField field){
risTagToMetadataField.put(risTag, field);
}
/**
* Remove entry associated with the Ris tag from the the RIS tag To MetadataField map
* @param risTag
*/
public void removeRisTag(String risTag){
risTagToMetadataField.remove(risTag);
}
/**
* Check for the Ris tag in the the RIS tag To MetadataField map
* @param risTag
*/
public boolean containsRisTag(String risTag){
return risTagToMetadataField.containsKey(risTag);
}
/*
public void setdelimiter(String delim){
delimiter = delim;
}
*/
@Override
public void extract(MetadataTarget target, CachedUrl cu, Emitter emitter)
throws IOException, PluginException {
ArticleMetadata md = extract(target, cu);
if (md != null) {
emitter.emitMetadata(cu, md);
}
}
/**
* Extract metadata from the content of the cu, which should be an RIS file.
* Reads line by line inserting the 2 character code and value into the raw map.
* The first line should be a material type witch if it is book or journal will
* determine if we interpret the SN tag as IS beltSN or ISBN.
* @param target
* @param cu
*/
public final ArticleMetadata extract(MetadataTarget target, CachedUrl cu)
throws IOException, PluginException {
if(cu == null) {
throw new IllegalArgumentException();
}
ArticleMetadata md = new ArticleMetadata();
BufferedReader bReader = new BufferedReader(cu.openForReading());
String line;
String refType = null;
try {
if(!containsRisTag("TY")){
String value = null;
while(refType == null && (line = bReader.readLine()) != null) {
if(line.trim().toUpperCase().startsWith("TY") && line.contains(delimiter) && !line.endsWith(delimiter)) {
value = line.substring(line.indexOf(delimiter) + 1).trim().toUpperCase();
if(value.contentEquals("JOUR")) {
refType = REFTYPE_JOURNAL;
}
else if(value.contains("BOOK") || value.contains("CHAP")) {
refType = REFTYPE_BOOK;
}
else {
refType = REFTYPE_OTHER;
}
}
}
if(refType == null){
return md;
}
md.putRaw("TY", value);
}
while ((line = bReader.readLine()) != null) {
line = line.trim();
if(!line.contentEquals("") && line.contains(delimiter) && !line.endsWith(delimiter)){
String value = line.substring(line.indexOf(delimiter) + 1);
String key = line.substring(0,line.indexOf(delimiter) - 1);
key = key.trim().toUpperCase();
md.putRaw(key, value.trim());
if(!containsRisTag("SN") && key.contentEquals("SN")){
if(refType.contentEquals(REFTYPE_BOOK)) {
addRisTag("SN", MetadataField.FIELD_ISBN);
}
else {
addRisTag("SN", MetadataField.FIELD_ISSN);
}
}
}
}
} finally {
IOUtil.safeClose(bReader);
}
md.cook(risTagToMetadataField);
return md;
}
}
|
package com.sonelli.juicessh.performancemonitor.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.sonelli.juicessh.performancemonitor.R;
import com.sonelli.juicessh.performancemonitor.adapters.ConnectionSpinnerAdapter;
import com.sonelli.juicessh.performancemonitor.controllers.BaseController;
import com.sonelli.juicessh.performancemonitor.controllers.CpuUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.DiskUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.FreeRamController;
import com.sonelli.juicessh.performancemonitor.controllers.LoadAverageController;
import com.sonelli.juicessh.performancemonitor.controllers.NetworkUsageController;
import com.sonelli.juicessh.performancemonitor.loaders.ConnectionListLoader;
import com.sonelli.juicessh.performancemonitor.views.AutoResizeTextView;
import com.sonelli.juicessh.pluginlibrary.PluginClient;
import com.sonelli.juicessh.pluginlibrary.PluginContract;
import com.sonelli.juicessh.pluginlibrary.exceptions.ServiceNotConnectedException;
import com.sonelli.juicessh.pluginlibrary.listeners.OnClientStartedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionFinishedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionStartedListener;
import java.util.UUID;
public class MainActivity extends ActionBarActivity implements ActionBar.OnNavigationListener, OnSessionStartedListener, OnSessionFinishedListener {
public static final String TAG = "MainActivity";
private boolean isClientStarted = false;
private final PluginClient client = new PluginClient();
private final static int JUICESSH_REQUEST_CODE = 2585;
private Button connectButton;
private Button disconnectButton;
private ConnectionSpinnerAdapter spinnerAdapter;
// Controllers
private BaseController loadAverageController;
private BaseController freeRamController;
private BaseController cpuUsageController;
private BaseController diskUsageController;
private BaseController networkUsageController;
// Text displays
private AutoResizeTextView loadAverageTextView;
private AutoResizeTextView freeRamTextView;
private AutoResizeTextView cpuUsageTextView;
private AutoResizeTextView networkUsageTextView;
private AutoResizeTextView diskUsageTextView;
// State
private volatile int sessionId;
private volatile String sessionKey;
private volatile boolean isConnected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an adapter for populating the actionbar spinner with connections.
// We're going to pass in TYPE_SSH to disable all spinner items not of this type.
// This is because sending of commands required to poll performance data is only
// possible on SSH connections.
this.spinnerAdapter = new ConnectionSpinnerAdapter(this, PluginContract.Connections.TYPE_SSH);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(spinnerAdapter, this);
this.loadAverageTextView = (AutoResizeTextView) findViewById(R.id.load_average);
this.freeRamTextView = (AutoResizeTextView) findViewById(R.id.free_memory);
this.cpuUsageTextView = (AutoResizeTextView) findViewById(R.id.cpu_usage);
this.networkUsageTextView = (AutoResizeTextView) findViewById(R.id.network_usage);
this.diskUsageTextView = (AutoResizeTextView) findViewById(R.id.disk_usage);
this.connectButton = (Button) findViewById(R.id.connect_button);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final UUID id = spinnerAdapter.getConnectionId(getSupportActionBar().getSelectedNavigationIndex());
if(id != null){
if(isClientStarted){
try {
client.connect(MainActivity.this, id, MainActivity.this, JUICESSH_REQUEST_CODE);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
}
}
}
});
this.disconnectButton = (Button) findViewById(R.id.disconnect_button);
this.disconnectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(sessionId > -1 && sessionKey != null){
if(isClientStarted){
disconnectButton.setText(R.string.disconnecting);
disconnectButton.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
client.disconnect(sessionId, sessionKey);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
disconnectButton.post(new Runnable() {
@Override
public void run() {
disconnectButton.setEnabled(true);
disconnectButton.setText(R.string.disconnect);
}
});
}
}).start();
}
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(loadAverageTextView != null){
loadAverageTextView.resizeText();
}
// Use a Loader to load the connection list into the adapter from the JuiceSSH content provider
// This keeps DB activity async and off the UI thread to prevent the plugin lagging
getSupportLoaderManager().initLoader(0, null, new ConnectionListLoader(this, spinnerAdapter));
if(this.isConnected){
connectButton.setVisibility(View.GONE);
disconnectButton.setVisibility(View.VISIBLE);
} else {
connectButton.setVisibility(View.VISIBLE);
disconnectButton.setVisibility(View.GONE);
}
}
@Override
protected void onPause() {
super.onPause();
if(this.isConnected){
// Disconnect when activity is paused
disconnectButton.performClick();
}
}
@Override
protected void onStart() {
super.onStart();
client.start(this, new OnClientStartedListener() {
@Override
public void onClientStarted() {
isClientStarted = true;
connectButton.setEnabled(true);
}
@Override
public void onClientStopped() {
isClientStarted = false;
connectButton.setEnabled(false);
}
});
}
@Override
protected void onStop() {
super.onStop();
if(isClientStarted){
client.stop(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// This is important if you want to be able to interact with JuiceSSH sessions that you
// have started otherwise the plugin won't have access.
if(requestCode == JUICESSH_REQUEST_CODE){
client.gotActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onSessionStarted(final int sessionId, final String sessionKey) {
MainActivity.this.sessionId = sessionId;
MainActivity.this.sessionKey = sessionKey;
MainActivity.this.isConnected = true;
connectButton.setVisibility(View.GONE);
connectButton.setEnabled(false);
disconnectButton.setVisibility(View.VISIBLE);
disconnectButton.setEnabled(true);
// Register a listener for session finish events so that we know when the session has been disconnected
try {
client.addSessionFinishedListener(sessionId, sessionKey, this);
} catch (ServiceNotConnectedException e){}
this.loadAverageController = new LoadAverageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(loadAverageTextView)
.start();
this.freeRamController = new FreeRamController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(freeRamTextView)
.start();
this.cpuUsageController = new CpuUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(cpuUsageTextView)
.start();
this.diskUsageController = new DiskUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(diskUsageTextView)
.start();
this.networkUsageController = new NetworkUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(networkUsageTextView)
.start();
}
@Override
public void onSessionCancelled() {
// The user cancelled our JuiceSSH connection before it finished
// connecting or failed authentication.
}
@Override
public void onSessionFinished() {
MainActivity.this.sessionId = -1;
MainActivity.this.sessionKey = null;
MainActivity.this.isConnected = false;
if(loadAverageController != null){
loadAverageController.stop();
}
if(freeRamController != null){
freeRamController.stop();
}
if(cpuUsageController != null){
cpuUsageController.stop();
}
if(diskUsageController != null){
diskUsageController.stop();
}
if(networkUsageController != null){
networkUsageController.stop();
}
loadAverageTextView.setText("
freeRamTextView.setText("
cpuUsageTextView.setText("
networkUsageTextView.setText("
diskUsageTextView.setText("
disconnectButton.setVisibility(View.GONE);
disconnectButton.setEnabled(false);
connectButton.setVisibility(View.VISIBLE);
connectButton.setEnabled(true);
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.fork_on_github:
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_url)));
urlIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(urlIntent, getString(R.string.open_address)));
return true;
case R.id.rate_plugin:
String packageName = getResources().getString(R.string.app_package);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
try {
startActivity(intent);
} catch (ActivityNotFoundException e){
Toast.makeText(this, getString(R.string.google_play_not_installed), Toast.LENGTH_SHORT).show();
}
return true;
case R.id.about:
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
return true;
}
return false;
}
}
|
package org.opencms.staticexport;
import org.opencms.main.OpenCms;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteManager;
import com.opencms.file.CmsObject;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.StringNode;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.scanners.ImageScanner;
import org.htmlparser.scanners.LinkScanner;
import org.htmlparser.tags.CompositeTag;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.Tag;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;
/**
* @author Carsten Weinholz (c.weinholz@alkacon.com)
*
* @version $Revision: 1.7 $
* @since 5.3
*/
public class CmsLinkProcessor extends NodeVisitor {
/** Processing modes */
private static final int C_REPLACE_LINKS = 0;
private static final int C_PROCESS_LINKS = 1;
/** Current processing mode */
private int m_mode;
/** The parser */
private Parser m_parser;
/** The link table used for link macro replacements */
private CmsLinkTable m_linkTable;
/** The processed content */
private StringBuffer m_result;
/** The current cms instance */
private CmsObject m_cms;
/** The relative path for relative links, if not set, relative links are treated as external links */
private String m_relativePath;
/** Indicates if links should be generated for editing purposes */
private boolean m_processEditorLinks;
/**
* Creates a new CmsLinkProcessor.<p>
*
* @param linkTable the link table to use
*/
public CmsLinkProcessor (CmsLinkTable linkTable) {
super(true, true);
m_linkTable = linkTable;
m_parser = new Parser();
m_parser.addScanner(new LinkScanner());
m_parser.addScanner(new ImageScanner(ImageTag.IMAGE_TAG_FILTER));
}
/**
* Starts link processing for the given content in replacement mode.<p>
* Links are replaced by macros.
*
* @param cms the cms object
* @param content the content to process
* @param relativePath additional path for links with relative path
* @return the processed content with replaced links
*
* @throws ParserException if something goes wrong
*/
public String replaceLinks(CmsObject cms, String content, String relativePath) throws ParserException {
Lexer lexer = new Lexer(content);
m_relativePath = relativePath;
m_mode = C_REPLACE_LINKS;
m_cms = cms;
m_result = new StringBuffer();
m_parser.setLexer(lexer);
m_parser.visitAllNodesWith(this);
return m_result.toString();
}
/**
* Starts link processing for the given content in processing mode.<p>
* Macros are replaced by links.
*
* @param cms the cms object
* @param content the content to process
* @param processEditorLinks flag to process links for editing purposes
* @return the processed content with replaced macros
*
* @throws ParserException if something goes wrong
*/
public String processLinks(CmsObject cms, String content, boolean processEditorLinks) throws ParserException {
Lexer lexer = new Lexer(content);
m_processEditorLinks = processEditorLinks;
m_mode = C_PROCESS_LINKS;
m_cms = cms;
m_result = new StringBuffer();
m_parser.setLexer(lexer);
m_parser.visitAllNodesWith(this);
return m_result.toString();
}
/**
* Visitor method to process a single link.<p>
*
* @param linkTag the tag to process
*
* @see org.htmlparser.visitors.NodeVisitor#visitLinkTag(org.htmlparser.tags.LinkTag)
*/
public void visitLinkTag(LinkTag linkTag) {
switch (m_mode) {
case C_REPLACE_LINKS:
String targetUri = linkTag.extractLink();
if (!"".equals(targetUri)) {
String internalUri = CmsLinkManager.getSitePath(m_cms, m_relativePath, targetUri);
if (internalUri != null) {
linkTag.setLink(replaceLink(m_linkTable.addLink(linkTag.getTagName(), internalUri, true)));
} else {
linkTag.setLink(replaceLink(m_linkTable.addLink(linkTag.getTagName(), targetUri, false)));
}
}
break;
case C_PROCESS_LINKS:
linkTag.setLink(processLink(m_linkTable.getLink(getLinkName(linkTag.getLink()))));
break;
default:
// noop
break;
}
}
/**
* Visitor method to process an image tag.<p>
*
* @param imageTag the tag to process
*
* @see org.htmlparser.visitors.NodeVisitor#visitImageTag(org.htmlparser.tags.ImageTag)
*/
public void visitImageTag(ImageTag imageTag) {
switch (m_mode) {
case C_REPLACE_LINKS:
String targetUri = imageTag.getImageURL();
String internalUri = CmsLinkManager.getSitePath(m_cms, m_relativePath, targetUri);
if (internalUri != null) {
imageTag.setImageURL(replaceLink(m_linkTable.addLink(imageTag.getTagName(), internalUri, true)));
} else {
imageTag.setImageURL(replaceLink(m_linkTable.addLink(imageTag.getTagName(), targetUri, false)));
}
break;
case C_PROCESS_LINKS:
imageTag.setImageURL(processLink(m_linkTable.getLink(getLinkName(imageTag.getImageURL()))));
break;
default:
// noop
break;
}
}
/**
* Visitor method to process a string node.<p>
*
* @param stringNode the string node to process
*
* @see org.htmlparser.visitors.NodeVisitor#visitStringNode(org.htmlparser.StringNode)
*/
public void visitStringNode(StringNode stringNode) {
// process only those nodes that won't be processed by an end tag,
// nodes without parents or parents without an end tag, since
// the complete processing of all children should happen before
// we turn this node back into html text
if (null == stringNode.getParent ()) {
m_result.append(stringNode.toHtml());
}
}
/**
* Visitor method to process a tag (start).<p>
*
* @param tag the tag to process
*
* @see org.htmlparser.visitors.NodeVisitor#visitTag(org.htmlparser.tags.Tag)
*/
public void visitTag(Tag tag) {
// process only those nodes that won't be processed by an end tag,
// nodes without parents or parents without an end tag, since
// the complete processing of all children should happen before
// we turn this node back into html text
if (null == tag.getParent ()
&& (!(tag instanceof CompositeTag) || null == ((CompositeTag)tag).getEndTag ())) {
m_result.append(tag.toHtml());
}
}
/**
* Visitor method to process a tag (end).<p>
*
* @param tag the tag to process
*
* @see org.htmlparser.visitors.NodeVisitor#visitEndTag(org.htmlparser.tags.Tag)
*/
public void visitEndTag(Tag tag) {
Node parent;
parent = tag.getParent ();
if (null == parent) {
m_result.append(tag.toHtml());
} else if (parent instanceof CompositeTag) {
// write the parent and its children only when the end tag is reached
if (tag == ((CompositeTag)parent).getEndTag()) {
m_result.append(parent.toHtml());
}
} else {
m_result.append(parent.toHtml());
}
}
/**
* Returns the replacement string for a given link.<p>
*
* @param link the link
* @return the replacement
*/
private String replaceLink(CmsLink link) {
return newMacro(link.getName());
}
/**
* Returns the processed link of a given link.<p>
*
* @param link the link
* @return processed link
*/
private String processLink(CmsLink link) {
if (link.isInternal()) {
CmsSite site = null;
// we are in the opencms root site but not in edit mode - use link as stored
if (!m_processEditorLinks && "".equals(m_cms.getRequestContext().getSiteRoot())) {
return OpenCms.getLinkManager().substituteLink(m_cms, link.getUri());
}
// otherwise get the desired site root from the stored link
// - if there is no site root, we have a system link (or the site was deleted),
// return the link prefixed with the opencms context
String siteRoot = link.getSiteRoot();
if (siteRoot == null) {
return OpenCms.getLinkManager().substituteLink(m_cms, link.getUri());
} else {
site = CmsSiteManager.getSite(siteRoot);
}
// if we are in the desired site, relative links are generated
// if the link is processed for editing purposes, relative links are generated, too
// otherwise, links are generated as absolute links
if (m_cms.getRequestContext().getSiteRoot().equals(siteRoot) || m_processEditorLinks) {
return OpenCms.getLinkManager().substituteLink(m_cms, link.getVfsUri());
} else {
return site.getUrl() + OpenCms.getLinkManager().substituteLink(m_cms, link.getVfsUri());
}
} else {
// don't touch external links
return link.getUri();
}
}
/**
* Internal method to create a macro name ${name}.<p>
*
* @param name the name of the macro
*
* @return the macro string
*/
private String newMacro (String name) {
return "${" + name + "}";
}
/**
* Internal method to get the name of a macro string.<p>
*
* @param macro the macro string
*
* @return the name of the macro
*/
private String getLinkName (String macro) {
return macro.substring(2, macro.length()-1);
}
}
|
package org.opencms.workplace;
import org.opencms.ade.configuration.CmsElementView;
import org.opencms.ade.containerpage.shared.CmsCntPageData.ElementDeleteMode;
import org.opencms.ade.galleries.shared.CmsGallerySearchScope;
import org.opencms.configuration.CmsAdditionalLogFolderConfig;
import org.opencms.configuration.CmsDefaultUserSettings;
import org.opencms.db.CmsExportPoint;
import org.opencms.db.CmsUserSettings;
import org.opencms.db.I_CmsProjectDriver;
import org.opencms.file.CmsFolder;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeFolderExtended;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.i18n.CmsAcceptLanguageHeaderParser;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsI18nInfo;
import org.opencms.i18n.CmsLocaleComparator;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.i18n.I_CmsLocaleHandler;
import org.opencms.loader.CmsLoaderException;
import org.opencms.main.CmsBroadcast.ContentMode;
import org.opencms.main.CmsEvent;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsEventListener;
import org.opencms.main.OpenCms;
import org.opencms.module.CmsModule;
import org.opencms.module.CmsModuleManager;
import org.opencms.relations.CmsCategoryService;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsPermissionViolationException;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.security.I_CmsPrincipal;
import org.opencms.util.CmsRfsFileViewer;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsAccountInfo.Field;
import org.opencms.workplace.editors.CmsEditorDisplayOptions;
import org.opencms.workplace.editors.CmsEditorHandler;
import org.opencms.workplace.editors.CmsWorkplaceEditorManager;
import org.opencms.workplace.editors.I_CmsEditorActionHandler;
import org.opencms.workplace.editors.I_CmsEditorCssHandler;
import org.opencms.workplace.editors.I_CmsEditorHandler;
import org.opencms.workplace.editors.I_CmsPreEditorActionDefinition;
import org.opencms.workplace.editors.directedit.CmsDirectEditDefaultProvider;
import org.opencms.workplace.editors.directedit.I_CmsDirectEditProvider;
import org.opencms.workplace.explorer.CmsExplorerTypeAccess;
import org.opencms.workplace.explorer.CmsExplorerTypeSettings;
import org.opencms.workplace.galleries.A_CmsAjaxGallery;
import org.opencms.workplace.tools.CmsToolManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Manages the global OpenCms workplace settings for all users.<p>
*
* This class reads the settings from the "opencms.properties" and stores them in member variables.
* For each setting one or more get methods are provided.<p>
*
* @since 6.0.0
*/
public final class CmsWorkplaceManager implements I_CmsLocaleHandler, I_CmsEventListener {
/**
* Helper class used to easily define default view mappings for standard resource types.<p>
*/
static class ViewRules {
/**
* Internal view map.<p>
*/
private Map<String, String> m_viewMap = Maps.newHashMap();
/**
* Creates a new instance.<p>
*
* @param rules an array of strings of the form 'foo,bar,baz:view1', where foo, ... are type names and view1 is a view name (explorertype)
*/
public ViewRules(String... rules) {
for (String rule : rules) {
int colIndex = rule.indexOf(':');
if (colIndex != -1) {
String before = rule.substring(0, colIndex);
String after = rule.substring(colIndex + 1);
for (String token : CmsStringUtil.splitAsList(before, ",")) {
m_viewMap.put(token.trim(), after);
}
}
}
}
/**
* Gets the view configured for the given type.<p>
*
* @param type a resource type name
* @return the view explorer type for the given resource type
*/
public String getViewForType(String type) {
return m_viewMap.get(type);
}
}
/** The default encoding for the workplace (UTF-8). */
public static final String DEFAULT_WORKPLACE_ENCODING = CmsEncoder.ENCODING_UTF_8;
/** The workplace localization manifest attribute name. */
public static final String LOCALIZATION_ATTRIBUTE_NAME = "OpenCms-Localization";
/** The manifest file resource name. */
public static final String MANIFEST_RESOURCE_NAME = "META-INF/MANIFEST.MF";
/** The id of the "requestedResource" parameter for the OpenCms login form. */
public static final String PARAM_LOGIN_REQUESTED_RESOURCE = "requestedResource";
/** Key name for the session workplace settings. */
public static final String SESSION_WORKPLACE_SETTINGS = "__CmsWorkplace.WORKPLACE_SETTINGS";
/** Default view configuration. */
static ViewRules m_defaultViewRules = new ViewRules(
"folder,plain,jsp,htmlredirect,containerpage:view_basic",
"imagegallery,downloadgallery,linkgallery,subsitemap,content_folder:view_folders",
"formatter_config,xmlvfsbundle,propertyvfsbundle,bundledescriptor,sitemap_config,sitemap_master_config,module_config,elementview,seo_file,containerpage_template,inheritance_config,macro_formatter,flex_formatter,settings_config:view_configs",
"xmlcontent,pointer:view_other");
/** The default account infos. */
private static final CmsAccountInfo[] DEFAULT_ACCOUNT_INFOS = new CmsAccountInfo[] {
new CmsAccountInfo(Field.firstname, null, false),
new CmsAccountInfo(Field.lastname, null, false),
new CmsAccountInfo(Field.email, null, false),
new CmsAccountInfo(Field.institution, null, false)};
/** The logger for this class. */
private static final Log LOG = CmsLog.getLog(CmsWorkplaceManager.class);
/** Value of the acacia-unlock configuration option (may be null if not set). */
private String m_acaciaUnlock;
/** The configured account infos. */
private List<CmsAccountInfo> m_accountInfos;
/** The admin cms context. */
private CmsObject m_adminCms;
/** Indicates if auto-locking of resources is enabled or disabled. */
private boolean m_autoLockResources;
/** The name of the local category folder(s). */
private String m_categoryFolder;
/** The default access for explorer types. */
private CmsExplorerTypeAccess m_defaultAccess;
/** The configured default locale of the workplace. */
private Locale m_defaultLocale;
/** The default property setting for setting new property values. */
private boolean m_defaultPropertiesOnStructure;
/** The default user settings. */
private CmsDefaultUserSettings m_defaultUserSettings;
/** The configured dialog handlers. */
private Map<String, I_CmsDialogHandler> m_dialogHandler;
/** The configured direct edit provider. */
private I_CmsDirectEditProvider m_directEditProvider;
/** The edit action handler. */
private I_CmsEditorActionHandler m_editorAction;
/** The editor CSS handlers. */
private List<I_CmsEditorCssHandler> m_editorCssHandlers;
/** The workplace editor display options. */
private CmsEditorDisplayOptions m_editorDisplayOptions;
/** The editor handler. */
private I_CmsEditorHandler m_editorHandler;
/** The editor manager. */
private CmsWorkplaceEditorManager m_editorManager;
/** The element delete mode. */
private ElementDeleteMode m_elementDeleteMode;
/** The flag if switching tabs in the advanced property dialog is enabled. */
private boolean m_enableAdvancedPropertyTabs;
/** The configured encoding of the workplace. */
private String m_encoding;
/** The explorer type settings. */
private List<CmsExplorerTypeSettings> m_explorerTypeSettings;
/** The explorer type settings from the configured modules. */
private List<CmsExplorerTypeSettings> m_explorerTypeSettingsFromModules;
/** The explorer type settings from the XML configuration. */
private List<CmsExplorerTypeSettings> m_explorerTypeSettingsFromXml;
/** The explorer type settings as Map with resource type name as key. */
private Map<String, CmsExplorerTypeSettings> m_explorerTypeSettingsMap;
/** The element views generated from explorer types. */
private Map<CmsUUID, CmsElementView> m_explorerTypeViews = Maps.newHashMap();
/** The workplace export points. */
private Set<CmsExportPoint> m_exportPoints;
/** Maximum size of an upload file. */
private int m_fileMaxUploadSize;
/** The instance used for reading portions of lines of a file to choose. */
private CmsRfsFileViewer m_fileViewSettings;
/** The configured workplace galleries. */
private Map<String, A_CmsAjaxGallery> m_galleries;
/** The configured gallery default scope. */
private String m_galleryDefaultScope;
/** The group translation. */
private I_CmsGroupNameTranslation m_groupNameTranslation;
/** The configured group translation class name. */
private String m_groupTranslationClass;
/** Keep-alive flag. */
private Boolean m_keepAlive;
/** Contains all folders that should be labeled if siblings exist. */
private List<String> m_labelSiteFolders;
/** List of installed workplace locales, sorted ascending. */
private List<Locale> m_locales;
/** The configured list of localized workplace folders. */
private List<String> m_localizedFolders;
/** The workplace localized messages (mapped to the locales). */
private Map<Locale, CmsWorkplaceMessages> m_messages;
/** The post upload handler. */
private I_CmsPostUploadDialogHandler m_postUploadHandler;
/** The condition definitions for the resource types which are triggered before opening the editor. */
private List<I_CmsPreEditorActionDefinition> m_preEditorConditionDefinitions;
/** The repository folder handler. */
private I_CmsRepositoryFolderHandler m_repositoryFolderHandler;
/** Indicates if the user management icon should be displayed in the workplace. */
private boolean m_showUserGroupIcon;
/** Exclude patterns for synchronization. */
private ArrayList<Pattern> m_synchronizeExcludePatterns;
/** The temporary file project used by the editors. */
private CmsProject m_tempFileProject;
/** The tool manager. */
private CmsToolManager m_toolManager;
/** The user additional information configuration. */
private CmsWorkplaceUserInfoManager m_userInfoManager;
/** The user list mode. */
private String m_userListMode;
/** The configured workplace views. */
private List<CmsWorkplaceView> m_views;
/** Expiring cache used to limit the number of notifications sent because of invalid workplace server names. */
private Cache<String, String> m_workplaceServerUserChecks;
/** The XML content auto correction flag. */
private boolean m_xmlContentAutoCorrect;
/** The additional log folder configuration. */
private CmsAdditionalLogFolderConfig m_logFolderConfig = new CmsAdditionalLogFolderConfig();
/** A flag, indicating if the categories should be displayed separated by repository in the category selection dialog. */
private boolean m_displayCategoriesByRepository;
/** A flag, indicating if the categories should be displayed separated by repository in the category selection dialog. */
private boolean m_displayCategorySelectionCollapsed;
/**
* Creates a new instance for the workplace manager, will be called by the workplace configuration manager.<p>
*/
public CmsWorkplaceManager() {
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WORKPLACE_INITIALIZE_START_0));
}
m_locales = new ArrayList<Locale>();
m_labelSiteFolders = new ArrayList<String>();
m_localizedFolders = new ArrayList<String>();
m_autoLockResources = true;
m_categoryFolder = CmsCategoryService.REPOSITORY_BASE_FOLDER;
m_xmlContentAutoCorrect = true;
m_showUserGroupIcon = true;
m_dialogHandler = new HashMap<String, I_CmsDialogHandler>();
m_views = new ArrayList<CmsWorkplaceView>();
m_exportPoints = new HashSet<CmsExportPoint>();
m_editorHandler = new CmsEditorHandler();
m_fileMaxUploadSize = -1;
m_fileViewSettings = new CmsRfsFileViewer();
m_explorerTypeSettingsFromXml = new ArrayList<CmsExplorerTypeSettings>();
m_explorerTypeSettingsFromModules = new ArrayList<CmsExplorerTypeSettings>();
m_defaultPropertiesOnStructure = true;
m_enableAdvancedPropertyTabs = true;
m_defaultUserSettings = new CmsDefaultUserSettings();
m_defaultAccess = new CmsExplorerTypeAccess();
m_galleries = new HashMap<String, A_CmsAjaxGallery>();
flushMessageCache();
m_preEditorConditionDefinitions = new ArrayList<I_CmsPreEditorActionDefinition>();
m_editorCssHandlers = new ArrayList<I_CmsEditorCssHandler>();
m_synchronizeExcludePatterns = new ArrayList<Pattern>();
// important to set this to null to avoid unnecessary overhead during configuration phase
m_explorerTypeSettings = null;
CacheBuilder<Object, Object> cb = CacheBuilder.newBuilder().expireAfterWrite(
2,
TimeUnit.MINUTES).concurrencyLevel(3);
m_workplaceServerUserChecks = cb.build();
}
/**
* Returns true if the provided request was done by a Workplace user.<p>
*
* @param req the request to check
*
* @return true if the provided request was done by a Workplace user
*/
public static boolean isWorkplaceUser(HttpServletRequest req) {
HttpSession session = req.getSession(false);
if (session != null) {
// if a session is available, check for a workplace configuration
CmsWorkplaceSettings workplaceSettings = (CmsWorkplaceSettings)session.getAttribute(
CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS);
return ((null != workplaceSettings) && !workplaceSettings.getUser().isGuestUser());
}
// no session means no workplace use
return false;
}
/**
* Adds an account info.<p>
*
* @param info the account info to add
*/
public void addAccountInfo(CmsAccountInfo info) {
if (m_accountInfos == null) {
m_accountInfos = new ArrayList<CmsAccountInfo>();
}
m_accountInfos.add(info);
}
/**
* Adds an account info.<p>
*
* @param field the field
* @param addInfoKey the additional info key
* @param editable the editable flag
*/
public void addAccountInfo(String field, String addInfoKey, String editable) {
addAccountInfo(new CmsAccountInfo(field, addInfoKey, editable));
}
/**
* Adds a dialog handler instance to the list of configured dialog handlers.<p>
*
* @param clazz the instantiated dialog handler to add
*/
public void addDialogHandler(I_CmsDialogHandler clazz) {
m_dialogHandler.put(clazz.getDialogHandler(), clazz);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_ADD_DIALOG_HANDLER_2,
clazz.getDialogHandler(),
clazz.getClass().getName()));
}
}
/**
* Adds an editor CSS handler class to the list of handlers.<p>
*
* @param editorCssHandlerClassName full class name of the css handler class
*/
public void addEditorCssHandler(String editorCssHandlerClassName) {
try {
I_CmsEditorCssHandler editorCssHandler = (I_CmsEditorCssHandler)Class.forName(
editorCssHandlerClassName).newInstance();
m_editorCssHandlers.add(editorCssHandler);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(Messages.INIT_EDITOR_CSSHANDLER_CLASS_1, editorCssHandlerClassName));
}
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(Messages.LOG_INVALID_EDITOR_CSSHANDLER_1, editorCssHandlerClassName),
e);
}
}
/**
* Adds an editor CSS handler class at the first position of the list of handlers.<p>
*
* @param editorCssHandlerClassName full class name of the css handler class
*/
public void addEditorCssHandlerToHead(String editorCssHandlerClassName) {
try {
I_CmsEditorCssHandler editorCssHandler = (I_CmsEditorCssHandler)Class.forName(
editorCssHandlerClassName).newInstance();
List<I_CmsEditorCssHandler> editorCssHandlers = new ArrayList<I_CmsEditorCssHandler>();
editorCssHandlers.add(editorCssHandler);
editorCssHandlers.addAll(m_editorCssHandlers);
m_editorCssHandlers = editorCssHandlers;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(Messages.INIT_EDITOR_CSSHANDLER_CLASS_1, editorCssHandlerClassName));
}
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(Messages.LOG_INVALID_EDITOR_CSSHANDLER_1, editorCssHandlerClassName),
e);
}
}
/**
* Adds an explorer type setting object to the list of type settings.<p>
*
* @param settings the explorer type settings
*/
public void addExplorerTypeSetting(CmsExplorerTypeSettings settings) {
m_explorerTypeSettingsFromXml.add(settings);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ADD_TYPE_SETTING_1, settings.getName()));
}
if (m_explorerTypeSettings != null) {
// reset the list of all explorer type settings, but not during startup
initExplorerTypeSettings();
}
}
/**
* Adds the list of explorer type settings from the given module.<p>
*
* @param module the module witch contains the explorer type settings to add
*/
public void addExplorerTypeSettings(CmsModule module) {
List<CmsExplorerTypeSettings> explorerTypes = module.getExplorerTypes();
if ((explorerTypes != null) && (explorerTypes.size() > 0)) {
Iterator<CmsExplorerTypeSettings> i = explorerTypes.iterator();
while (i.hasNext()) {
CmsExplorerTypeSettings settings = i.next();
if (m_explorerTypeSettingsFromModules.contains(settings)) {
m_explorerTypeSettingsFromModules.remove(settings);
}
m_explorerTypeSettingsFromModules.add(settings);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(Messages.INIT_ADD_TYPE_SETTING_1, settings.getName()));
}
}
// reset the list of all explorer type settings
initExplorerTypeSettings();
}
}
/**
* Adds newly created export point to the workplace configuration.<p>
*
* @param uri the export point uri
* @param destination the export point destination
*/
public void addExportPoint(String uri, String destination) {
CmsExportPoint point = new CmsExportPoint(uri, destination);
m_exportPoints.add(point);
if (CmsLog.INIT.isInfoEnabled() && (point.getDestinationPath() != null)) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_ADD_EXPORT_POINT_2,
point.getUri(),
point.getDestinationPath()));
}
}
/**
* Adds a folder to the list of labeled folders.<p>
*
* @param uri the folder uri to add
*/
public void addLabeledFolder(String uri) {
m_labelSiteFolders.add(uri);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LABEL_LINKS_IN_FOLDER_1, uri));
}
}
/**
* Adds a new folder to the list of localized workplace folders.<p>
*
* @param uri a new folder to add to the list of localized workplace folders
*/
public void addLocalizedFolder(String uri) {
m_localizedFolders.add(uri);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WORKPLACE_LOCALIZED_1, uri));
}
}
/**
* Adds an initialized condition definition class that is triggered before opening the editor.<p>
*
* @param preEditorCondition the initialized condition definition class
*/
public void addPreEditorConditionDefinition(I_CmsPreEditorActionDefinition preEditorCondition) {
m_preEditorConditionDefinitions.add(preEditorCondition);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_EDITOR_PRE_ACTION_2,
preEditorCondition.getClass().getName(),
preEditorCondition.getResourceTypeName()));
}
}
/**
* Adds a condition definition class for a given resource type name that is triggered before opening the editor.<p>
*
* @param resourceTypeName the name of the resource type
* @param preEditorConditionDefinitionClassName full class name of the condition definition class
*/
public void addPreEditorConditionDefinition(String resourceTypeName, String preEditorConditionDefinitionClassName) {
try {
I_CmsPreEditorActionDefinition preEditorCondition = (I_CmsPreEditorActionDefinition)Class.forName(
preEditorConditionDefinitionClassName).newInstance();
preEditorCondition.setResourceTypeName(resourceTypeName);
m_preEditorConditionDefinitions.add(preEditorCondition);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_EDITOR_PRE_ACTION_2,
preEditorConditionDefinitionClassName,
resourceTypeName));
}
} catch (Exception e) {
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_INVALID_EDITOR_PRE_ACTION_1,
preEditorConditionDefinitionClassName),
e);
}
}
/**
* Adds a pattern to be excluded in VFS synchronization.<p>
*
* @param pattern a java regex to applied on the file name
*/
public void addSynchronizeExcludePattern(String pattern) {
try {
m_synchronizeExcludePatterns.add(Pattern.compile(pattern));
} catch (PatternSyntaxException e) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_INVALID_SYNCHRONIZE_EXCLUDE_PATTERN_1, pattern), e);
}
}
/**
* Returns if the autolock resources feature is enabled.<p>
*
* @return true if the autolock resources feature is enabled, otherwise false
*/
public boolean autoLockResources() {
return m_autoLockResources;
}
/**
* Checks whether the workplace is accessed through the workplace server, and sends an error message otherwise.<p>
*
* @param request the request to check
* @param cms the CmsObject to use
*/
public void checkWorkplaceRequest(HttpServletRequest request, CmsObject cms) {
try {
if ((OpenCms.getSiteManager().getSites().size() > 1)
&& !OpenCms.getSiteManager().isWorkplaceRequest(request)) {
// this is a multi site-configuration, but not a request to the configured Workplace site
CmsUser user = cms.getRequestContext().getCurrentUser();
// to limit the number of times broadcast is called for a user, we use an expiring cache
// with the user name as key
if (null == m_workplaceServerUserChecks.getIfPresent(user.getName())) {
m_workplaceServerUserChecks.put(user.getName(), "");
OpenCms.getSessionManager().sendBroadcast(
null,
Messages.get().getBundle(getWorkplaceLocale(cms)).key(
Messages.ERR_WORKPLACE_SERVER_CHECK_FAILED_0),
user,
ContentMode.plain);
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
/**
* Implements the event listener of this class.<p>
*
* @see org.opencms.main.I_CmsEventListener#cmsEvent(org.opencms.main.CmsEvent)
*/
public void cmsEvent(CmsEvent event) {
switch (event.getType()) {
case I_CmsEventListener.EVENT_CLEAR_CACHES:
flushMessageCache();
m_editorDisplayOptions.clearCache();
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_EVENT_CLEAR_CACHES_0));
}
break;
default: // no operation
}
}
/**
* Creates a temporary file which is needed while working in an editor with preview option.<p>
*
* <i>Note</i>: This method is synchronized to avoid rare issues that might be caused by
* double requests fired by some browser/OS combinations.<p>
*
* @param cms the cms context
* @param resourceName the name of the resource to copy
* @param currentProjectId the id of the project to work with
*
* @return the file name of the temporary file
*
* @throws CmsException if something goes wrong
*/
public synchronized String createTempFile(CmsObject cms, String resourceName, CmsUUID currentProjectId)
throws CmsException {
if (!cms.hasPermissions(cms.readResource(resourceName, CmsResourceFilter.ALL), CmsPermissionSet.ACCESS_WRITE)) {
throw new CmsPermissionViolationException(
org.opencms.db.Messages.get().container(org.opencms.db.Messages.ERR_PERM_DENIED_2, resourceName, "w"));
}
// initialize admin cms context
CmsObject adminCms = getAdminCms(cms);
// generate the filename of the temporary file
String temporaryFilename = CmsWorkplace.getTemporaryFileName(resourceName);
// check if the temporary file is already present
if (adminCms.existsResource(temporaryFilename, CmsResourceFilter.ALL)) {
// delete old temporary file
if (!cms.getLock(temporaryFilename).isUnlocked()) {
// steal lock
cms.changeLock(temporaryFilename);
} else {
// lock resource to current user
cms.lockResource(temporaryFilename);
}
cms.deleteResource(temporaryFilename, CmsResource.DELETE_PRESERVE_SIBLINGS);
}
try {
// switch to the temporary file project
adminCms.getRequestContext().setCurrentProject(cms.readProject(getTempFileProjectId()));
// copy the file to edit to a temporary file
adminCms.copyResource(resourceName, temporaryFilename, CmsResource.COPY_AS_NEW);
} finally {
// switch back to current project
adminCms.getRequestContext().setCurrentProject(cms.readProject(currentProjectId));
}
try {
// switch to the temporary file project
cms.getRequestContext().setCurrentProject(
cms.readProject(OpenCms.getWorkplaceManager().getTempFileProjectId()));
// lock the temporary file
cms.changeLock(temporaryFilename);
// touch the temporary file
cms.setDateLastModified(temporaryFilename, System.currentTimeMillis(), false);
// set the temporary file flag
CmsResource tempFile = cms.readResource(temporaryFilename, CmsResourceFilter.ALL);
int flags = tempFile.getFlags();
if ((flags & CmsResource.FLAG_TEMPFILE) == 0) {
flags += CmsResource.FLAG_TEMPFILE;
}
cms.chflags(temporaryFilename, flags);
// remove eventual release & expiration date from temporary file to make preview in editor work
cms.setDateReleased(temporaryFilename, CmsResource.DATE_RELEASED_DEFAULT, false);
cms.setDateExpired(temporaryFilename, CmsResource.DATE_EXPIRED_DEFAULT, false);
if (cms.hasPermissions(tempFile, CmsPermissionSet.ACCESS_CONTROL)) {
cms.chacc(
temporaryFilename,
I_CmsPrincipal.PRINCIPAL_GROUP,
OpenCms.getDefaultUsers().getGroupUsers(),
"-v");
}
} finally {
// switch back to current project
cms.getRequestContext().setCurrentProject(cms.readProject(currentProjectId));
}
return temporaryFilename;
}
/**
* Flushes the cached workplace messages.<p>
*/
public void flushMessageCache() {
// clear the cached message objects
m_messages = new HashMap<Locale, CmsWorkplaceMessages>();
if (LOG.isDebugEnabled()) {
try {
throw new RuntimeException("Tracing exception");
} catch (Exception e) {
LOG.info("Tracing call to CmsWorkplaceManager.flushMessageCache method.", e);
}
}
}
/**
* Gets the value of the acacia-unlock configuration option (null if not set explicitly).<p>
*
* @return the value of the acacia-unlock configuration option
*/
public String getAcaciaUnlock() {
return m_acaciaUnlock;
}
/**
* Returns the account infos.<p>
*
* @return the account infos
*/
public List<CmsAccountInfo> getAccountInfos() {
if (m_accountInfos == null) {
return Collections.unmodifiableList(Arrays.asList(DEFAULT_ACCOUNT_INFOS));
} else {
return Collections.unmodifiableList(m_accountInfos);
}
}
/**
* Gets the additional log folder configuration.<p>
*
* @return the additional log folder configuration
*/
public CmsAdditionalLogFolderConfig getAdditionalLogFolderConfiguration() {
return m_logFolderConfig;
}
/**
* Returns the name of the local category folder(s).<p>
*
* @return the name of the local category folder(s)
*/
public String getCategoryFolder() {
return m_categoryFolder;
}
/**
* Returns the configured account infos.<p>
*
* @return the configured account infos
*/
public List<CmsAccountInfo> getConfiguredAccountInfos() {
return m_accountInfos;
}
/**
* Gets the access object of the type settings.<p>
*
* @return access object of the type settings
*/
public CmsExplorerTypeAccess getDefaultAccess() {
return m_defaultAccess;
}
/**
* Returns the Workplace default locale.<p>
*
* @return the Workplace default locale
*/
public Locale getDefaultLocale() {
return m_defaultLocale;
}
/**
* Gets the default name pattern for the given type.<p>
*
* @param type the type name
* @return the default name pattern for the type
*/
public String getDefaultNamePattern(String type) {
CmsExplorerTypeSettings settings = getExplorerTypeSetting(type);
if ((settings != null) && (settings.getNamePattern() != null)) {
return settings.getNamePattern();
}
if (type.equals("sitemap_config") || type.equals("module_config")) {
return ".config%(number)";
}
if (type.equals("content_folder")) {
return ".content%(number)";
}
return "new_" + type + "%(number)";
}
/**
* Returns the Workplace default user settings.<p>
*
* @return the Workplace default user settings
*/
public CmsDefaultUserSettings getDefaultUserSettings() {
return m_defaultUserSettings;
}
/**
* Returns all instantiated dialog handlers for the workplace.<p>
*
* @return all instantiated dialog handlers for the workplace
*/
public Map<String, I_CmsDialogHandler> getDialogHandler() {
return m_dialogHandler;
}
/**
* Returns the instantiated dialog handler class for the key or null, if there is no mapping for the key.<p>
*
* @param key the key whose associated value is to be returned
*
* @return the instantiated dialog handler class for the key
*/
public I_CmsDialogHandler getDialogHandler(String key) {
return m_dialogHandler.get(key);
}
/**
* Returns a new instance of the configured direct edit provider.<p>
*
* @return a new instance of the configured direct edit provider
*/
public I_CmsDirectEditProvider getDirectEditProvider() {
return m_directEditProvider.newInstance();
}
/**
* Returns the instantiated editor action handler class.<p>
*
* @return the instantiated editor action handler class
*/
public I_CmsEditorActionHandler getEditorActionHandler() {
return m_editorAction;
}
/**
* Returns the instantiated editor CSS handler classes.<p>
*
* @return the instantiated editor CSS handler classes
*/
public List<I_CmsEditorCssHandler> getEditorCssHandlers() {
return m_editorCssHandlers;
}
/**
* Returns the instantiated editor display option class.<p>
*
* @return the instantiated editor display option class
*/
public CmsEditorDisplayOptions getEditorDisplayOptions() {
return m_editorDisplayOptions;
}
/**
* Returns the instantiated editor handler class.<p>
*
* @return the instantiated editor handler class
*/
public I_CmsEditorHandler getEditorHandler() {
return m_editorHandler;
}
/**
* Returns the element delete mode.<p>
*
* @return the element delete mode
*/
public ElementDeleteMode getElementDeleteMode() {
return m_elementDeleteMode;
}
/**
* Returns the configured workplace encoding.<p>
*
* @return the configured workplace encoding
*/
public String getEncoding() {
return m_encoding;
}
/**
* Returns the explorer type settings for the specified resource type.<p>
*
* @param type the resource type for which the settings are required
*
* @return the explorer type settings for the specified resource type
*/
public CmsExplorerTypeSettings getExplorerTypeSetting(String type) {
return m_explorerTypeSettingsMap.get(type);
}
/**
* Returns the list of explorer type settings.<p>
*
* These settings provide information for the new resource dialog and the context menu appearance.<p>
*
* @return the list of explorer type settings
*/
public List<CmsExplorerTypeSettings> getExplorerTypeSettings() {
if (m_explorerTypeSettings == null) {
// initialize all explorer type settings if not already done
initExplorerTypeSettings();
}
return m_explorerTypeSettings;
}
/**
* Gets the explorer types for the given view name.<p>
*
* @param viewName the view name
*
* @return the explorer names for the given view names
*/
public List<CmsExplorerTypeSettings> getExplorerTypesForView(String viewName) {
List<CmsExplorerTypeSettings> result = Lists.newArrayList();
for (CmsExplorerTypeSettings explorerType : getExplorerTypeSettings()) {
String currentViewName = explorerType.getElementView();
if (currentViewName == null) {
currentViewName = getDefaultView(explorerType.getName());
}
if ((currentViewName != null) && currentViewName.equals(viewName)) {
if (OpenCms.getResourceManager().hasResourceType(explorerType.getName())) {
result.add(explorerType);
}
} else if (CmsResourceTypeFolder.getStaticTypeName().equals(explorerType.getName())
&& "view_folders|view_basic".contains(viewName)) {
result.add(explorerType);
}
}
return result;
}
/**
* Gets the element views generated from explorer types.<p>
*
* @return the map of element views from the explorer types
*/
public Map<CmsUUID, CmsElementView> getExplorerTypeViews() {
return Collections.unmodifiableMap(m_explorerTypeViews);
}
/**
* Returns the set of configured export points for the workplace.<p>
*
* @return the set of configured export points for the workplace
*/
public Set<CmsExportPoint> getExportPoints() {
return m_exportPoints;
}
/**
* Returns the value (in bytes) for the maximum file upload size of the current user.<p>
*
* @param cms the initialized CmsObject
*
* @return the value (in bytes) for the maximum file upload size
*/
public long getFileBytesMaxUploadSize(CmsObject cms) {
int maxFileSize = getFileMaxUploadSize();
long maxFileSizeBytes = maxFileSize * 1024;
// check if current user belongs to Admin group, if so no file upload limit
if ((maxFileSize <= 0) || OpenCms.getRoleManager().hasRole(cms, CmsRole.VFS_MANAGER)) {
maxFileSizeBytes = -1;
}
return maxFileSizeBytes;
}
/**
* Returns the value (in kb) for the maximum file upload size.<p>
*
* @return the value (in kb) for the maximum file upload size
*/
public int getFileMaxUploadSize() {
return m_fileMaxUploadSize;
}
/**
* Returns the system-wide file view settings for the workplace.<p>
*
* Note that this instance may not modified (invocation of setters) directly or a
* <code>{@link org.opencms.main.CmsRuntimeException}</code> will be thrown.<p>
*
* It has to be cloned first and then may be written back to the workplace settings using
* method {@link #setFileViewSettings(CmsObject, org.opencms.util.CmsRfsFileViewer)}.<p>
*
* @return the system-wide file view settings for the workplace
*/
public CmsRfsFileViewer getFileViewSettings() {
return m_fileViewSettings;
}
/**
* Returns a collection of all available galleries.<p>
*
* The Map has the gallery type name as key and an instance of the
* gallery class (not completely initialized) as value.<p>
*
* @return a collection of all available galleries
*/
public Map<String, A_CmsAjaxGallery> getGalleries() {
return m_galleries;
}
/**
* Returns the gallery default scope.<p>
*
* @return the gallery default scope
*/
public CmsGallerySearchScope getGalleryDefaultScope() {
CmsGallerySearchScope result = CmsGallerySearchScope.siteShared;
if (m_galleryDefaultScope != null) {
try {
result = CmsGallerySearchScope.valueOf(m_galleryDefaultScope);
} catch (Throwable t) {
// ignore
}
}
return result;
}
/**
* Gets the configured gallery default scope as a string.<p>
*
* @return the gallery default scope as a string
*/
public String getGalleryDefaultScopeString() {
return m_galleryDefaultScope;
}
/**
* Returns the object used for translating group names.<p>
*
* @return the group name translator
*/
public I_CmsGroupNameTranslation getGroupNameTranslation() {
if (m_groupNameTranslation != null) {
return m_groupNameTranslation;
}
if (m_groupTranslationClass != null) {
try {
m_groupNameTranslation = (I_CmsGroupNameTranslation)Class.forName(
m_groupTranslationClass).newInstance();
return m_groupNameTranslation;
} catch (ClassNotFoundException e) {
LOG.error(e.getLocalizedMessage(), e);
} catch (IllegalAccessException e) {
LOG.error(e.getLocalizedMessage(), e);
} catch (InstantiationException e) {
LOG.error(e.getLocalizedMessage(), e);
} catch (ClassCastException e) {
LOG.error(e.getLocalizedMessage(), e);
}
m_groupNameTranslation = getDefaultGroupNameTranslation();
return m_groupNameTranslation;
} else {
m_groupNameTranslation = getDefaultGroupNameTranslation();
return m_groupNameTranslation;
}
}
/**
* Returns the configured class name for translating group names.<p>
*
* @return the group translation class name
*/
public String getGroupTranslationClass() {
return m_groupTranslationClass;
}
/**
* @see org.opencms.i18n.I_CmsLocaleHandler#getI18nInfo(javax.servlet.http.HttpServletRequest, org.opencms.file.CmsUser, org.opencms.file.CmsProject, java.lang.String)
*/
public CmsI18nInfo getI18nInfo(HttpServletRequest req, CmsUser user, CmsProject project, String resource) {
Locale locale = null;
// try to read locale from session
if (req != null) {
// set the request character encoding
try {
req.setCharacterEncoding(m_encoding);
} catch (UnsupportedEncodingException e) {
// should not ever really happen
LOG.error(Messages.get().getBundle().key(Messages.LOG_UNSUPPORTED_ENCODING_SET_1, m_encoding), e);
}
// read workplace settings
HttpSession session = req.getSession(false);
if (session != null) {
CmsWorkplaceSettings settings = (CmsWorkplaceSettings)session.getAttribute(
CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS);
if (settings != null) {
locale = settings.getUserSettings().getLocale();
}
}
}
if (locale == null) {
// no session available, try to read the locale form the user additional info
if (!user.isGuestUser()) {
// check user settings only for "real" users
CmsUserSettings settings = new CmsUserSettings(user);
locale = settings.getLocale();
}
if (req != null) {
List<Locale> acceptedLocales = (new CmsAcceptLanguageHeaderParser(
req,
getDefaultLocale())).getAcceptedLocales();
if ((locale != null) && (!acceptedLocales.contains(locale))) {
acceptedLocales.add(0, locale);
}
locale = OpenCms.getLocaleManager().getFirstMatchingLocale(acceptedLocales, m_locales);
}
// if no locale was found, use the default
if (locale == null) {
locale = getDefaultLocale();
}
}
return new CmsI18nInfo(locale, m_encoding);
}
/**
* Returns a list of site folders which generate labeled links.<p>
*
* @return a list of site folders which generate labeled links
*/
public List<String> getLabelSiteFolders() {
return m_labelSiteFolders;
}
/**
* Returns the list of available workplace locales, sorted ascending.<p>
*
* Please note: Be careful not to modify the returned Set as it is not a clone.<p>
*
* @return the set of available workplace locales
*/
public List<Locale> getLocales() {
return m_locales;
}
/**
* Returns the configured list of localized workplace folders.<p>
*
* @return the configured list of localized workplace folders
*/
public List<String> getLocalizedFolders() {
return m_localizedFolders;
}
/**
* Returns the {@link CmsWorkplaceMessages} for the given locale.<p>
*
* The workplace messages are a collection of resource bundles, containing the messages
* for all OpenCms core bundles and of all initialized modules.<p>
*
* Please note that the message objects are cached internally.
* The returned message object should therefore never be modified directly in any way.<p>
*
* @param locale the locale to get the messages for
*
* @return the {@link CmsWorkplaceMessages} for the given locale
*/
public CmsWorkplaceMessages getMessages(Locale locale) {
CmsWorkplaceMessages result = m_messages.get(locale);
if (result != null) {
// messages have already been read
return result;
}
// messages have not been read so far
synchronized (this) {
// check again
result = m_messages.get(locale);
if (result == null) {
result = new CmsWorkplaceMessages(locale);
m_messages.put(locale, result);
}
}
return result;
}
/**
* Returns the post upload handler.<p>
*
* @return the post upload handler
*/
public I_CmsPostUploadDialogHandler getPostUploadHandler() {
return m_postUploadHandler;
}
/**
* Returns the condition definition for the given resource type that is triggered before opening the editor.<p>
*
* @param resourceType the resource type
*
* @return the condition definition for the given resource type class name or null if none is found
*/
public I_CmsPreEditorActionDefinition getPreEditorConditionDefinition(I_CmsResourceType resourceType) {
Iterator<I_CmsPreEditorActionDefinition> i = m_preEditorConditionDefinitions.iterator();
I_CmsPreEditorActionDefinition result = null;
int matchResult = -1;
while (i.hasNext()) {
I_CmsPreEditorActionDefinition currentDefinition = i.next();
if (resourceType.getClass().isInstance(currentDefinition.getResourceType())) {
// now determine the match count...
int matchDistance = 0;
Class<?> superClass = resourceType.getClass();
while (true) {
// check if a super class is present
if (superClass == null) {
break;
}
if (superClass.getName().equals(currentDefinition.getResourceType().getClass().getName())) {
break;
}
matchDistance += 1;
superClass = superClass.getSuperclass();
}
if (matchResult != -1) {
if (matchDistance < matchResult) {
matchResult = matchDistance;
result = currentDefinition;
}
} else {
matchResult = matchDistance;
result = currentDefinition;
}
}
}
return result;
}
/**
* Returns the condition definitions for the different resource
* types which are triggered before opening the editor.<p>
*
* @return the condition definitions
*/
public List<I_CmsPreEditorActionDefinition> getPreEditorConditionDefinitions() {
return m_preEditorConditionDefinitions;
}
/**
* Returns the repository folder handler.<p>
*
* @return the repository folder handler
*/
public I_CmsRepositoryFolderHandler getRepositoryFolderHandler() {
if (m_repositoryFolderHandler == null) {
// handler has not been configured, use the default one
m_repositoryFolderHandler = new CmsRepositoryFolderHandler();
}
return m_repositoryFolderHandler;
}
/**
* Returns Regex patterns that should be excluded from synchronization.<p>
*
* @return the exclude patterns
*/
public ArrayList<Pattern> getSynchronizeExcludePatterns() {
return m_synchronizeExcludePatterns;
}
/**
* Returns the id of the temporary file project required by the editors.<p>
*
* @return the id of the temporary file project required by the editors
*/
public CmsUUID getTempFileProjectId() {
if (m_tempFileProject != null) {
return m_tempFileProject.getUuid();
} else {
return null;
}
}
/**
* Returns the tool manager.<p>
*
* @return the tool manager
*/
public CmsToolManager getToolManager() {
if (m_toolManager == null) {
m_toolManager = new CmsToolManager();
}
return m_toolManager;
}
/**
* Gets the upload hook URI which should be opened for an upload to a given folder.<p>
* This method will return null if no upload hook should be used for the given upload folder.<p>
*
* The API for this upload hook is as follows:
*
* The upload hook will be called with the following parameters:
*
* resources (required): a comma separated list of the structure ids of the uploaded resources
* if this is omitted
* closelink (optional): a link which should be opened once the upload hook has finished whatever
* it is doing
*
* @param cms the current CMS context
* @param uploadFolder the folder for which the upload hook should be found
*
* @return the URI of the upload hook or null
*/
public String getUploadHook(CmsObject cms, String uploadFolder) {
if (m_postUploadHandler != null) {
return m_postUploadHandler.getUploadHook(cms, uploadFolder);
}
I_CmsDialogHandler handler = getDialogHandler(CmsDialogSelector.DIALOG_PROPERTY);
if ((handler != null) && (handler instanceof I_CmsPostUploadDialogHandler)) {
return ((I_CmsPostUploadDialogHandler)handler).getUploadHook(cms, uploadFolder);
} else {
return null;
}
}
/**
* Returns the user additional information configuration Manager.<p>
*
* @return the user additional information configuration manager
*/
public CmsWorkplaceUserInfoManager getUserInfoManager() {
return m_userInfoManager;
}
/**
* Returns the user list mode as a string.<p>
*
* @return the user list mode as a string
*/
public String getUserListModeString() {
return m_userListMode;
}
/**
* Returns the map of configured workplace views.<p>
*
* @return the map of configured workplace views
*/
public List<CmsWorkplaceView> getViews() {
return m_views;
}
/**
* Returns the instantiated workplace editor manager class.<p>
*
* @return the instantiated workplace editor manager class
*/
public CmsWorkplaceEditorManager getWorkplaceEditorManager() {
return m_editorManager;
}
/**
* Returns the list of explorer type settings configured in the opencms-workplace.xml file.<p>
*
* @return the list of explorer type settings
*/
public List<CmsExplorerTypeSettings> getWorkplaceExplorerTypeSettings() {
return Collections.unmodifiableList(m_explorerTypeSettingsFromXml);
}
/**
* Returns the workplace locale from the current user's settings.<p>
*
* @param cms the current cms object
*
* @return the workplace locale
*/
public Locale getWorkplaceLocale(CmsObject cms) {
return getWorkplaceLocale(cms.getRequestContext());
}
/**
* Gets the workplace locale for the given request context.<p>
*
* @param requestContext the request context
*
* @return the workplace locale for the request context
*/
public Locale getWorkplaceLocale(CmsRequestContext requestContext) {
Locale wpLocale = new CmsUserSettings(requestContext.getCurrentUser()).getLocale();
if (wpLocale == null) {
// fall back
wpLocale = getDefaultLocale();
if (wpLocale == null) {
// fall back
wpLocale = requestContext.getLocale();
}
}
return wpLocale;
}
/**
* Returns the workplace locale for the user.
* @param user the user to get the workplace locale for.
* @return the workplace locale for the user.
*/
public Locale getWorkplaceLocale(CmsUser user) {
Locale wpLocale = new CmsUserSettings(user).getLocale();
if (wpLocale == null) {
// fall back
wpLocale = OpenCms.getWorkplaceManager().getDefaultLocale();
if (wpLocale == null) {
// fall back
wpLocale = CmsLocaleManager.MASTER_LOCALE;
}
}
return wpLocale;
}
/**
* @see org.opencms.i18n.I_CmsLocaleHandler#initHandler(org.opencms.file.CmsObject)
*/
public void initHandler(CmsObject cms) {
// initialize the workplace locale set
m_locales = initWorkplaceLocales(cms);
}
public synchronized void initialize(CmsObject cms) throws CmsException, CmsRoleViolationException {
try {
OpenCms.getRoleManager().checkRole(cms, CmsRole.WORKPLACE_MANAGER);
// set the workplace encoding
try {
// workplace encoding is set on the workplace parent folder /system/workplace/
CmsResource wpFolderRes = cms.readResource(CmsWorkplace.VFS_PATH_WORKPLACE);
m_encoding = CmsLocaleManager.getResourceEncoding(cms, wpFolderRes);
} catch (CmsVfsResourceNotFoundException e) {
// workplace parent folder could not be read - use configured default encoding
m_encoding = OpenCms.getSystemInfo().getDefaultEncoding();
}
// configure direct edit provider with default if not available
if (m_directEditProvider == null) {
m_directEditProvider = new CmsDirectEditDefaultProvider();
}
// throw away all currently configured module explorer types
m_explorerTypeSettingsFromModules.clear();
// now add the additional explorer types found in the modules
CmsModuleManager moduleManager = OpenCms.getModuleManager();
Iterator<String> moduleNameIterator = moduleManager.getModuleNames().iterator();
while (moduleNameIterator.hasNext()) {
CmsModule module = moduleManager.getModule(moduleNameIterator.next());
if (module != null) {
addExplorerTypeSettings(module);
}
}
// initialize the explorer type settings
initExplorerTypeSettings();
// initialize the workplace views
initWorkplaceViews(cms);
// initialize the workplace editor manager
m_editorManager = new CmsWorkplaceEditorManager(cms);
// initialize the locale handler
initHandler(cms);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_VFS_ACCESS_INITIALIZED_0));
}
try {
// read the temporary file project
m_tempFileProject = cms.readProject(I_CmsProjectDriver.TEMP_FILE_PROJECT_NAME);
} catch (CmsException e) {
// during initial setup of OpenCms the temp file project does not yet exist...
LOG.error(Messages.get().getBundle().key(Messages.LOG_NO_TEMP_FILE_PROJECT_0));
}
// create an instance of editor display options
m_editorDisplayOptions = new CmsEditorDisplayOptions();
// throw away all current gallery settings
m_galleries.clear();
// read out the configured gallery classes
Iterator<I_CmsResourceType> typesIterator = OpenCms.getResourceManager().getResourceTypes().iterator();
while (typesIterator.hasNext()) {
I_CmsResourceType resourceType = typesIterator.next();
if (resourceType instanceof CmsResourceTypeFolderExtended) {
// found a configured extended folder resource type
CmsResourceTypeFolderExtended galleryType = (CmsResourceTypeFolderExtended)resourceType;
String folderClassName = galleryType.getFolderClassName();
if (CmsStringUtil.isNotEmpty(folderClassName)) {
// only process this as a gallery if the folder name is not empty
try {
// check, if the folder class is a subclass of A_CmsGallery
if (A_CmsAjaxGallery.class.isAssignableFrom(Class.forName(folderClassName))) {
// create gallery class instance
A_CmsAjaxGallery galleryInstance = (A_CmsAjaxGallery)Class.forName(
folderClassName).newInstance();
// set gallery folder resource type
galleryInstance.setResourceType(galleryType);
// store the gallery class instance with the type name as lookup key
m_galleries.put(galleryType.getTypeName(), galleryInstance);
}
} catch (ClassNotFoundException e) {
LOG.error(e.getLocalizedMessage());
} catch (InstantiationException e) {
LOG.error(e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.error(e.getLocalizedMessage());
}
}
}
}
getDefaultUserSettings().initPreferences(this);
// configures the tool manager
getToolManager().configure(cms);
flushMessageCache();
// register this object as event listener
OpenCms.addCmsEventListener(this, new int[] {I_CmsEventListener.EVENT_CLEAR_CACHES});
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
throw new CmsException(Messages.get().container(Messages.ERR_INITIALIZE_WORKPLACE_0));
}
m_adminCms = cms;
}
/**
* Returns the default property editing mode on resources.<p>
*
* @return the default property editing mode on resources
*/
public boolean isDefaultPropertiesOnStructure() {
return m_defaultPropertiesOnStructure;
}
/**
* Returns a flag, indicating if the categories should be displayed separated by repository in the category selection dialog.
*
* @return a flag, indicating if the categories should be displayed separated by repository in the category selection dialog.
*/
public boolean isDisplayCategoriesByRepository() {
return m_displayCategoriesByRepository;
}
/**
* Returns a flag, indicating if the category selection dialog should have all entries completely collapsed when opened.
*
* @return a flag, indicating if the category selection dialog should have all entries completely collapsed when opened.
*/
public boolean isDisplayCategorySelectionCollapsed() {
return m_displayCategorySelectionCollapsed;
}
/**
* Returns if tabs in the advanced property dialog are enabled.<p>
*
* @return <code>true</code> if tabs should be enabled, otherwise <code>false</code>
*/
public boolean isEnableAdvancedPropertyTabs() {
return m_enableAdvancedPropertyTabs;
}
/**
* Returns true if "keep alive" mode is active.
*
* @return true if the session should be kept alive
*/
public boolean isKeepAlive() {
return isKeepAlive(true).booleanValue();
}
/**
* Returns true if the session should be kept alive.<p>
*
* @param useDefault if true, the default value will be returned if the "keep alive" setting is not explicitly configured
*
* @return True if the "keep alive" mode is active
*/
public Boolean isKeepAlive(boolean useDefault) {
if (m_keepAlive != null) {
return m_keepAlive;
}
if (useDefault) {
return Boolean.TRUE;
} else {
return null;
}
}
/**
* Returns if XML content is automatically corrected when opened with the editor.<p>
*
* @return <code>true</code> if XML content is automatically corrected when opened with the editor, otherwise <code>false</code>
*/
public boolean isXmlContentAutoCorrect() {
return m_xmlContentAutoCorrect;
}
/**
* Returns if lazy user lists are enabled.<p>
*
* @return <code>true</code> if lazy user lists are enabled
*/
public boolean lazyUserListsEnabled() {
return true;
}
/**
* Removes the list of explorer type settings from the given module.<p>
*
* @param module the module witch contains the explorer type settings to remove
*/
public void removeExplorerTypeSettings(CmsModule module) {
List<CmsExplorerTypeSettings> explorerTypes = module.getExplorerTypes();
if ((explorerTypes != null) && (explorerTypes.size() > 0)) {
Iterator<CmsExplorerTypeSettings> i = explorerTypes.iterator();
while (i.hasNext()) {
CmsExplorerTypeSettings settings = i.next();
if (m_explorerTypeSettingsFromModules.contains(settings)) {
m_explorerTypeSettingsFromModules.remove(settings);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_REMOVE_EXPLORER_TYPE_SETTING_1,
settings.getName()));
}
}
}
// reset the list of all explorer type settings
initExplorerTypeSettings();
}
}
/**
* Sets the value of the acacia-unlock configuration option.<p>
*
* @param value the value of the acacia-unlock configuration option
*/
public void setAcaciaUnlock(String value) {
m_acaciaUnlock = value;
}
/**
* Sets the additional log folder configuration.<p>
*
* @param logConfig the additional log folder configuration
*/
public void setAdditionalLogFolderConfiguration(CmsAdditionalLogFolderConfig logConfig) {
m_logFolderConfig = logConfig;
}
/**
* Sets if the autolock resources feature is enabled.<p>
*
* @param value <code>"true"</code> if the autolock resources feature is enabled, otherwise false
*/
public void setAutoLock(String value) {
m_autoLockResources = Boolean.valueOf(value).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
m_autoLockResources ? Messages.INIT_AUTO_LOCK_ENABLED_0 : Messages.INIT_AUTO_LOCK_DISABLED_0));
}
}
/**
* Sets the category display options that affect how the category selection dialog is shown.
*
* @param displayCategoriesByRepository if true, the categories are shown separated by repository.
* @param displayCategorySelectionCollapsed if true, the selection dialog opens showing only the top-level categories
* (or the various repositories) in collapsed state.
*/
public void setCategoryDisplayOptions(
String displayCategoriesByRepository,
String displayCategorySelectionCollapsed) {
m_displayCategoriesByRepository = Boolean.parseBoolean(displayCategoriesByRepository);
m_displayCategorySelectionCollapsed = Boolean.parseBoolean(displayCategorySelectionCollapsed);
}
/**
* Sets the name of the local category folder(s).<p>
*
* @param categoryFolder the name of the local category folder(s)
*/
public void setCategoryFolder(String categoryFolder) {
m_categoryFolder = categoryFolder;
}
/**
* Sets the access object of the type settings.<p>
*
* @param access access object
*/
public void setDefaultAccess(CmsExplorerTypeAccess access) {
m_defaultAccess = access;
}
/**
* Sets the Workplace default locale.<p>
*
* @param locale the locale to set
*/
public void setDefaultLocale(String locale) {
try {
m_defaultLocale = CmsLocaleManager.getLocale(locale);
} catch (Exception e) {
if (CmsLog.INIT.isWarnEnabled()) {
CmsLog.INIT.warn(Messages.get().getBundle().key(Messages.INIT_NONCRIT_ERROR_0), e);
}
}
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DEFAULT_LOCALE_1, m_defaultLocale));
}
}
/**
* Sets the default property editing mode on resources.<p>
*
* @param defaultPropertiesOnStructure the default property editing mode on resources
*/
public void setDefaultPropertiesOnStructure(String defaultPropertiesOnStructure) {
m_defaultPropertiesOnStructure = Boolean.valueOf(defaultPropertiesOnStructure).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
m_defaultPropertiesOnStructure
? Messages.INIT_PROP_ON_STRUCT_TRUE_0
: Messages.INIT_PROP_ON_STRUCT_FALSE_0));
}
}
/**
* Sets the Workplace default user settings.<p>
*
* @param defaultUserSettings the user settings to set
*/
public void setDefaultUserSettings(CmsDefaultUserSettings defaultUserSettings) {
m_defaultUserSettings = defaultUserSettings;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_DEFAULT_USER_SETTINGS_1,
m_defaultUserSettings.getClass().getName()));
}
}
/**
* Sets the direct edit provider.<p>
*
* @param clazz the direct edit provider to set
*/
public void setDirectEditProvider(I_CmsDirectEditProvider clazz) {
m_directEditProvider = clazz;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_DIRECT_EDIT_PROVIDER_1,
m_directEditProvider.getClass().getName()));
}
}
/**
* Sets the editor action class.<p>
*
* @param clazz the editor action class to set
*/
public void setEditorAction(I_CmsEditorActionHandler clazz) {
m_editorAction = clazz;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_EDITOR_ACTION_CLASS_1,
m_editorAction.getClass().getName()));
}
}
/**
* Sets the editor display option class.<p>
*
* @param clazz the editor display option class to set
*/
public void setEditorDisplayOptions(CmsEditorDisplayOptions clazz) {
m_editorDisplayOptions = clazz;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_EDITOR_DISPLAY_OPTS_1,
m_editorAction.getClass().getName()));
}
}
/**
* Sets the editor handler class.<p>
*
* @param clazz the editor handler class to set
*/
public void setEditorHandler(I_CmsEditorHandler clazz) {
m_editorHandler = clazz;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_EDITOR_HANDLER_CLASS_1,
m_editorHandler.getClass().getName()));
}
}
/**
* Sets the element delete mode.<p>
*
* @param deleteMode the element delete mode
*/
public void setElementDeleteMode(String deleteMode) {
try {
m_elementDeleteMode = ElementDeleteMode.valueOf(deleteMode);
} catch (Throwable t) {
m_elementDeleteMode = ElementDeleteMode.askDelete;
}
}
/**
* Sets if tabs in the advanced property dialog are enabled.<p>
*
* @param enableAdvancedPropertyTabs true if tabs should be enabled, otherwise false
*/
public void setEnableAdvancedPropertyTabs(String enableAdvancedPropertyTabs) {
m_enableAdvancedPropertyTabs = Boolean.valueOf(enableAdvancedPropertyTabs).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
m_enableAdvancedPropertyTabs
? Messages.INIT_ADV_PROP_DIALOG_SHOW_TABS_0
: Messages.INIT_ADV_PROP_DIALOG_HIDE_TABS_0));
}
}
/**
* Sets the value (in kb) for the maximum file upload size.<p>
*
* @param value the value (in kb) for the maximum file upload size
*/
public void setFileMaxUploadSize(String value) {
try {
m_fileMaxUploadSize = Integer.valueOf(value).intValue();
} catch (NumberFormatException e) {
// can usually be ignored
if (LOG.isInfoEnabled()) {
LOG.info(e.getLocalizedMessage());
}
m_fileMaxUploadSize = -1;
}
if (CmsLog.INIT.isInfoEnabled()) {
if (m_fileMaxUploadSize > 0) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_MAX_FILE_UPLOAD_SIZE_1,
new Integer(m_fileMaxUploadSize)));
} else {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_MAX_FILE_UPLOAD_SIZE_UNLIMITED_0));
}
}
}
/**
* Sets the system-wide file view settings for the workplace.<p>
*
* @param cms the CmsObject for ensuring security constraints.
*
* @param fileViewSettings the system-wide file view settings for the workplace to set
*
* @throws CmsRoleViolationException if the current user does not own the administrator role ({@link CmsRole#ROOT_ADMIN})
* */
public void setFileViewSettings(CmsObject cms, CmsRfsFileViewer fileViewSettings) throws CmsRoleViolationException {
if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) {
OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN);
}
m_fileViewSettings = fileViewSettings;
// disallow modifications of this "new original"
m_fileViewSettings.setFrozen(true);
}
/**
* Sets the gallery default scope.<p>
*
* @param galleryDefaultScope the gallery default scope
*/
public void setGalleryDefaultScope(String galleryDefaultScope) {
m_galleryDefaultScope = galleryDefaultScope;
try {
CmsGallerySearchScope.valueOf(galleryDefaultScope);
} catch (Throwable t) {
LOG.warn(t.getLocalizedMessage(), t);
}
}
/**
* Sets the group translation class name.<p>
*
* @param translationClassName the group translation class name
*/
public void setGroupTranslationClass(String translationClassName) {
m_groupTranslationClass = translationClassName;
}
/**
* Sets the "keep alive" mode.<p>
*
* @param keepAlive the keep-alive mode
*/
public void setKeepAlive(String keepAlive) {
m_keepAlive = Boolean.valueOf(keepAlive);
}
/**
* Sets the post upload dialog handler.<p>
*
* @param uploadHandler the post upload handler
*/
public void setPostUploadHandler(I_CmsPostUploadDialogHandler uploadHandler) {
m_postUploadHandler = uploadHandler;
}
/**
* Sets the repository folder handler.<p>
*
* @param clazz the repository folder handler
*/
public void setRepositoryFolderHandler(I_CmsRepositoryFolderHandler clazz) {
m_repositoryFolderHandler = clazz;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
org.opencms.configuration.Messages.get().getBundle().key(
org.opencms.configuration.Messages.INIT_REPOSITORY_FOLDER_1,
m_repositoryFolderHandler.getClass().getName()));
}
}
/**
* Sets the tool Manager object.<p>
*
* @param toolManager the tool Manager object to set
*/
public void setToolManager(CmsToolManager toolManager) {
m_toolManager = toolManager;
}
/**
* Sets the user additional information configuration manager.<p>
*
* @param userInfoManager the manager to set
*/
public void setUserInfoManager(CmsWorkplaceUserInfoManager userInfoManager) {
m_userInfoManager = userInfoManager;
}
/**
* Sets the user list mode.<p>
*
* @param mode the user list mode
*/
public void setUserListMode(String mode) {
m_userListMode = mode;
}
/**
* Controls if the user/group icon in the administration view should be shown.<p>
*
* @param value <code>"true"</code> if the user/group icon in the administration view should be shown, otherwise false
*/
public void setUserManagementEnabled(String value) {
m_showUserGroupIcon = Boolean.valueOf(value).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
if (m_showUserGroupIcon) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_USER_MANAGEMENT_ICON_ENABLED_0));
} else {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_USER_MANAGEMENT_ICON_DISABLED_0));
}
}
}
/**
* Sets the auto correction of XML contents when they are opened with the editor.<p>
*
* @param xmlContentAutoCorrect if "true", the content will be corrected without notification, otherwise a confirmation is needed
*/
public void setXmlContentAutoCorrect(String xmlContentAutoCorrect) {
m_xmlContentAutoCorrect = Boolean.valueOf(xmlContentAutoCorrect).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
m_xmlContentAutoCorrect
? Messages.INIT_XMLCONTENT_AUTOCORRECT_ENABLED_0
: Messages.INIT_XMLCONTENT_AUTOCORRECT_DISABLED_0));
}
}
/**
* Returns true if the Acacia editor in standalone mode should automatically unlock resources.<p>
*
* @return true if resources should be automatically unlocked in standalone mode
*/
public boolean shouldAcaciaUnlock() {
if (m_acaciaUnlock == null) {
return true;
} else {
return Boolean.parseBoolean(m_acaciaUnlock);
}
}
/**
* Returns if the user/group icon in the administration view should be shown.<p>
*
* @return true if the user/group icon in the administration view should be shown, otherwise false
*/
public boolean showUserGroupIcon() {
return m_showUserGroupIcon;
}
/**
* Returns true if lazy user lists should be used.<p>
*
* @return true if lazy user lists should be used
*/
public boolean supportsLazyUserLists() {
boolean result = "lazy".equalsIgnoreCase(m_userListMode);
if (org.opencms.db.mssql.CmsUserDriver.isInstantiated()) {
LOG.warn("Lazy user lists currently not supported on MSSQL, using classic user list mode as a fallback.");
result = false;
}
return result;
}
/**
* Translates a group name using the configured {@link I_CmsGroupNameTranslation}.<p>
*
* @param groupName the group name
* @param keepOu if true, the OU will be appended to the translated name
*
* @return the translated group name
*/
public String translateGroupName(String groupName, boolean keepOu) {
I_CmsGroupNameTranslation translation = getGroupNameTranslation();
return translation.translateGroupName(groupName, keepOu);
}
/**
* Gets the default view name ( = explorer type) for the given type.<p>
*
* @param typeName a resource type name
* @return the default view for the given type
*/
String getDefaultView(String typeName) {
String result = m_defaultViewRules.getViewForType(typeName);
if (result == null) {
result = "view_other";
try {
if (OpenCms.getResourceManager().hasResourceType(typeName)
&& OpenCms.getResourceManager().getResourceType(typeName).isFolder()) {
result = "view_folders";
}
} catch (CmsLoaderException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return result;
}
/**
* Creates a copy of the admin cms object which is initialize with the data of the current cms object.<p>
*
* @param cms the current cms object
* @return the new admin cms object
*
* @throws CmsException if something goes wrong
*/
private CmsObject getAdminCms(CmsObject cms) throws CmsException {
CmsObject adminCms = OpenCms.initCmsObject(m_adminCms);
adminCms.getRequestContext().setSiteRoot(cms.getRequestContext().getSiteRoot());
adminCms.getRequestContext().setRequestTime(cms.getRequestContext().getRequestTime());
adminCms.getRequestContext().setCurrentProject(cms.getRequestContext().getCurrentProject());
adminCms.getRequestContext().setEncoding(cms.getRequestContext().getEncoding());
adminCms.getRequestContext().setUri(cms.getRequestContext().getUri());
return adminCms;
}
/**
* Returns a dummy group name translation which leaves the group names unchanged.<p>
*
* @return a dummy group name translation
*/
private I_CmsGroupNameTranslation getDefaultGroupNameTranslation() {
return new I_CmsGroupNameTranslation() {
public String translateGroupName(String group, boolean keepOu) {
return keepOu ? group : CmsOrganizationalUnit.getSimpleName(group);
}
};
}
/**
* Initializes the configured explorer type settings.<p>
*/
private synchronized void initExplorerTypeSettings() {
Map<String, CmsExplorerTypeSettings> explorerTypeSettingsMap = new HashMap<String, CmsExplorerTypeSettings>();
List<CmsExplorerTypeSettings> explorerTypeSettings = new ArrayList<CmsExplorerTypeSettings>();
if (m_defaultAccess.getAccessControlList() == null) {
try {
// initialize the default access control configuration
m_defaultAccess.createAccessControlList(CmsExplorerTypeAccess.PRINCIPAL_DEFAULT);
} catch (CmsException e) {
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_ADD_TYPE_SETTING_FAILED_1,
CmsExplorerTypeAccess.PRINCIPAL_DEFAULT),
e);
}
}
}
explorerTypeSettings.addAll(m_explorerTypeSettingsFromXml);
explorerTypeSettings.addAll(m_explorerTypeSettingsFromModules);
for (int i = 0; i < explorerTypeSettings.size(); i++) {
CmsExplorerTypeSettings settings = explorerTypeSettings.get(i);
// put the settings in the lookup map
explorerTypeSettingsMap.put(settings.getName(), settings);
if (getDefaultAccess() == settings.getAccess()) {
continue;
}
try {
// initialize the access control configuration of the explorer type
settings.getAccess().createAccessControlList(settings.getName());
} catch (CmsException e) {
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(Messages.INIT_ADD_TYPE_SETTING_FAILED_1, settings.getName()),
e);
}
}
}
// sort the explorer type settings
Collections.sort(explorerTypeSettings);
// make the settings unmodifiable and store them in the global variables
m_explorerTypeSettings = Collections.unmodifiableList(explorerTypeSettings);
m_explorerTypeSettingsMap = Collections.unmodifiableMap(explorerTypeSettingsMap);
m_explorerTypeViews = Maps.newHashMap();
Set<String> explorerTypeViews = Sets.newHashSet();
for (CmsExplorerTypeSettings explorerType : getExplorerTypeSettings()) {
if (explorerType.isView()) {
explorerTypeViews.add(explorerType.getName());
}
}
for (String typeName : explorerTypeViews) {
CmsExplorerTypeSettings explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(typeName);
CmsElementView elemView = new CmsElementView(explorerType);
m_explorerTypeViews.put(elemView.getId(), elemView);
}
}
private List<Locale> initWorkplaceLocales(CmsObject cms) {
Set<Locale> locales = new HashSet<Locale>();
// collect locales from the VFS
if (cms.existsResource(CmsWorkplace.VFS_PATH_LOCALES)) {
List<CmsResource> localeFolders;
try {
localeFolders = cms.getSubFolders(CmsWorkplace.VFS_PATH_LOCALES);
} catch (CmsException e) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_WORKPLACE_INIT_NO_LOCALES_1,
CmsWorkplace.VFS_PATH_LOCALES),
e);
// can not throw exception here since then OpenCms would not even start in shell mode (runlevel 2)
localeFolders = new ArrayList<CmsResource>();
}
Iterator<CmsResource> i = localeFolders.iterator();
while (i.hasNext()) {
CmsFolder folder = (CmsFolder)i.next();
Locale locale = CmsLocaleManager.getLocale(folder.getName());
// add locale
locales.add(locale);
// add less specialized locale
locales.add(new Locale(locale.getLanguage(), locale.getCountry()));
// add even less specialized locale
locales.add(new Locale(locale.getLanguage()));
}
}
// collect locales from JAR manifests
try {
Enumeration<URL> resources = getClass().getClassLoader().getResources(MANIFEST_RESOURCE_NAME);
while (resources.hasMoreElements()) {
URL resUrl = resources.nextElement();
try {
Manifest manifest = new Manifest(resUrl.openStream());
String localeString = manifest.getMainAttributes().getValue(LOCALIZATION_ATTRIBUTE_NAME);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(localeString)) {
Locale locale = CmsLocaleManager.getLocale(localeString);
// add locale
locales.add(locale);
// add less specialized locale
locales.add(new Locale(locale.getLanguage(), locale.getCountry()));
// add even less specialized locale
locales.add(new Locale(locale.getLanguage()));
}
} catch (IOException e) {
LOG.warn(
"Error reading manifest from " + resUrl + " while evaluating available workplace localization.",
e);
}
}
} catch (IOException e) {
LOG.error("Error evaluating available workplace localization from JAR manifests.", e);
}
// sort the result
ArrayList<Locale> result = new ArrayList<Locale>();
result.addAll(locales);
Collections.sort(result, CmsLocaleComparator.getComparator());
return result;
}
private List<CmsWorkplaceView> initWorkplaceViews(CmsObject cms) {
List<CmsResource> viewFolders;
try {
// get the subfolders of the "views" folder
viewFolders = cms.getSubFolders(CmsWorkplace.VFS_PATH_VIEWS);
} catch (CmsException e) {
if ((OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) && LOG.isInfoEnabled()) {
LOG.info(
Messages.get().getBundle().key(Messages.LOG_WORKPLACE_INIT_NO_VIEWS_1, CmsWorkplace.VFS_PATH_VIEWS),
e);
}
// can not throw exception here since then OpenCms would not even start in shell mode (runlevel 2)
viewFolders = new ArrayList<CmsResource>();
}
m_views = new ArrayList<CmsWorkplaceView>(viewFolders.size());
for (int i = 0; i < viewFolders.size(); i++) {
// loop through all view folders
CmsFolder folder = (CmsFolder)viewFolders.get(i);
String folderPath = cms.getSitePath(folder);
try {
// get view information from folder properties
String order = cms.readPropertyObject(
folderPath,
CmsPropertyDefinition.PROPERTY_NAVPOS,
false).getValue();
String key = cms.readPropertyObject(
folderPath,
CmsPropertyDefinition.PROPERTY_NAVTEXT,
false).getValue();
String viewUri = cms.readPropertyObject(
folderPath,
CmsPropertyDefinition.PROPERTY_DEFAULT_FILE,
false).getValue();
if (viewUri == null) {
// no view URI found
viewUri = folderPath;
} else if (!viewUri.startsWith("/")) {
// default file is in current view folder, create absolute path to view URI
viewUri = folderPath + viewUri;
}
if (order == null) {
// no valid NavPos property value found, use loop count as order value
order = "" + i;
}
Float orderValue;
try {
// create Float order object
orderValue = Float.valueOf(order);
} catch (NumberFormatException e) {
// String was not formatted correctly, use loop counter
orderValue = Float.valueOf(i);
}
if (key == null) {
// no language key found, use default String to avoid NullPointerException
key = "View " + i;
// if no navtext is given do not display the view
continue;
}
// create new view object
CmsWorkplaceView view = new CmsWorkplaceView(key, viewUri, orderValue);
m_views.add(view);
// log the view
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WORKPLACE_VIEW_1, view.getUri()));
}
} catch (CmsException e) {
// should usually never happen
LOG.error(Messages.get().getBundle().key(Messages.LOG_READING_VIEW_FOLDER_FAILED_1, folderPath), e);
}
}
// sort the views by their order number
Collections.sort(m_views);
return m_views;
}
}
|
package org.pentaho.di.core.database;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.core.xml.XMLInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.shared.SharedObjectBase;
import org.pentaho.di.shared.SharedObjectInterface;
import org.w3c.dom.Node;
/**
* This class defines the database specific parameters for a certain database type.
* It also provides static information regarding a number of well known databases.
*
* @author Matt
* @since 18-05-2003
*
*/
public class DatabaseMeta extends SharedObjectBase implements Cloneable, XMLInterface, SharedObjectInterface, VariableSpace
{
public static final String XML_TAG = "connection";
private DatabaseInterface databaseInterface;
private static DatabaseInterface[] allDatabaseInterfaces;
private VariableSpace variables = new Variables();
/**
* Indicates that the connections doesn't point to a type of database yet.
*/
public static final int TYPE_DATABASE_NONE = 0;
/**
* Connection to a MySQL database
*/
public static final int TYPE_DATABASE_MYSQL = 1;
/**
* Connection to an Oracle database
*/
public static final int TYPE_DATABASE_ORACLE = 2;
/**
* Connection to an AS/400 (IBM iSeries) DB400 database
*/
public static final int TYPE_DATABASE_AS400 = 3;
/**
* Connection to an Microsoft Access database
*/
public static final int TYPE_DATABASE_ACCESS = 4;
/**
* Connection to a Microsoft SQL Server database
*/
public static final int TYPE_DATABASE_MSSQL = 5;
/**
* Connection to an IBM DB2 database
*/
public static final int TYPE_DATABASE_DB2 = 6;
/**
* Connection to a PostgreSQL database
*/
public static final int TYPE_DATABASE_POSTGRES = 7;
/**
* Connection to an Intersystems Cache database
*/
public static final int TYPE_DATABASE_CACHE = 8;
/**
* Connection to an IBM Informix database
*/
public static final int TYPE_DATABASE_INFORMIX = 9;
/**
* Connection to a Sybase ASE database
*/
public static final int TYPE_DATABASE_SYBASE = 10;
/**
* Connection to a Gupta SQLBase database
*/
public static final int TYPE_DATABASE_GUPTA = 11;
/**
* Connection to a DBase III/IV/V database through JDBC
*/
public static final int TYPE_DATABASE_DBASE = 12;
/**
* Connection to a FireBird database
*/
public static final int TYPE_DATABASE_FIREBIRD = 13;
/**
* Connection to a SAP DB database
*/
public static final int TYPE_DATABASE_SAPDB = 14;
/**
* Connection to a Hypersonic java database
*/
public static final int TYPE_DATABASE_HYPERSONIC = 15;
/**
* Connection to a generic database
*/
public static final int TYPE_DATABASE_GENERIC = 16;
/**
* Connection to an SAP R/3 system
*/
public static final int TYPE_DATABASE_SAPR3 = 17;
/**
* Connection to an Ingress database
*/
public static final int TYPE_DATABASE_INGRES = 18;
/**
* Connection to a Borland Interbase database
*/
public static final int TYPE_DATABASE_INTERBASE = 19;
/**
* Connection to an ExtenDB database
*/
public static final int TYPE_DATABASE_EXTENDB = 20;
/**
* Connection to a Teradata database
*/
public static final int TYPE_DATABASE_TERADATA = 21;
/**
* Connection to an Oracle RDB database
*/
public static final int TYPE_DATABASE_ORACLE_RDB = 22;
/**
* Connection to an H2 database
*/
public static final int TYPE_DATABASE_H2 = 23;
/**
* Connection to a Netezza database
*/
public static final int TYPE_DATABASE_NETEZZA = 24;
/**
* Connection to an IBM UniVerse database
*/
public static final int TYPE_DATABASE_UNIVERSE = 25;
/**
* Connection to a SQLite database
*/
public static final int TYPE_DATABASE_SQLITE = 26;
/**
* Connection to an Apache Derby database
*/
public static final int TYPE_DATABASE_DERBY = 27;
/**
* Connect natively through JDBC thin driver to the database.
*/
public static final int TYPE_ACCESS_NATIVE = 0;
/**
* Connect to the database using ODBC.
*/
public static final int TYPE_ACCESS_ODBC = 1;
/**
* Connect to the database using OCI. (Oracle only)
*/
public static final int TYPE_ACCESS_OCI = 2;
/**
* Connect to the database using plugin specific method. (SAP R/3)
*/
public static final int TYPE_ACCESS_PLUGIN = 3;
/**
* Connect to the database using JNDI.
*/
public static final int TYPE_ACCESS_JNDI = 4;
/**
* Short description of the access type, used in XML and the repository.
*/
public static final String dbAccessTypeCode[] =
{
"Native",
"ODBC",
"OCI",
"Plugin",
"JNDI"
};
/**
* Longer description for user interactions.
*/
public static final String dbAccessTypeDesc[] =
{
"Native (JDBC)",
"ODBC",
"OCI",
"Plugin specific access method",
"JNDI"
};
/**
* Use this length in a String value to indicate that you want to use a CLOB in stead of a normal text field.
*/
public static final int CLOB_LENGTH = 9999999;
/**
* The value to store in the attributes so that an empty value doesn't get lost...
*/
public static final String EMPTY_OPTIONS_STRING = "><EMPTY><";
/**
* Construct a new database connections. Note that not all these parameters are not allways mandatory.
*
* @param name The database name
* @param type The type of database
* @param access The type of database access
* @param host The hostname or IP address
* @param db The database name
* @param port The port on which the database listens.
* @param user The username
* @param pass The password
*/
public DatabaseMeta(String name, String type, String access, String host, String db, String port, String user, String pass)
{
setValues(name, type, access, host, db, port, user, pass);
addOptions();
}
/**
* Create an empty database connection
*
*/
public DatabaseMeta()
{
setDefault();
addOptions();
}
/**
* Set default values for an Oracle database.
*
*/
public void setDefault()
{
setValues("", "Oracle", "Native", "", "", "1521", "", "");
}
/**
* Add a list of common options for some databases.
*
*/
public void addOptions()
{
String mySQL = new MySQLDatabaseMeta().getDatabaseTypeDesc();
addExtraOption(mySQL, "defaultFetchSize", "500");
addExtraOption(mySQL, "useCursorFetch", "true");
}
/**
* @return the system dependend database interface for this database metadata definition
*/
public DatabaseInterface getDatabaseInterface()
{
return databaseInterface;
}
/**
* Set the system dependend database interface for this database metadata definition
* @param databaseInterface the system dependend database interface
*/
public void setDatabaseInterface(DatabaseInterface databaseInterface)
{
this.databaseInterface = databaseInterface;
}
/**
* Search for the right type of DatabaseInterface object and clone it.
*
* @param databaseType the type of DatabaseInterface to look for (description)
* @return The requested DatabaseInterface
*
* @throws KettleDatabaseException when the type could not be found or referenced.
*/
private static final DatabaseInterface getDatabaseInterface(String databaseType) throws KettleDatabaseException
{
return (DatabaseInterface)findDatabaseInterface(databaseType).clone();
}
/**
* Search for the right type of DatabaseInterface object and return it.
*
* @param databaseType the type of DatabaseInterface to look for (description)
* @return The requested DatabaseInterface
*
* @throws KettleDatabaseException when the type could not be found or referenced.
*/
private static final DatabaseInterface findDatabaseInterface(String databaseTypeDesc) throws KettleDatabaseException
{
DatabaseInterface di[] = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseTypeDesc().equalsIgnoreCase(databaseTypeDesc) ||
di[i].getDatabaseTypeDescLong().equalsIgnoreCase(databaseTypeDesc)
) return di[i];
}
throw new KettleDatabaseException("database type ["+databaseTypeDesc+"] couldn't be found!");
}
/**
*
* Load the Database Info
*/
public DatabaseMeta(Repository rep, long id_database) throws KettleException
{
this();
try
{
RowMetaAndData r = rep.getDatabase(id_database);
if (r!=null)
{
long id_database_type = r.getInteger("ID_DATABASE_TYPE", 0); // con_type
String dbTypeDesc = rep.getDatabaseTypeCode(id_database_type);
if (dbTypeDesc!=null)
{
databaseInterface = getDatabaseInterface(dbTypeDesc);
setAttributes(new Properties()); // new attributes
}
else
{
throw new KettleException("No database type was specified [id_database_type="+id_database_type+"]");
}
setID(id_database);
setName( r.getString("NAME", "") );
long id_database_contype = r.getInteger("ID_DATABASE_CONTYPE", 0); // con_access
setAccessType( getAccessType( rep.getDatabaseConTypeCode( id_database_contype)) );
setHostname( r.getString("HOST_NAME", "") );
setDBName( r.getString("DATABASE_NAME", "") );
setDBPort( r.getString("PORT", "") );
setUsername( r.getString("USERNAME", "") );
setPassword( Encr.decryptPasswordOptionallyEncrypted( r.getString("PASSWORD", "") ) );
setServername( r.getString("SERVERNAME", "") );
setDataTablespace( r.getString("DATA_TBS", "") );
setIndexTablespace( r.getString("INDEX_TBS", "") );
// Also, load all the properties we can find...
final Collection<RowMetaAndData> attrs = rep.getDatabaseAttributes();
for (RowMetaAndData row : attrs)
{
String code = row.getString("CODE", "");
String attribute = row.getString("VALUE_STR", "");
// System.out.println("Attributes: "+(getAttributes()!=null)+", code: "+(code!=null)+", attribute: "+(attribute!=null));
getAttributes().put(code, Const.NVL(attribute, ""));
}
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Error loading database connection from repository (id_database="+id_database+")", dbe);
}
}
/**
* Saves the database information into a given repository.
*
* @param rep The repository to save the database into.
*
* @throws KettleException if an error occurs.
*/
public void saveRep(Repository rep) throws KettleException
{
try
{
// If we don't have an ID, we don't know which entry in the database we need to update.
// See if a database with the same name is already available...
if (getID()<=0)
{
setID(rep.getDatabaseID(getName()));
}
// Still not found? --> Insert
if (getID()<=0)
{
// Insert new Note in repository
setID(rep.insertDatabase( getName(),
getDatabaseTypeCode(getDatabaseType()),
getAccessTypeDesc(getAccessType()),
getHostname(),
getDatabaseName(),
getDatabasePortNumberString(),
getUsername(),
getPassword(),
getServername(),
getDataTablespace(),
getIndexTablespace()
)
);
}
else // --> found entry with the same name...
{
// Update the note...
rep.updateDatabase( getID(),
getName(),
getDatabaseTypeCode(getDatabaseType()),
getAccessTypeDesc(getAccessType()),
getHostname(),
getDatabaseName(),
getDatabasePortNumberString(),
getUsername(),
getPassword(),
getServername(),
getDataTablespace(),
getIndexTablespace()
);
}
// For the extra attributes, just delete them and re-add them.
rep.delDatabaseAttributes(getID());
// OK, now get a list of all the attributes set on the database connection...
Properties attributes = getAttributes();
Enumeration<Object> keys = getAttributes().keys();
while (keys.hasMoreElements())
{
String code = (String) keys.nextElement();
String attribute = (String)attributes.get(code);
// Save this attribute
rep.insertDatabaseAttribute(getID(), code, attribute);
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Error saving database connection or one of its attributes to the repository.", dbe);
}
}
/**
* Returns the database ID of this database connection if a repository was used before.
*
* @return the ID of the db connection.
*/
public long getID()
{
return databaseInterface.getId();
}
public void setID(long id)
{
databaseInterface.setId(id);
}
public Object clone()
{
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.replaceMeta(this);
databaseMeta.setID(-1L);
return databaseMeta;
}
public void replaceMeta(DatabaseMeta databaseMeta)
{
this.setValues(databaseMeta.getName(), databaseMeta.getDatabaseTypeDesc(), databaseMeta.getAccessTypeDesc(),
databaseMeta.getHostname(), databaseMeta.getDatabaseName(), databaseMeta.getDatabasePortNumberString(),
databaseMeta.getUsername(), databaseMeta.getPassword()
);
this.setServername(databaseMeta.getServername());
this.setDataTablespace( databaseMeta.getDataTablespace() );
this.setIndexTablespace( databaseMeta.getIndexTablespace() );
this.databaseInterface = (DatabaseInterface) databaseMeta.databaseInterface.clone();
this.setID(databaseMeta.getID());
this.setChanged();
}
public void setValues(String name, String type, String access, String host, String db, String port, String user, String pass)
{
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new RuntimeException("Database type not found!", kde);
}
setName(name);
setAccessType(getAccessType(access));
setHostname(host);
setDBName(db);
setDBPort(port);
setUsername(user);
setPassword(pass);
setServername(null);
setChanged(false);
}
public void setDatabaseType(String type)
{
DatabaseInterface oldInterface = databaseInterface;
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new RuntimeException("Database type ["+type+"] not found!", kde);
}
setName(oldInterface.getName());
setAccessType(oldInterface.getAccessType());
setHostname(oldInterface.getHostname());
setDBName(oldInterface.getDatabaseName());
setDBPort(oldInterface.getDatabasePortNumberString());
setUsername(oldInterface.getUsername());
setPassword(oldInterface.getPassword());
setServername(oldInterface.getServername());
setDataTablespace(oldInterface.getDataTablespace());
setIndexTablespace(oldInterface.getIndexTablespace());
setChanged(oldInterface.isChanged());
}
public void setValues(DatabaseMeta info)
{
databaseInterface = (DatabaseInterface)info.databaseInterface.clone();
}
/**
* Sets the name of the database connection. This name should be
* unique in a transformation and in general in a single repository.
*
* @param name The name of the database connection
*/
public void setName(String name)
{
databaseInterface.setName(name);
}
/**
* Returns the name of the database connection
* @return The name of the database connection
*/
public String getName()
{
return databaseInterface.getName();
}
/**
* Returns the type of database, one of <p>
* TYPE_DATABASE_MYSQL<p>
* TYPE_DATABASE_ORACLE<p>
* TYPE_DATABASE_...<p>
*
* @return the database type
*/
public int getDatabaseType()
{
return databaseInterface.getDatabaseType();
}
/*
* Sets the type of database.
* @param db_type The database type
public void setDatabaseType(int db_type)
{
databaseInterface
this.databaseType = db_type;
}
*/
/**
* Return the type of database access. One of <p>
* TYPE_ACCESS_NATIVE<p>
* TYPE_ACCESS_ODBC<p>
* TYPE_ACCESS_OCI<p>
* @return The type of database access.
*/
public int getAccessType()
{
return databaseInterface.getAccessType();
}
/**
* Set the type of database access.
* @param access_type The access type.
*/
public void setAccessType(int access_type)
{
databaseInterface.setAccessType(access_type);
}
/**
* Returns a short description of the type of database.
* @return A short description of the type of database.
*/
public String getDatabaseTypeDesc()
{
return databaseInterface.getDatabaseTypeDesc();
}
/**
* Gets you a short description of the type of database access.
* @return A short description of the type of database access.
*/
public String getAccessTypeDesc()
{
return dbAccessTypeCode[getAccessType()];
}
/**
* Return the hostname of the machine on which the database runs.
* @return The hostname of the database.
*/
public String getHostname()
{
return databaseInterface.getHostname();
}
/**
* Sets the hostname of the machine on which the database runs.
* @param hostname The hostname of the machine on which the database runs.
*/
public void setHostname(String hostname)
{
databaseInterface.setHostname(hostname);
}
/**
* Return the port on which the database listens as a String. Allows for parameterisation.
* @return The database port.
*/
public String getDatabasePortNumberString()
{
return databaseInterface.getDatabasePortNumberString();
}
/**
* Sets the port on which the database listens.
*
* @param db_port The port number on which the database listens
*/
public void setDBPort(String db_port)
{
databaseInterface.setDatabasePortNumberString(db_port);
}
/**
* Return the name of the database.
* @return The database name.
*/
public String getDatabaseName()
{
return databaseInterface.getDatabaseName();
}
/**
* Set the name of the database.
* @param databaseName The new name of the database
*/
public void setDBName(String databaseName)
{
databaseInterface.setDatabaseName(databaseName);
}
/**
* Get the username to log into the database on this connection.
* @return The username to log into the database on this connection.
*/
public String getUsername()
{
return databaseInterface.getUsername();
}
/**
* Sets the username to log into the database on this connection.
* @param username The username
*/
public void setUsername(String username)
{
databaseInterface.setUsername(username);
}
/**
* Get the password to log into the database on this connection.
* @return the password to log into the database on this connection.
*/
public String getPassword()
{
return databaseInterface.getPassword();
}
/**
* Sets the password to log into the database on this connection.
* @param password the password to log into the database on this connection.
*/
public void setPassword(String password)
{
databaseInterface.setPassword(password);
}
/**
* @param servername the Informix servername
*/
public void setServername(String servername)
{
databaseInterface.setServername(servername);
}
/**
* @return the Informix servername
*/
public String getServername()
{
return databaseInterface.getServername();
}
public String getDataTablespace()
{
return databaseInterface.getDataTablespace();
}
public void setDataTablespace(String data_tablespace)
{
databaseInterface.setDataTablespace(data_tablespace);
}
public String getIndexTablespace()
{
return databaseInterface.getIndexTablespace();
}
public void setIndexTablespace(String index_tablespace)
{
databaseInterface.setIndexTablespace(index_tablespace);
}
public void setChanged()
{
setChanged(true);
}
public void setChanged(boolean ch)
{
databaseInterface.setChanged(ch);
}
public boolean hasChanged()
{
return databaseInterface.isChanged();
}
public String toString()
{
return getName();
}
/**
* @return The extra attributes for this database connection
*/
public Properties getAttributes()
{
return databaseInterface.getAttributes();
}
/**
* Set extra attributes on this database connection
* @param attributes The extra attributes to set on this database connection.
*/
public void setAttributes(Properties attributes)
{
databaseInterface.setAttributes(attributes);
}
/**
* Constructs a new database using an XML string snippet.
* It expects the snippet to be enclosed in <code>connection</code> tags.
* @param xml The XML string to parse
* @throws KettleXMLException in case there is an XML parsing error
*/
public DatabaseMeta(String xml) throws KettleXMLException
{
this( XMLHandler.getSubNode(XMLHandler.loadXMLString(xml), "connection") );
}
/**
* Reads the information from an XML Node into this new database connection.
* @param con The Node to read the data from
* @throws KettleXMLException
*/
public DatabaseMeta(Node con) throws KettleXMLException
{
this();
try
{
String type = XMLHandler.getTagValue(con, "type");
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new KettleXMLException("Unable to create new database interface", kde);
}
setName( XMLHandler.getTagValue(con, "name") );
setHostname( XMLHandler.getTagValue(con, "server") );
String acc = XMLHandler.getTagValue(con, "access");
setAccessType( getAccessType(acc) );
setDBName( XMLHandler.getTagValue(con, "database") );
setDBPort( XMLHandler.getTagValue(con, "port") );
setUsername( XMLHandler.getTagValue(con, "username") );
setPassword( Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue(con, "password") ) );
setServername( XMLHandler.getTagValue(con, "servername") );
setDataTablespace( XMLHandler.getTagValue(con, "data_tablespace") );
setIndexTablespace( XMLHandler.getTagValue(con, "index_tablespace") );
// Also, read the database attributes...
Node attrsnode = XMLHandler.getSubNode(con, "attributes");
if (attrsnode!=null)
{
int nr = XMLHandler.countNodes(attrsnode, "attribute");
for (int i=0;i<nr;i++)
{
Node attrnode = XMLHandler.getSubNodeByNr(attrsnode, "attribute", i);
String code = XMLHandler.getTagValue(attrnode, "code");
String attribute = XMLHandler.getTagValue(attrnode, "attribute");
if (code!=null && attribute!=null) getAttributes().put(code, attribute);
}
}
}
catch(Exception e)
{
throw new KettleXMLException("Unable to load database connection info from XML node", e);
}
}
@SuppressWarnings("unchecked")
public String getXML()
{
StringBuffer retval = new StringBuffer(250);
retval.append(" <").append(XML_TAG).append('>').append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("name", getName()));
retval.append(" ").append(XMLHandler.addTagValue("server", getHostname()));
retval.append(" ").append(XMLHandler.addTagValue("type", getDatabaseTypeDesc()));
retval.append(" ").append(XMLHandler.addTagValue("access", getAccessTypeDesc()));
retval.append(" ").append(XMLHandler.addTagValue("database", getDatabaseName()));
retval.append(" ").append(XMLHandler.addTagValue("port", getDatabasePortNumberString()));
retval.append(" ").append(XMLHandler.addTagValue("username", getUsername()));
retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword())));
retval.append(" ").append(XMLHandler.addTagValue("servername", getServername()));
retval.append(" ").append(XMLHandler.addTagValue("data_tablespace", getDataTablespace()));
retval.append(" ").append(XMLHandler.addTagValue("index_tablespace", getIndexTablespace()));
retval.append(" <attributes>").append(Const.CR);
List list = new ArrayList( getAttributes().keySet() );
Collections.sort(list); // Sort the entry-sets to make sure we can compare XML strings: if the order is different, the XML is different.
for (Iterator iter = list.iterator(); iter.hasNext();)
{
String code = (String) iter.next();
String attribute = getAttributes().getProperty(code);
if (!Const.isEmpty(attribute))
{
retval.append(" <attribute>"+
XMLHandler.addTagValue("code", code, false)+
XMLHandler.addTagValue("attribute", attribute, false)+
"</attribute>"+Const.CR);
}
}
retval.append(" </attributes>").append(Const.CR);
retval.append(" </"+XML_TAG+">").append(Const.CR);
return retval.toString();
}
public int hashCode()
{
return getName().hashCode(); // name of connection is unique!
}
public boolean equals(Object obj)
{
return getName().equals( ((DatabaseMeta)obj).getName() );
}
public String getURL() throws KettleDatabaseException
{
return getURL(null);
}
public String getURL(String partitionId) throws KettleDatabaseException
{
String baseUrl;
if (isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = getPartitionMeta(partitionId);
String hostname = partition.getHostname();
String port = partition.getPort();
String databaseName = partition.getDatabaseName();
baseUrl = databaseInterface.getURL(hostname, port, databaseName);
}
else
{
baseUrl = databaseInterface.getURL(getHostname(), getDatabasePortNumberString(), getDatabaseName());
}
StringBuffer url=new StringBuffer( baseUrl );
if (databaseInterface.supportsOptionsInURL())
{
// OK, now add all the options...
String optionIndicator = getExtraOptionIndicator();
String optionSeparator = getExtraOptionSeparator();
String valueSeparator = getExtraOptionValueSeparator();
Map<String, String> map = getExtraOptions();
if (map.size()>0)
{
Iterator<String> iterator = map.keySet().iterator();
boolean first=true;
while (iterator.hasNext())
{
String typedParameter=(String)iterator.next();
int dotIndex = typedParameter.indexOf('.');
if (dotIndex>=0)
{
String typeCode = typedParameter.substring(0,dotIndex);
String parameter = typedParameter.substring(dotIndex+1);
String value = map.get(typedParameter);
// Only add to the URL if it's the same database type code...
if (databaseInterface.getDatabaseTypeDesc().equals(typeCode))
{
if (first) url.append(optionIndicator);
else url.append(optionSeparator);
url.append(parameter);
if (!Const.isEmpty(value) && !value.equals(EMPTY_OPTIONS_STRING))
{
url.append(valueSeparator).append(value);
}
first=false;
}
}
}
}
}
else
{
// We need to put all these options in a Properties file later (Oracle & Co.)
// This happens at connect time...
}
return url.toString();
}
public Properties getConnectionProperties()
{
Properties properties =new Properties();
Map<String, String> map = getExtraOptions();
if (map.size()>0)
{
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String typedParameter=(String)iterator.next();
int dotIndex = typedParameter.indexOf('.');
if (dotIndex>=0)
{
String typeCode = typedParameter.substring(0,dotIndex);
String parameter = typedParameter.substring(dotIndex+1);
String value = (String) map.get(typedParameter);
// Only add to the URL if it's the same database type code...
if (databaseInterface.getDatabaseTypeDesc().equals(typeCode))
{
if (value!=null && value.equals(EMPTY_OPTIONS_STRING)) value="";
properties.put(parameter, environmentSubstitute(Const.NVL(value, "")));
}
}
}
}
return properties;
}
public String getExtraOptionIndicator()
{
return databaseInterface.getExtraOptionIndicator();
}
/**
* @return The extra option separator in database URL for this platform (usually this is semicolon ; )
*/
public String getExtraOptionSeparator()
{
return databaseInterface.getExtraOptionSeparator();
}
/**
* @return The extra option value separator in database URL for this platform (usually this is the equal sign = )
*/
public String getExtraOptionValueSeparator()
{
return databaseInterface.getExtraOptionValueSeparator();
}
/**
* Add an extra option to the attributes list
* @param databaseTypeCode The database type code for which the option applies
* @param option The option to set
* @param value The value of the option
*/
public void addExtraOption(String databaseTypeCode, String option, String value)
{
databaseInterface.addExtraOption(databaseTypeCode, option, value);
}
/**
* @deprecated because the same database can support transactions or not. It all depends on the database setup. Therefor, we look at the database metadata
* DatabaseMetaData.supportsTransactions() in stead of this.
* @return true if the database supports transactions
*/
public boolean supportsTransactions()
{
return databaseInterface.supportsTransactions();
}
public boolean supportsAutoinc()
{
return databaseInterface.supportsAutoInc();
}
public boolean supportsSequences()
{
return databaseInterface.supportsSequences();
}
public String getSQLSequenceExists(String sequenceName)
{
return databaseInterface.getSQLSequenceExists(sequenceName);
}
public boolean supportsBitmapIndex()
{
return databaseInterface.supportsBitmapIndex();
}
public boolean supportsSetLong()
{
return databaseInterface.supportsSetLong();
}
/**
* @return true if the database supports schemas
*/
public boolean supportsSchemas()
{
return databaseInterface.supportsSchemas();
}
/**
* @return true if the database supports catalogs
*/
public boolean supportsCatalogs()
{
return databaseInterface.supportsCatalogs();
}
/**
*
* @return true when the database engine supports empty transaction.
* (for example Informix does not on a non-ANSI database type!)
*/
public boolean supportsEmptyTransactions()
{
return databaseInterface.supportsEmptyTransactions();
}
/**
* See if this database supports the setCharacterStream() method on a PreparedStatement.
*
* @return true if we can set a Stream on a field in a PreparedStatement. False if not.
*/
public boolean supportsSetCharacterStream()
{
return databaseInterface.supportsSetCharacterStream();
}
/**
* Get the maximum length of a text field for this database connection.
* This includes optional CLOB, Memo and Text fields. (the maximum!)
* @return The maximum text field length for this database type. (mostly CLOB_LENGTH)
*/
public int getMaxTextFieldLength()
{
return databaseInterface.getMaxTextFieldLength();
}
public final static int getDatabaseType(String dbTypeDesc)
{
// Backward compatibility...
if (dbTypeDesc.equalsIgnoreCase("ODBC-ACCESS")) return TYPE_DATABASE_ACCESS;
try
{
DatabaseInterface di = getDatabaseInterface(dbTypeDesc);
return di.getDatabaseType();
}
catch(KettleDatabaseException kde)
{
return TYPE_DATABASE_NONE;
}
}
/**
* Get a string representing the unqiue database type code
* @param dbtype the database type to get the code of
* @return The database type code
* @deprecated please use getDatabaseTypeCode()
*/
public final static String getDBTypeDesc(int dbtype)
{
return getDatabaseTypeCode(dbtype);
}
/**
* Get a string representing the unqiue database type code
* @param dbtype the database type to get the code of
* @return The database type code
*/
public final static String getDatabaseTypeCode(int dbtype)
{
// Find the DatabaseInterface for this type...
DatabaseInterface[] di = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseType() == dbtype) return di[i].getDatabaseTypeDesc();
}
return null;
}
/**
* Get a description of the database type
* @param dbtype the database type to get the description for
* @return The database type description
*/
public final static String getDatabaseTypeDesc(int dbtype)
{
// Find the DatabaseInterface for this type...
DatabaseInterface[] di = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseType() == dbtype) return di[i].getDatabaseTypeDescLong();
}
return null;
}
public final static int getAccessType(String dbaccess)
{
int i;
if (dbaccess==null) return TYPE_ACCESS_NATIVE;
for (i=0;i<dbAccessTypeCode.length;i++)
{
if (dbAccessTypeCode[i].equalsIgnoreCase(dbaccess))
{
return i;
}
}
for (i=0;i<dbAccessTypeDesc.length;i++)
{
if (dbAccessTypeDesc[i].equalsIgnoreCase(dbaccess))
{
return i;
}
}
return TYPE_ACCESS_NATIVE;
}
public final static String getAccessTypeDesc(int dbaccess)
{
if (dbaccess<0) return null;
if (dbaccess>dbAccessTypeCode.length) return null;
return dbAccessTypeCode[dbaccess];
}
public final static String getAccessTypeDescLong(int dbaccess)
{
if (dbaccess<0) return null;
if (dbaccess>dbAccessTypeDesc.length) return null;
return dbAccessTypeDesc[dbaccess];
}
public final static String[] getDBTypeDescLongList()
{
DatabaseInterface[] di = getDatabaseInterfaces();
String[] retval = new String[di.length];
for (int i=0;i<di.length;i++)
{
retval[i] = di[i].getDatabaseTypeDescLong();
}
return retval;
}
public final static String[] getDBTypeDescList()
{
DatabaseInterface[] di = getDatabaseInterfaces();
String[] retval = new String[di.length];
for (int i=0;i<di.length;i++)
{
retval[i] = di[i].getDatabaseTypeDesc();
}
return retval;
}
public static final DatabaseInterface[] getDatabaseInterfaces()
{
if (allDatabaseInterfaces!=null) return allDatabaseInterfaces;
Class<?> ic[] = DatabaseInterface.implementingClasses;
allDatabaseInterfaces = new DatabaseInterface[ic.length];
for (int i=0;i<ic.length;i++)
{
try
{
Class.forName(ic[i].getName());
allDatabaseInterfaces[i] = (DatabaseInterface)ic[i].newInstance();
}
catch(Exception e)
{
throw new RuntimeException("Error creating class for : "+ic[i].getName(), e);
}
}
return allDatabaseInterfaces;
}
public final static int[] getAccessTypeList(String dbTypeDesc)
{
try
{
DatabaseInterface di = findDatabaseInterface(dbTypeDesc);
return di.getAccessTypeList();
}
catch(KettleDatabaseException kde)
{
return null;
}
}
public static final int getPortForDBType(String strtype, String straccess)
{
try
{
DatabaseInterface di = getDatabaseInterface(strtype);
di.setAccessType(getAccessType(straccess));
return di.getDefaultDatabasePort();
}
catch(KettleDatabaseException kde)
{
return -1;
}
}
public int getDefaultDatabasePort()
{
return databaseInterface.getDefaultDatabasePort();
}
public int getNotFoundTK(boolean use_autoinc)
{
return databaseInterface.getNotFoundTK(use_autoinc);
}
public String getDriverClass()
{
return databaseInterface.getDriverClass();
}
public String stripCR(String sbsql)
{
return stripCR(new StringBuffer(sbsql));
}
public String stripCR(StringBuffer sbsql)
{
// DB2 Can't handle \n in SQL Statements...
if (getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 ||
getDatabaseType() == DatabaseMeta.TYPE_DATABASE_CACHE ||
getDatabaseType() == DatabaseMeta.TYPE_DATABASE_UNIVERSE
)
{
// Remove CR's
for (int i=sbsql.length()-1;i>=0;i
{
if (sbsql.charAt(i)=='\n' || sbsql.charAt(i)=='\r') sbsql.setCharAt(i, ' ');
}
}
return sbsql.toString();
}
public String getSeqNextvalSQL(String sequenceName)
{
return databaseInterface.getSQLNextSequenceValue(sequenceName);
}
public String getSQLCurrentSequenceValue(String sequenceName)
{
return databaseInterface.getSQLCurrentSequenceValue(sequenceName);
}
public boolean isFetchSizeSupported()
{
return databaseInterface.isFetchSizeSupported();
}
/**
* Indicates the need to insert a placeholder (0) for auto increment fields.
* @return true if we need a placeholder for auto increment fields in insert statements.
*/
public boolean needsPlaceHolder()
{
return databaseInterface.needsPlaceHolder();
}
public String getFunctionSum()
{
return databaseInterface.getFunctionSum();
}
public String getFunctionAverage()
{
return databaseInterface.getFunctionAverage();
}
public String getFunctionMaximum()
{
return databaseInterface.getFunctionMaximum();
}
public String getFunctionMinimum()
{
return databaseInterface.getFunctionMinimum();
}
public String getFunctionCount()
{
return databaseInterface.getFunctionCount();
}
/**
* Check the database connection parameters and give back an array of remarks
* @return an array of remarks Strings
*/
public String[] checkParameters()
{
ArrayList<String> remarks = new ArrayList<String>();
if (getDatabaseType()==TYPE_DATABASE_NONE)
{
remarks.add("No database type was choosen");
}
if (getName()==null || getName().length()==0)
{
remarks.add("Please give this database connection a name");
}
if (!isPartitioned() && getDatabaseType()!=TYPE_DATABASE_SAPR3 && getDatabaseType()!=TYPE_DATABASE_GENERIC)
{
if (getDatabaseName()==null || getDatabaseName().length()==0)
{
remarks.add("Please specify the name of the database");
}
}
return remarks.toArray(new String[remarks.size()]);
}
/**
* Calculate the schema-table combination, usually this is the schema and table separated with a dot. (schema.table)
* @param schemaName the schema-name or null if no schema is used.
* @param tableName the table name
* @return the schemaname-tablename combination
*/
public String getSchemaTableCombination(String schemaName, String tableName)
{
if (Const.isEmpty(schemaName)) return tableName; // no need to look further
return databaseInterface.getSchemaTableCombination(schemaName, tableName);
}
public boolean isClob(ValueMetaInterface v)
{
boolean retval=true;
if (v==null || v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
retval=false;
}
else
{
return true;
}
return retval;
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc)
{
return getFieldDefinition(v, tk, pk, use_autoinc, true, true);
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
return databaseInterface.getFieldDefinition(v, tk, pk, use_autoinc, add_fieldname, add_cr);
}
public String getLimitClause(int nrRows)
{
return databaseInterface.getLimitClause(nrRows);
}
/**
* @param tableName The table or schema-table combination. We expect this to be quoted properly already!
* @return the SQL for to get the fields of this table.
*/
public String getSQLQueryFields(String tableName)
{
return databaseInterface.getSQLQueryFields(tableName);
}
public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
/**
* @return an array of reserved words for the database type...
*/
public String[] getReservedWords()
{
return databaseInterface.getReservedWords();
}
/**
* @return true if reserved words need to be double quoted ("password", "select", ...)
*/
public boolean quoteReservedWords()
{
return databaseInterface.quoteReservedWords();
}
/**
* @return The start quote sequence, mostly just double quote, but sometimes [, ...
*/
public String getStartQuote()
{
return databaseInterface.getStartQuote();
}
/**
* @return The end quote sequence, mostly just double quote, but sometimes ], ...
*/
public String getEndQuote()
{
return databaseInterface.getEndQuote();
}
/**
* Returns a quoted field if this is needed: contains spaces, is a reserved word, ...
* @param field The fieldname to check for quoting
* @return The quoted field (if this is needed.
*/
public String quoteField(String field)
{
if (Const.isEmpty(field)) return null;
// If the field already contains quotes, we don't touch it anymore, just return the same string...
if (field.indexOf(getStartQuote())>=0 || field.indexOf(getEndQuote())>=0)
{
return field;
}
if (isReservedWord(field) && quoteReservedWords())
{
return handleCase(getStartQuote()+field+getEndQuote());
}
else
{
if (databaseInterface.isQuoteAllFields() ||
hasSpacesInField(field) ||
hasSpecialCharInField(field) ||
hasDotInField(field))
{
return getStartQuote()+field+getEndQuote();
}
else
{
return field;
}
}
}
private String handleCase(String field)
{
if (databaseInterface.isDefaultingToUppercase())
{
return field.toUpperCase();
}
else
{
return field.toLowerCase();
}
}
/**
* Determines whether or not this field is in need of quoting:<br>
* - When the fieldname contains spaces<br>
* - When the fieldname is a reserved word<br>
* @param fieldname the fieldname to check if there is a need for quoting
* @return true if the fieldname needs to be quoted.
*/
public boolean isInNeedOfQuoting(String fieldname)
{
return isReservedWord(fieldname) || hasSpacesInField(fieldname);
}
/**
* Returns true if the string specified is a reserved word on this database type.
* @param word The word to check
* @return true if word is a reserved word on this database.
*/
public boolean isReservedWord(String word)
{
String reserved[] = getReservedWords();
if (Const.indexOfString(word, reserved)>=0) return true;
return false;
}
/**
* Detects if a field has spaces in the name. We need to quote the field in that case.
* @param fieldname The fieldname to check for spaces
* @return true if the fieldname contains spaces
*/
public boolean hasSpacesInField(String fieldname)
{
if( fieldname == null ) return false;
if (fieldname.indexOf(' ')>=0) return true;
return false;
}
/**
* Detects if a field has spaces in the name. We need to quote the field in that case.
* @param fieldname The fieldname to check for spaces
* @return true if the fieldname contains spaces
*/
public boolean hasSpecialCharInField(String fieldname)
{
if(fieldname==null) return false;
if (fieldname.indexOf('/')>=0) return true;
if (fieldname.indexOf('-')>=0) return true;
if (fieldname.indexOf('+')>=0) return true;
if (fieldname.indexOf(',')>=0) return true;
if (fieldname.indexOf('*')>=0) return true;
if (fieldname.indexOf('(')>=0) return true;
if (fieldname.indexOf(')')>=0) return true;
if (fieldname.indexOf('{')>=0) return true;
if (fieldname.indexOf('}')>=0) return true;
if (fieldname.indexOf('[')>=0) return true;
if (fieldname.indexOf(']')>=0) return true;
if (fieldname.indexOf('%')>=0) return true;
if (fieldname.indexOf('@')>=0) return true;
return false;
}
public boolean hasDotInField(String fieldname)
{
if(fieldname==null) return false;
if (fieldname.indexOf('.')>=0) return true;
return false;
}
/**
* Checks the fields specified for reserved words and quotes them.
* @param fields the list of fields to check
* @return true if one or more values have a name that is a reserved word on this database type.
*/
public boolean replaceReservedWords(RowMetaInterface fields)
{
boolean hasReservedWords=false;
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
if (isReservedWord(v.getName()))
{
hasReservedWords = true;
v.setName( quoteField(v.getName()) );
}
}
return hasReservedWords;
}
/**
* Checks the fields specified for reserved words
* @param fields the list of fields to check
* @return The nr of reserved words for this database.
*/
public int getNrReservedWords(RowMetaInterface fields)
{
int nrReservedWords=0;
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
if (isReservedWord(v.getName())) nrReservedWords++;
}
return nrReservedWords;
}
/**
* @return a list of types to get the available tables
*/
public String[] getTableTypes()
{
return databaseInterface.getTableTypes();
}
/**
* @return a list of types to get the available views
*/
public String[] getViewTypes()
{
return databaseInterface.getViewTypes();
}
/**
* @return a list of types to get the available synonyms
*/
public String[] getSynonymTypes()
{
return databaseInterface.getSynonymTypes();
}
/**
* @return true if we need to supply the schema-name to getTables in order to get a correct list of items.
*/
public boolean useSchemaNameForTableList()
{
return databaseInterface.useSchemaNameForTableList();
}
/**
* @return true if the database supports views
*/
public boolean supportsViews()
{
return databaseInterface.supportsViews();
}
/**
* @return true if the database supports synonyms
*/
public boolean supportsSynonyms()
{
return databaseInterface.supportsSynonyms();
}
/**
*
* @return The SQL on this database to get a list of stored procedures.
*/
public String getSQLListOfProcedures()
{
return databaseInterface.getSQLListOfProcedures();
}
/**
* @param tableName The tablename to be truncated
* @return The SQL statement to remove all rows from the specified statement, if possible without using transactions
*/
public String getTruncateTableStatement(String schema, String tableName)
{
return databaseInterface.getTruncateTableStatement(getQuotedSchemaTableCombination(schema, tableName));
}
/**
* @return true if the database rounds floating point numbers to the right precision.
* For example if the target field is number(7,2) the value 12.399999999 is converted into 12.40
*/
public boolean supportsFloatRoundingOnUpdate()
{
return databaseInterface.supportsFloatRoundingOnUpdate();
}
/**
* @param tableNames The names of the tables to lock
* @return The SQL commands to lock database tables for write purposes.
* null is returned in case locking is not supported on the target database.
*/
public String getSQLLockTables(String tableNames[])
{
return databaseInterface.getSQLLockTables(tableNames);
}
/**
* @param tableNames The names of the tables to unlock
* @return The SQL commands to unlock databases tables.
* null is returned in case locking is not supported on the target database.
*/
public String getSQLUnlockTables(String tableNames[])
{
return databaseInterface.getSQLUnlockTables(tableNames);
}
/*
* TODO: re-add the feature list support later on...
*
* @return a feature list for the choosen database type.
public List getFeatureSummary()
{
ArrayList list = new ArrayList();
Row r =null;
final String par = "Parameter";
final String val = "Value";
Value testValue = new Value("FIELD", ValueMetaInterface.TYPE_STRING);
testValue.setLength(30);
if (databaseInterface!=null)
{
// Type of database
r = new Row(); r.addValue(new Value(par, "Database type")); r.addValue(new Value(val, getDatabaseTypeDesc())); list.add(r);
// Type of access
r = new Row(); r.addValue(new Value(par, "Access type")); r.addValue(new Value(val, getAccessTypeDesc())); list.add(r);
// Name of database
r = new Row(); r.addValue(new Value(par, "Database name")); r.addValue(new Value(val, getDatabaseName())); list.add(r);
// server hostname
r = new Row(); r.addValue(new Value(par, "Server hostname")); r.addValue(new Value(val, getHostname())); list.add(r);
// Port number
r = new Row(); r.addValue(new Value(par, "Service port")); r.addValue(new Value(val, getDatabasePortNumberString())); list.add(r);
// Username
r = new Row(); r.addValue(new Value(par, "Username")); r.addValue(new Value(val, getUsername())); list.add(r);
// Informix server
r = new Row(); r.addValue(new Value(par, "Informix server name")); r.addValue(new Value(val, getServername())); list.add(r);
// Other properties...
Enumeration keys = getAttributes().keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
String value = getAttributes().getProperty(key);
r = new Row(); r.addValue(new Value(par, "Extra attribute ["+key+"]")); r.addValue(new Value(val, value)); list.add(r);
}
// driver class
r = new Row(); r.addValue(new Value(par, "Driver class")); r.addValue(new Value(val, getDriverClass())); list.add(r);
// URL
String pwd = getPassword();
setPassword("password"); // Don't give away the password in the URL!
String url = "";
try { url = getURL(); } catch(KettleDatabaseException e) {}
r = new Row(); r.addValue(new Value(par, "URL")); r.addValue(new Value(val, url)); list.add(r);
setPassword(pwd);
// SQL: Next sequence value
r = new Row(); r.addValue(new Value(par, "SQL: next sequence value")); r.addValue(new Value(val, getSeqNextvalSQL("SEQUENCE"))); list.add(r);
// is set fetchsize supported
r = new Row(); r.addValue(new Value(par, "supported: set fetch size")); r.addValue(new Value(val, isFetchSizeSupported())); list.add(r);
// needs placeholder for auto increment
r = new Row(); r.addValue(new Value(par, "auto increment field needs placeholder")); r.addValue(new Value(val, needsPlaceHolder())); list.add(r);
// Sum function
r = new Row(); r.addValue(new Value(par, "SUM aggregate function")); r.addValue(new Value(val, getFunctionSum())); list.add(r);
// Avg function
r = new Row(); r.addValue(new Value(par, "AVG aggregate function")); r.addValue(new Value(val, getFunctionAverage())); list.add(r);
// Minimum function
r = new Row(); r.addValue(new Value(par, "MIN aggregate function")); r.addValue(new Value(val, getFunctionMinimum())); list.add(r);
// Maximum function
r = new Row(); r.addValue(new Value(par, "MAX aggregate function")); r.addValue(new Value(val, getFunctionMaximum())); list.add(r);
// Count function
r = new Row(); r.addValue(new Value(par, "COUNT aggregate function")); r.addValue(new Value(val, getFunctionCount())); list.add(r);
// Schema-table comination
r = new Row(); r.addValue(new Value(par, "Schema / Table combination")); r.addValue(new Value(val, getSchemaTableCombination("SCHEMA", "TABLE"))); list.add(r);
// Limit clause
r = new Row(); r.addValue(new Value(par, "LIMIT clause for 100 rows")); r.addValue(new Value(val, getLimitClause(100))); list.add(r);
// add column statement
r = new Row(); r.addValue(new Value(par, "Add column statement")); r.addValue(new Value(val, getAddColumnStatement("TABLE", testValue, null, false, null, false))); list.add(r);
// drop column statement
r = new Row(); r.addValue(new Value(par, "Drop column statement")); r.addValue(new Value(val, getDropColumnStatement("TABLE", testValue, null, false, null, false))); list.add(r);
// Modify column statement
r = new Row(); r.addValue(new Value(par, "Modify column statement")); r.addValue(new Value(val, getModifyColumnStatement("TABLE", testValue, null, false, null, false))); list.add(r);
// List of reserved words
String reserved = "";
if (getReservedWords()!=null) for (int i=0;i<getReservedWords().length;i++) reserved+=(i>0?", ":"")+getReservedWords()[i];
r = new Row(); r.addValue(new Value(par, "List of reserved words")); r.addValue(new Value(val, reserved)); list.add(r);
// Quote reserved words?
r = new Row(); r.addValue(new Value(par, "Quote reserved words?")); r.addValue(new Value(val, quoteReservedWords())); list.add(r);
// Start Quote
r = new Row(); r.addValue(new Value(par, "Start quote for reserved words")); r.addValue(new Value(val, getStartQuote())); list.add(r);
// End Quote
r = new Row(); r.addValue(new Value(par, "End quote for reserved words")); r.addValue(new Value(val, getEndQuote())); list.add(r);
// List of table types
String types = "";
String slist[] = getTableTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new Row(); r.addValue(new Value(par, "List of JDBC table types")); r.addValue(new Value(val, types)); list.add(r);
// List of view types
types = "";
slist = getViewTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new Row(); r.addValue(new Value(par, "List of JDBC view types")); r.addValue(new Value(val, types)); list.add(r);
// List of synonym types
types = "";
slist = getSynonymTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new Row(); r.addValue(new Value(par, "List of JDBC synonym types")); r.addValue(new Value(val, types)); list.add(r);
// Use schema-name to get list of tables?
r = new Row(); r.addValue(new Value(par, "use schema name to get table list?")); r.addValue(new Value(val, useSchemaNameForTableList())); list.add(r);
// supports view?
r = new Row(); r.addValue(new Value(par, "supports views?")); r.addValue(new Value(val, supportsViews())); list.add(r);
// supports synonyms?
r = new Row(); r.addValue(new Value(par, "supports synonyms?")); r.addValue(new Value(val, supportsSynonyms())); list.add(r);
// SQL: get list of procedures?
r = new Row(); r.addValue(new Value(par, "SQL: list of procedures")); r.addValue(new Value(val, getSQLListOfProcedures())); list.add(r);
// SQL: get truncate table statement?
r = new Row(); r.addValue(new Value(par, "SQL: truncate table")); r.addValue(new Value(val, getTruncateTableStatement(null, "TABLE"))); list.add(r);
// supports float rounding on update?
r = new Row(); r.addValue(new Value(par, "supports floating point rounding on update/insert")); r.addValue(new Value(val, supportsFloatRoundingOnUpdate())); list.add(r);
// supports time stamp to date conversion
r = new Row(); r.addValue(new Value(par, "supports timestamp-date conversion")); r.addValue(new Value(val, supportsTimeStampToDateConversion())); list.add(r);
// supports batch updates
r = new Row(); r.addValue(new Value(par, "supports batch updates")); r.addValue(new Value(val, supportsBatchUpdates())); list.add(r);
// supports boolean values
r = new Row(); r.addValue(new Value(par, "supports boolean data type")); r.addValue(new Value(val, supportsBooleanDataType())); list.add(r);
}
return list;
}
*/
/**
* @return true if the database resultsets support getTimeStamp() to retrieve date-time. (Date)
*/
public boolean supportsTimeStampToDateConversion()
{
return databaseInterface.supportsTimeStampToDateConversion();
}
/**
* @return true if the database JDBC driver supports batch updates
* For example Interbase doesn't support this!
*/
public boolean supportsBatchUpdates()
{
return databaseInterface.supportsBatchUpdates();
}
/**
* @return true if the database supports a boolean, bit, logical, ... datatype
*/
public boolean supportsBooleanDataType()
{
return databaseInterface.supportsBooleanDataType();
}
/**
* Changes the names of the fields to their quoted equivalent if this is needed
* @param fields The row of fields to change
*/
public void quoteReservedWords(RowMetaInterface fields)
{
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
v.setName( quoteField(v.getName()) );
}
}
/**
* @return a map of all the extra URL options you want to set.
*/
public Map<String, String> getExtraOptions()
{
return databaseInterface.getExtraOptions();
}
/**
* @return true if the database supports connection options in the URL, false if they are put in a Properties object.
*/
public boolean supportsOptionsInURL()
{
return databaseInterface.supportsOptionsInURL();
}
/**
* @return extra help text on the supported options on the selected database platform.
*/
public String getExtraOptionsHelpText()
{
return databaseInterface.getExtraOptionsHelpText();
}
/**
* @return true if the database JDBC driver supports getBlob on the resultset. If not we must use getBytes() to get the data.
*/
public boolean supportsGetBlob()
{
return databaseInterface.supportsGetBlob();
}
/**
* @return The SQL to execute right after connecting
*/
public String getConnectSQL()
{
return databaseInterface.getConnectSQL();
}
/**
* @param sql The SQL to execute right after connecting
*/
public void setConnectSQL(String sql)
{
databaseInterface.setConnectSQL(sql);
}
/**
* @return true if the database supports setting the maximum number of return rows in a resultset.
*/
public boolean supportsSetMaxRows()
{
return databaseInterface.supportsSetMaxRows();
}
/**
* Verify the name of the database and if required, change it if it already exists in the list of databases.
* @param databases the databases to check against.
* @param oldname the old name of the database
* @return the new name of the database connection
*/
public String verifyAndModifyDatabaseName(List<DatabaseMeta> databases, String oldname)
{
String name = getName();
if (name.equalsIgnoreCase(oldname)) return name; // nothing to see here: move along!
int nr = 2;
while (DatabaseMeta.findDatabase(databases, getName())!=null)
{
setName(name+" "+nr);
nr++;
}
return getName();
}
/**
* @return true if we want to use a database connection pool
*/
public boolean isUsingConnectionPool()
{
return databaseInterface.isUsingConnectionPool();
}
/**
* @param usePool true if we want to use a database connection pool
*/
public void setUsingConnectionPool(boolean usePool)
{
databaseInterface.setUsingConnectionPool(usePool);
}
/**
* @return the maximum pool size
*/
public int getMaximumPoolSize()
{
return databaseInterface.getMaximumPoolSize();
}
/**
* @param maximumPoolSize the maximum pool size
*/
public void setMaximumPoolSize(int maximumPoolSize)
{
databaseInterface.setMaximumPoolSize(maximumPoolSize);
}
/**
* @return the initial pool size
*/
public int getInitialPoolSize()
{
return databaseInterface.getInitialPoolSize();
}
/**
* @param initalPoolSize the initial pool size
*/
public void setInitialPoolSize(int initalPoolSize)
{
databaseInterface.setInitialPoolSize(initalPoolSize);
}
/**
* @return true if the connection contains partitioning information
*/
public boolean isPartitioned()
{
return databaseInterface.isPartitioned();
}
/**
* @param partitioned true if the connection is set to contain partitioning information
*/
public void setPartitioned(boolean partitioned)
{
databaseInterface.setPartitioned(partitioned);
}
/**
* @return the available partition/host/databases/port combinations in the cluster
*/
public PartitionDatabaseMeta[] getPartitioningInformation()
{
return databaseInterface.getPartitioningInformation();
}
/**
* @param partitionInfo the available partition/host/databases/port combinations in the cluster
*/
public void setPartitioningInformation(PartitionDatabaseMeta[] partitionInfo)
{
databaseInterface.setPartitioningInformation(partitionInfo);
}
/**
* Finds the partition metadata for the given partition iD
* @param partitionId The partition ID to look for
* @return the partition database metadata or null if nothing was found.
*/
public PartitionDatabaseMeta getPartitionMeta(String partitionId)
{
PartitionDatabaseMeta[] partitionInfo = getPartitioningInformation();
for (int i=0;i<partitionInfo.length;i++)
{
if (partitionInfo[i].getPartitionId().equals(partitionId)) return partitionInfo[i];
}
return null;
}
public Properties getConnectionPoolingProperties()
{
return databaseInterface.getConnectionPoolingProperties();
}
public void setConnectionPoolingProperties(Properties properties)
{
databaseInterface.setConnectionPoolingProperties(properties);
}
public String getSQLTableExists(String tablename)
{
return databaseInterface.getSQLTableExists(tablename);
}
public boolean needsToLockAllTables()
{
return databaseInterface.needsToLockAllTables();
}
public String getQuotedSchemaTableCombination(String schemaName, String tableName)
{
return getSchemaTableCombination(quoteField(schemaName), quoteField(tableName));
}
/**
* @return true if the database is streaming results (normally this is an option just for MySQL).
*/
public boolean isStreamingResults()
{
return databaseInterface.isStreamingResults();
}
/**
* @param useStreaming true if we want the database to stream results (normally this is an option just for MySQL).
*/
public void setStreamingResults(boolean useStreaming)
{
databaseInterface.setStreamingResults(useStreaming);
}
/**
* @return true if all fields should always be quoted in db
*/
public boolean isQuoteAllFields()
{
return databaseInterface.isQuoteAllFields();
}
/**
* @param quoteAllFields true if all fields in DB should be quoted.
*/
public void setQuoteAllFields(boolean quoteAllFields)
{
databaseInterface.setQuoteAllFields(quoteAllFields);
}
/**
* Find a database with a certain name in an arraylist of databases.
* @param databases The ArrayList of databases
* @param dbname The name of the database connection
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<? extends SharedObjectInterface> databases, String dbname)
{
if (databases == null)
return null;
for (int i = 0; i < databases.size(); i++)
{
DatabaseMeta ci = (DatabaseMeta) databases.get(i);
if (ci.getName().equalsIgnoreCase(dbname))
return ci;
}
return null;
}
/**
* Find a database with a certain name in an ArrayList of databases.
* @param databases The ArrayList of databases
* @param dbname The name of the database connection
* @param exclude the name of the database connection to exclude from the search
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<DatabaseMeta> databases, String dbname, String exclude)
{
if (databases == null)
return null;
for (int i = 0; i < databases.size(); i++)
{
DatabaseMeta ci = (DatabaseMeta) databases.get(i);
if (ci.getName().equalsIgnoreCase(dbname))
return ci;
}
return null;
}
/**
* Find a database with a certain ID in an arraylist of databases.
* @param databases The ArrayList of databases
* @param id The id of the database connection
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<DatabaseMeta> databases, long id)
{
if (databases == null)
return null;
for (DatabaseMeta ci : databases)
{
if (ci.getID() == id) {
return ci;
}
}
return null;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
}
|
package com.vk.api.sdk.queries.wall;
import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.wall.responses.CreateCommentResponse;
import java.util.Arrays;
import java.util.List;
/**
* Query for Wall.createComment method
*/
public class WallCreateCommentQuery extends AbstractQueryBuilder<WallCreateCommentQuery, CreateCommentResponse> {
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param postId value of "post id" parameter. Minimum is 0.
*/
public WallCreateCommentQuery(VkApiClient client, UserActor actor, int postId) {
super(client, "wall.createComment", CreateCommentResponse.class);
accessToken(actor.getAccessToken());
postId(postId);
}
/**
* User ID or community ID. Use a negative value to designate a community ID.
*
* @param value value of "owner id" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery ownerId(Integer value) {
return unsafeParam("owner_id", value);
}
/**
* Post ID.
*
* @param value value of "post id" parameter. Minimum is 0.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected WallCreateCommentQuery postId(int value) {
return unsafeParam("post_id", value);
}
/**
* Post the comment as from the community;
*
* @param value value of "from group" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery fromGroup(Integer value) {
return unsafeParam("from_group", value);
}
/**
* (Required if "attachments" is not set.) Text of the comment.
*
* @param value value of "message" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery message(String value) {
return unsafeParam("message", value);
}
/**
* ID of comment to reply.
*
* @param value value of "reply to comment" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery replyToComment(Integer value) {
return unsafeParam("reply_to_comment", value);
}
/**
* (Required if "message" is not set.) List of media objects attached to the comment, in the following format:
* "type""owner_id"_"media_id"
* ""type"" - Type of media ojbect:
* "photo" - photo
* "video" - video
* "audio" - audio
* "doc" - document
* ""owner_id"" - ID of the media owner.
* ""media_id"" - Media ID.
* <p>
* For example:
* photo100172_166443618,photo66748_265827614
*
* @param value value of "attachments" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery attachments(String... value) {
return unsafeParam("attachments", value);
}
/**
* (Required if "message" is not set.) List of media objects attached to the comment, in the following format:
* "type""owner_id"_"media_id"
* ""type"" - Type of media ojbect:
* "photo" - photo
* "video" - video
* "audio" - audio
* "doc" - document
* ""owner_id"" - ID of the media owner.
* ""media_id"" - Media ID.
* <p>
* For example:
* photo100172_166443618,photo66748_265827614
*
* @param value value of "attachments" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery attachments(List<String> value) {
return unsafeParam("attachments", value);
}
/**
* Sticker ID.
*
* @param value value of "sticker id" parameter. Minimum is 0.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery stickerId(Integer value) {
return unsafeParam("sticker_id", value);
}
/**
* Unique identifier to avoid repeated comments.
*
* @param value value of "guid" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public WallCreateCommentQuery guid(String value) {
return unsafeParam("guid", value);
}
@Override
protected WallCreateCommentQuery getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Arrays.asList("post_id", "access_token");
}
}
|
package org.uefiide.handlers;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.core.internal.resources.Project;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import org.uefiide.wizards.NewEdk2ModuleFileWizard;
public class NewEdk2SourceHandler implements IHandler {
@Override
public void addHandlerListener(IHandlerListener handlerListener) {
}
@Override
public void dispose() {
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell shell = HandlerUtil.getActiveShell(event);
ISelection sel = HandlerUtil.getActiveMenuSelection(event);
IStructuredSelection selection = (IStructuredSelection) sel;
NewEdk2ModuleFileWizard wizard = new NewEdk2ModuleFileWizard((IProject)selection.getFirstElement());
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.open();
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean isHandled() {
return true;
}
@Override
public void removeHandlerListener(IHandlerListener handlerListener) {
}
}
|
package pathfinding.astar.arcs;
import graphic.PrintBuffer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedList;
import memory.CinemObsMM;
import config.Config;
import config.ConfigInfo;
import config.Configurable;
import container.Service;
import obstacles.types.ObstacleCircular;
import robot.Cinematique;
import robot.CinematiqueObs;
import robot.RobotChrono;
import robot.Speed;
import utils.Log;
import utils.Vec2RO;
import utils.Vec2RW;
public class ClothoidesComputer implements Service, Configurable
{
private Log log;
private CinemObsMM memory;
private PrintBuffer buffer;
private BigDecimal x, y;
private static final int S_MAX = 10;
public static final double PRECISION_TRACE = 0.02;
public static final double PRECISION_TRACE_1000 = PRECISION_TRACE*1000;
private static final int INDICE_MAX = (int) (S_MAX / PRECISION_TRACE);
public static final int NB_POINTS = 5; // nombre de points dans un arc
public static final double DISTANCE_ARC_COURBE = PRECISION_TRACE * NB_POINTS * 1000; // en mm
static final double DISTANCE_ARC_COURBE_M = PRECISION_TRACE * NB_POINTS; // en m
public static final double d = PRECISION_TRACE * 1000 / 2;
private double courbureMax;
private Vec2RO[] trajectoire = new Vec2RO[2 * INDICE_MAX - 1];
public ClothoidesComputer(Log log, CinemObsMM memory, PrintBuffer buffer)
{
this.memory = memory;
this.log = log;
this.buffer = buffer;
if(!chargePoints()) // le calcul est un peu long, donc on le sauvegarde
{
init();
sauvegardePoints();
}
}
private void calculeXY(BigDecimal sparam)
{
BigDecimal s = sparam;
x = s;
BigDecimal factorielle = new BigDecimal(1).setScale(15, RoundingMode.HALF_EVEN);
BigDecimal b2 = new BigDecimal(1).setScale(15, RoundingMode.HALF_EVEN);
BigDecimal s2 = s.multiply(s);
BigDecimal b = b2;
s = s.multiply(s2);
y = s.divide(b.multiply(new BigDecimal(3).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN);
BigDecimal seuil = new BigDecimal(0.000000000001).setScale(15, RoundingMode.HALF_EVEN);
BigDecimal tmp;
long i = 1;
do
{
factorielle = factorielle.multiply(new BigDecimal(2*i).setScale(15, RoundingMode.HALF_EVEN));
b = b.multiply(b2);
s = s.multiply(s2);
tmp = s.divide(factorielle.multiply(b).multiply(new BigDecimal(4*i+1).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN);
if((i & 1) == 0)
x = x.add(tmp);
else
x = x.subtract(tmp);
factorielle = factorielle.multiply(new BigDecimal(2*i+1).setScale(15, RoundingMode.HALF_EVEN));
b = b.multiply(b2);
s = s.multiply(s2);
tmp = s.divide(factorielle.multiply(b).multiply(new BigDecimal(4*i+3).setScale(15, RoundingMode.HALF_EVEN)), RoundingMode.HALF_EVEN);
if((i & 1) == 0)
y = y.add(tmp);
else
y = y.subtract(tmp);
i++;
} while(tmp.abs().compareTo(seuil) > 0);
y = y.multiply(new BigDecimal(1000));
x = x.multiply(new BigDecimal(1000));
}
private void init()
{
for(int s = 0; s < 2 * INDICE_MAX - 1; s++)
{
calculeXY(new BigDecimal((s - INDICE_MAX + 1) * PRECISION_TRACE).setScale(15, RoundingMode.HALF_EVEN));
trajectoire[s] = new Vec2RO(x.doubleValue(), y.doubleValue());
trajectoire[2 * INDICE_MAX - 2 - s] = new Vec2RO(-x.doubleValue(), -y.doubleValue());
System.out.println((s - INDICE_MAX + 1) * PRECISION_TRACE+" "+trajectoire[s]);
buffer.addSupprimable(new ObstacleCircular(new Vec2RO(x.doubleValue(), 1000+y.doubleValue()), 5));
buffer.addSupprimable(new ObstacleCircular(new Vec2RO(-x.doubleValue(), 1000-y.doubleValue()), 5));
}
}
public final ArcCourbeDynamique cubicInterpolation(RobotChrono robot, Cinematique arrivee, Speed vitesseMax, VitesseCourbure v)
{
return cubicInterpolation(robot.getCinematique(), arrivee, vitesseMax, v);
}
public final ArcCourbeDynamique cubicInterpolation(Cinematique cinematiqueInitiale, Cinematique arrivee, Speed vitesseMax, VitesseCourbure v)
{
// log.debug(v);
double alphas[] = {100, 300, 600, 800, 1000, 1200};
// log.debug("Interpolation cubique, rebrousse : "+v.rebrousse);
double sin, cos;
double courbure = cinematiqueInitiale.courbureGeometrique,
orientation = cinematiqueInitiale.orientationGeometrique;
if(v.rebrousse) // si on rebrousse, la courbure est nulle
{
orientation += Math.PI;
courbure = 0;
}
Speed vitesse = vitesseMax;
if(!(v.rebrousse ^ cinematiqueInitiale.enMarcheAvant))
vitesse = Speed.values()[vitesseMax.ordinal()+1];
sin = Math.sin(orientation);
cos = Math.cos(orientation);
LinkedList<CinematiqueObs> out = new LinkedList<CinematiqueObs>();
for(int i = 0; i < alphas.length; i++)
{
double alpha = alphas[i];
double bx, by;
if(Math.abs(cos) < Math.abs(sin))
{
bx = -courbure/1000*alpha*alpha/(2*sin);
by = 0;
}
else
{
bx = 0;
by = courbure/1000*alpha*alpha/(2*cos);
}
double dx = cinematiqueInitiale.getPosition().getX();
double cx = cos*alpha;
double ax = arrivee.getPosition().getX() - bx - cx - dx;
// idem pour y
double dy = cinematiqueInitiale.getPosition().getY();
double cy = sin*alpha;
double ay = arrivee.getPosition().getY() - by - cy - dy;
boolean first = true;
double t = 1, tnext = 1, lastCourbure = 0, lastOrientation = 0;
double longueur = 0;
CinematiqueObs last = null, actuel;
boolean error = false;
out.clear();
while(t > 0.)
{
double tmp1 = 3*ax*t*t+2*bx*t+cx;
double tmp2 = 3*ay*t*t+2*by*t+cy;
tnext -= PRECISION_TRACE*1000/(Math.sqrt(tmp1 * tmp1 + tmp2 * tmp2));
if(tnext < 0)
tnext = 0;
double t2 = t*t;
double x = ax*t*t2 + bx*t2 + cx*t + dx;
double y = ay*t*t2 + by*t2 + cy*t + dy;
double vx = 3*ax*t2+2*bx*t+cx;
double vy = 3*ay*t2+2*by*t+cy;
double acx = 6*ax*t+2*bx;
double acy = 6*ay*t+2*by;
actuel = memory.getNewNode();
actuel.update(
x,
y,
Math.atan2(vy, vx), // orientation = atan2(vy, vx)
v.rebrousse ^ cinematiqueInitiale.enMarcheAvant,
1000*(vx * acy - vy * acx) / Math.pow(vx*vx + vy*vy, 1.5),
vitesse.translationalSpeed);
// TODO vitesse
// log.debug(t);
// On prend de la marge
if(x < -1500 || x > 1500 || y < 0 || y > 2000 || Math.abs(actuel.courbureGeometrique) > courbureMax*0.7 || (!first && (Math.abs(actuel.courbureGeometrique - lastCourbure) > 3 || Math.abs(actuel.orientationGeometrique - lastOrientation) > 1)))
{
// log.debug("ERREUR");
error = true;
break;
}
// log.debug(x+" "+y);
lastCourbure = actuel.courbureGeometrique;
lastOrientation = actuel.orientationGeometrique;
// calcul de la longueur de l'arc
if(last != null)
{
longueur += actuel.getPosition().distanceFast(last.getPosition());
}
out.addFirst(actuel);
last = actuel;
first = false;
t = tnext;
}
// dans ce cas, on ignore l'arc
if(error || out.size() < (cinematiqueInitiale.getPosition().distanceFast(arrivee.getPosition()) / (1000 * PRECISION_TRACE))) // on essaye un autre alpha
{
for(CinematiqueObs c : out)
memory.destroyNode(c);
continue;
}
if(out.getFirst().getPosition().squaredDistance(cinematiqueInitiale.getPosition()) < (PRECISION_TRACE*1000*PRECISION_TRACE*1000)*0.7)
out.removeFirst();
return new ArcCourbeDynamique(out, longueur, v.rebrousse);
}
return null;
}
public void getTrajectoire(ArcCourbe depart, VitesseCourbure vitesse, Speed vitesseMax, ArcCourbeStatique modified)
{
CinematiqueObs last = depart.getLast();
getTrajectoire(last, vitesse, vitesseMax, modified);
}
public final void getTrajectoire(RobotChrono robot, VitesseCourbure vitesse, Speed vitesseMax, ArcCourbeStatique modified)
{
getTrajectoire(robot.getCinematique(), vitesse, vitesseMax, modified);
}
public final void getTrajectoire(Cinematique cinematiqueInitiale, VitesseCourbure vitesse, Speed vitesseMax, ArcCourbeStatique modified)
{
// modified.v = vitesse;
// log.debug(vitesse);
double courbure = cinematiqueInitiale.courbureGeometrique;
double orientation = cinematiqueInitiale.orientationGeometrique;
if(vitesse.rebrousse)
{
courbure = 0;
orientation += Math.PI;
}
boolean marcheAvant = vitesse.rebrousse ^ cinematiqueInitiale.enMarcheAvant;
Speed vitesseTr = vitesseMax;
if(!marcheAvant)
vitesseTr = Speed.values()[vitesseMax.ordinal()+1];
if(vitesse.vitesse == 0)
{
if(courbure < 0.00001 && courbure > -0.00001)
getTrajectoireLigneDroite(cinematiqueInitiale.getPosition(), orientation, vitesseTr, modified, marcheAvant);
else
getTrajectoireCirculaire(cinematiqueInitiale.getPosition(), orientation, courbure, vitesseTr, modified, marcheAvant);
return;
}
double coeffMultiplicatif = 1. / vitesse.squaredRootVitesse;
double sDepart = courbure / vitesse.squaredRootVitesse;
if(!vitesse.positif)
sDepart = -sDepart;
int pointDepart = (int) ((sDepart / PRECISION_TRACE) + INDICE_MAX - 1 + 0.5); // le 0.5 vient du fait qu'on fait ici un arrondi
if(pointDepart < 0 || pointDepart >= trajectoire.length)
log.critical("Sorti de la clothoïde précalculée !");
double orientationClothoDepart = sDepart * sDepart;
if(!vitesse.positif)
orientationClothoDepart = - orientationClothoDepart;
double baseOrientation = orientation - orientationClothoDepart;
double cos = Math.cos(baseOrientation);
double sin = Math.sin(baseOrientation);
// for(int i = 0; i < NB_POINTS; i++)
// log.debug("Clotho : "+trajectoire[vitesse.squaredRootVitesse * (i + 1)]);
// le premier point n'est pas position, mais le suivant
for(int i = 0; i < NB_POINTS; i++)
{
sDepart += vitesse.squaredRootVitesse * PRECISION_TRACE;
computePoint(pointDepart, vitesse, sDepart, coeffMultiplicatif, i, baseOrientation, cos, sin, marcheAvant, vitesseTr, cinematiqueInitiale.getPosition(), modified.arcselems[i]);
}
modified.rebrousse = vitesse.rebrousse;
}
private void computePoint(int pointDepart, VitesseCourbure vitesse, double sDepart, double coeffMultiplicatif, int i, double baseOrientation, double cos, double sin, boolean marcheAvant, Speed vitesseTr, Vec2RO positionInitiale, CinematiqueObs c)
{
trajectoire[pointDepart + vitesse.squaredRootVitesse * (i + 1)].copy(c.getPositionEcriture());
c.getPositionEcriture().minus(trajectoire[pointDepart])
.scalar(coeffMultiplicatif)
.Ysym(!vitesse.positif)
.rotate(cos, sin)
.plus(positionInitiale);
double orientationClotho = sDepart * sDepart;
if(!vitesse.positif)
orientationClotho = - orientationClotho;
c.orientationGeometrique = baseOrientation + orientationClotho;
c.courbureGeometrique = sDepart * vitesse.squaredRootVitesse;
if(!vitesse.positif)
c.courbureGeometrique = - c.courbureGeometrique;
if(marcheAvant)
{
c.orientationReelle = c.orientationGeometrique;
c.courbureReelle = c.courbureGeometrique;
}
else
{
c.orientationReelle = c.orientationGeometrique + Math.PI;
c.courbureReelle = - c.courbureGeometrique;
}
c.enMarcheAvant = marcheAvant;
c.vitesseMax = vitesseTr.translationalSpeed;
c.obstacle.update(c.getPosition(), c.orientationReelle);
}
private Vec2RW delta = new Vec2RW();
private Vec2RW centreCercle = new Vec2RW();
/**
* Calcule la trajectoire dans le cas particulier d'une trajectoire circulaire
* @param position
* @param orientation
* @param courbure
* @param modified
*/
private void getTrajectoireCirculaire(Vec2RO position, double orientation, double courbure, Speed vitesseMax, ArcCourbeStatique modified, boolean enMarcheAvant)
{
// log.debug("Trajectoire circulaire !");
// rappel = la courbure est l'inverse du rayon de courbure
double rayonCourbure = 1000. / courbure;
delta.setX(Math.cos(orientation + Math.PI / 2) * rayonCourbure);
delta.setY(Math.sin(orientation + Math.PI / 2) * rayonCourbure);
centreCercle.setX(position.getX() + delta.getX());
centreCercle.setY(position.getY() + delta.getY());
double angle = PRECISION_TRACE * courbure;
double cos = Math.cos(angle);
double sin = Math.sin(angle);
for(int i = 0; i < NB_POINTS; i++)
{
delta.rotate(cos, sin);
centreCercle.copy(modified.arcselems[i].getPositionEcriture());
modified.arcselems[i].getPositionEcriture().minus(delta);
modified.arcselems[i].orientationGeometrique = orientation + angle * (i + 1);
modified.arcselems[i].courbureGeometrique = courbure;
if(enMarcheAvant)
{
modified.arcselems[i].orientationReelle = modified.arcselems[i].orientationGeometrique;
modified.arcselems[i].courbureReelle = modified.arcselems[i].courbureGeometrique;
}
else
{
modified.arcselems[i].orientationReelle = modified.arcselems[i].orientationGeometrique + Math.PI;
modified.arcselems[i].courbureReelle = - modified.arcselems[i].courbureGeometrique;
}
modified.arcselems[i].vitesseMax = vitesseMax.translationalSpeed;
modified.arcselems[i].enMarcheAvant = enMarcheAvant;
modified.arcselems[i].obstacle.update(modified.arcselems[i].getPosition(), modified.arcselems[i].orientationReelle);
}
}
/**
* Calcule la trajectoire dans le cas particulier d'une ligne droite
* @param position
* @param orientation
* @param modified
*/
private void getTrajectoireLigneDroite(Vec2RO position, double orientation, Speed vitesseMax, ArcCourbeStatique modified, boolean enMarcheAvant)
{
double cos = Math.cos(orientation);
double sin = Math.sin(orientation);
for(int i = 0; i < NB_POINTS; i++)
{
double distance = (i + 1) * PRECISION_TRACE * 1000;
modified.arcselems[i].getPositionEcriture().setX(position.getX() + distance * cos);
modified.arcselems[i].getPositionEcriture().setY(position.getY() + distance * sin);
modified.arcselems[i].orientationGeometrique = orientation;
modified.arcselems[i].courbureGeometrique = 0;
modified.arcselems[i].courbureReelle = 0;
if(enMarcheAvant)
modified.arcselems[i].orientationReelle = modified.arcselems[i].orientationGeometrique;
else
modified.arcselems[i].orientationReelle = modified.arcselems[i].orientationGeometrique + Math.PI;
modified.arcselems[i].vitesseMax = vitesseMax.translationalSpeed;
modified.arcselems[i].enMarcheAvant = enMarcheAvant;
modified.arcselems[i].obstacle.update(modified.arcselems[i].getPosition(), modified.arcselems[i].orientationReelle);
}
}
@Override
public void useConfig(Config config)
{
courbureMax = config.getDouble(ConfigInfo.COURBURE_MAX);
}
private void sauvegardePoints()
{
log.debug("Sauvegarde des points de la clothoïde unitaire");
try {
java.io.File fichier_creation;
FileOutputStream fichier;
ObjectOutputStream oos;
fichier_creation = new java.io.File("clotho-"+S_MAX+".dat");
fichier_creation.createNewFile();
fichier = new FileOutputStream("clotho-"+S_MAX+".dat");
oos = new ObjectOutputStream(fichier);
oos.writeObject(trajectoire);
oos.flush();
oos.close();
log.debug("Sauvegarde terminée");
}
catch(IOException e)
{
log.critical("Erreur lors de la sauvegarde des points de la clothoïde ! "+e);
}
}
private boolean chargePoints()
{
log.debug("Chargement des points de la clothoïde");
try {
FileInputStream fichier = new FileInputStream("clotho-"+S_MAX+".dat");
ObjectInputStream ois = new ObjectInputStream(fichier);
trajectoire = (Vec2RO[]) ois.readObject();
ois.close();
return true;
}
catch(IOException | ClassNotFoundException e)
{
log.critical("Chargement échoué !");
}
return false;
}
}
|
package org.gluu.oxtrust.ldap.service;
import org.gluu.oxtrust.config.OxTrustConfiguration;
import org.gluu.site.ldap.persistence.LdapEntryManager;
import org.gluu.site.ldap.persistence.exception.LdapMappingException;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.xdi.config.oxtrust.LdapOxPassportConfiguration;
import org.xdi.service.JsonService;
import org.xdi.util.properties.FileConfiguration;
/**
* Passport service
*
* @author Shekhar L
*/
@Scope(ScopeType.STATELESS)
@Name("passportService")
@AutoCreate
public class OxPassportService {
@Logger
private Log log;
@In
private JsonService jsonService;
@In
private LdapEntryManager ldapEntryManager;
@In
private OxTrustConfiguration oxTrustConfiguration;
public LdapOxPassportConfiguration loadConfigurationFromLdap(String ... returnAttributes) {
try {
FileConfiguration fc = oxTrustConfiguration.getLdapConfiguration();
String configurationDn = fc.getString("oxpassport_ConfigurationEntryDN");
log.info("
if ((configurationDn != null) && !(configurationDn.trim().equals(""))) {
LdapEntryManager ldapEntryManager = (LdapEntryManager) Component.getInstance("ldapEntryManager");
LdapOxPassportConfiguration conf = ldapEntryManager.find(LdapOxPassportConfiguration.class, configurationDn,returnAttributes);
log.info("
log.info("
return conf;
}
} catch (LdapMappingException ex) {
log.error("Failed to load configuration from LDAP", ex);
} catch (Exception ex) {
log.error("Exception ", ex);
}
return null;
}
/**
* Update LdapOxPassportConfiguration entry
*
* @param LdapOxPassportConfiguration
* LdapOxPassportConfiguration
*/
public void updateLdapOxPassportConfiguration(LdapOxPassportConfiguration ldapOxPassportConfiguration) {
ldapEntryManager.merge(ldapOxPassportConfiguration);
}
}
|
package io.spine.base;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import io.spine.code.proto.ScalarType;
import io.spine.type.TypeName;
import io.spine.type.TypeUrl;
import io.spine.value.ValueHolder;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.protobuf.Descriptors.FieldDescriptor.Type.ENUM;
import static com.google.protobuf.Descriptors.FieldDescriptor.Type.MESSAGE;
import static com.google.protobuf.TextFormat.shortDebugString;
import static io.spine.util.Exceptions.newIllegalArgumentException;
import static io.spine.util.Exceptions.newIllegalStateException;
import static io.spine.util.Preconditions2.checkNotEmptyOrBlank;
/**
* A reference to a Protobuf message field.
*
* @apiNote This class aggregates {@link FieldPath} for augmenting this generated class with
* useful methods (instead of using static utilities). This approach is used (instead of using
* {@link io.spine.annotation.GeneratedMixin GeneratedMixin}) because Model Compiler itself depends
* on this package. Thus, {@code GeneratedMixin} cannot be used for augmenting generated classes
* that belong to it.
*/
@Immutable
public final class Field extends ValueHolder<FieldPath> {
private static final String SEPARATOR = ".";
private static final Joiner joiner = Joiner.on(SEPARATOR);
private static final Splitter dotSplitter = Splitter.on(SEPARATOR)
.trimResults();
private static final long serialVersionUID = 0L;
private Field(FieldPath path) {
super(path);
}
private static Field create(FieldPath path) {
checkNotEmpty(path);
return new Field(path);
}
/**
* Creates a new field reference by the passed path.
*/
public static Field withPath(FieldPath path) {
checkNotNull(path);
return create(path);
}
/**
* Parses the passed field path.
*
* @param path
* non-empty field path
* @return the field reference parsed from the path
*/
public static Field parse(String path) {
checkNotNull(path);
FieldPath fp = doParse(path);
return create(fp);
}
/**
* Creates a new field reference by its name.
*
* <p>The passed string is the direct reference to the field, not a field path.
* Therefore it must not contain the dot separator.
*/
public static Field named(String fieldName) {
checkName(fieldName);
FieldPath path = create(ImmutableList.of(fieldName));
Field result = create(path);
return result;
}
public static Field withNumberIn(int number, Descriptor message) {
String name = nameOf(number, message);
Field result = named(name);
return result;
}
public static String nameOf(int fieldNumber, Descriptor message) {
checkNotNull(message);
checkArgument(fieldNumber > 0);
String result = message
.getFields()
.stream()
.filter(f -> f.getNumber() == fieldNumber)
.findFirst()
.map(FieldDescriptor::getName)
.orElseThrow(() -> newIllegalStateException(
"Unable to find the field with the number %d in the type `%s`.",
fieldNumber,
message.getFullName()
));
return result;
}
/** Obtains the path of the field. */
public FieldPath path() {
return value();
}
/**
* Obtains the value of the field in the passed message.
*
* @param holder
* the message which potentially has the referenced field
* @return the value of the field or empty {@code Optional} if the field is not defined
* in this type of messages
*/
public Optional<Object> findValue(Message holder) {
Object value = doGetValue(path(), holder, false);
return Optional.ofNullable(value);
}
public Object valueIn(Message holder) {
Object result = findValue(holder).orElseThrow(
() -> newIllegalStateException("Unable to get the field `%s` from `%s`.",
this, shortDebugString(holder))
);
return result;
}
/**
* Obtains a descriptor of the referenced field in the passed message type.
*
* @return the descriptor, if there is such a field in the passed type, or empty
* {@code Optional} if the field is not declared
*/
public Optional<FieldDescriptor> findDescriptor(Descriptor message) {
@Nullable FieldDescriptor field = fieldIn(path(), message);
return Optional.ofNullable(field);
}
/**
* Obtains the type of the referenced field in the passed message class.
*/
public Optional<Class<?>> findType(Class<? extends Message> holderType) {
Descriptor message = TypeName.of(holderType).messageDescriptor();
@Nullable FieldDescriptor field = fieldIn(path(), message);
if (field == null) {
return Optional.empty();
}
Class<?> result = classOf(field);
return Optional.of(result);
}
/**
* Obtains a string value of the field path.
*
* <p>Unlike {@link Message#toString()}, which produces diagnostics output, this method
* returns the string form of {@code some_field.nested_field.nested_deeper}.
*/
@Override
public String toString() {
return join(value().getFieldNameList());
}
/** Creates a new path containing the passed elements. */
private static FieldPath create(List<String> elements) {
elements.forEach(Field::checkName);
FieldPath result = FieldPath
.newBuilder()
.addAllFieldName(elements)
.build();
return result;
}
/** Creates a path instance by parsing the passed non-empty string. */
@VisibleForTesting
static FieldPath doParse(String fieldPath) {
checkArgument(!fieldPath.isEmpty(), "A field path must not be empty.");
List<String> pathElements = dotSplitter.splitToList(fieldPath);
return create(pathElements);
}
private static @Nullable Object doGetValue(FieldPath path, Message holder, boolean strict) {
Message message = holder;
Object currentValue = message;
for (Iterator<String> iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) {
String fieldName = iterator.next();
Descriptor type = message.getDescriptorForType();
@Nullable FieldDescriptor field = type.findFieldByName(fieldName);
if (field == null) {
if (strict) {
throw newIllegalArgumentException(
"Unable to find the field named `%s` in the type `%s`.",
fieldName, type.getFullName());
}
return null;
}
currentValue = message.getField(field);
currentValue = convertIfEnum(currentValue);
if (currentValue instanceof Message) {
message = (Message) currentValue;
} else {
if (iterator.hasNext()) {
/* We're not at the end of iteration, and the inner path item references a
non-message field. We cannot continue going the path and need to exit
the routine. */
if (strict) {
throw newIllegalArgumentException(
"The field referenced by the name `%s` is not a message, and" +
" it is not possible to obtain a nested field named `%s`. " +
" The full field path is: `%s`.",
fieldName, iterator.next(), withPath(path)
);
}
return null;
}
}
}
return currentValue;
}
/**
* If the passed value is {@code EnumValueDescriptor} converts it to the corresponding
* Java enum value. Otherwise, returns the passed value.
*
* <p>{@link Message#getField(FieldDescriptor)} returns {@code EnumValueDescriptor} if
* a field of a message is an enum value. This descriptor contains information about the
* the value of the enum. This method converts this value into an instance of a generated
* Java {@link Enum} which corresponds to the enum proto type of the field.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
// The generic arg. of the enum is of no importance here.
private static Object convertIfEnum(Object currentValue) {
if (!(currentValue instanceof EnumValueDescriptor)) {
return currentValue;
}
EnumValueDescriptor value = (EnumValueDescriptor) currentValue;
EnumDescriptor enumType = value.getType();
TypeName typeName = TypeName.of(enumType.getFullName());
Class<? extends Enum> cls = typeName.toEnumClass();
Enum enumValue = Enum.valueOf(cls, value.getName());
return enumValue;
}
/**
* Obtains the descriptor of the field in the passed message type.
*
* @return the descriptor or {@code null} if the message type does not declare this field
*/
private static @Nullable FieldDescriptor fieldIn(FieldPath path, Descriptor message) {
Descriptor current = message;
FieldDescriptor field = null;
for (Iterator<String> iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) {
String fieldName = iterator.next();
field = current.findFieldByName(fieldName);
if (field == null) {
return null;
}
if (iterator.hasNext()) {
checkArgument(field.getType() == MESSAGE,
"Field `%s` of the type `%s` is not a message field.");
current = field.getMessageType();
}
}
return field;
}
/** Ensures that the passed filed name does not contain the path separator. */
private static void checkName(String fieldName) {
checkNotEmptyOrBlank(fieldName);
checkArgument(
!fieldName.contains(SEPARATOR),
"A field name cannot contain path separator. Found: `%s`.", fieldName
);
}
/** Obtains the type of the values stored in the field. */
static Class<?> classOf(FieldDescriptor field) {
FieldDescriptor.Type type = field.getType();
if (type == MESSAGE) {
Class<?> cls = TypeUrl.from(field.getMessageType()).toJavaClass();
return cls;
} else if (type == ENUM) {
Class<?> cls = TypeUrl.from(field.getEnumType()).toJavaClass();
return cls;
} else {
Class<?> result = ScalarType.javaType(field.toProto().getType());
return result;
}
}
/** Ensures that the passed path has at least one element. */
private static void checkNotEmpty(FieldPath path) throws IllegalArgumentException {
checkArgument(path.getFieldNameCount() > 0, "Field path must not be empty.");
}
/**
* Joins the passed path elements into the string representation of the path.
*/
private static String join(Iterable<String> elements) {
String result = joiner.join(elements);
return result;
}
}
|
package fi.nls.oskari.control;
import fi.nls.oskari.domain.GuestUser;
import fi.nls.oskari.domain.User;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.IOHelper;
import fi.nls.oskari.util.RequestHelper;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* A wrapper class for request/response that is populated before giving to ActionHandlers.
* ActionHandlers use this to process a request.
*/
public class ActionParameters {
private HttpServletRequest request;
private HttpServletResponse response;
private User user;
private Locale locale;
private Map<String, Object> additionalParams = new HashMap<String, Object>();
/**
* The original request
* @return
*/
public HttpServletRequest getRequest() {
return request;
}
/**
* The original request
*/
public void setRequest(HttpServletRequest request) {
this.request = request;
}
/**
* The original response
* @return
*/
public HttpServletResponse getResponse() {
return response;
}
/**
* The original response
*/
public void setResponse(HttpServletResponse response) {
this.response = response;
}
/**
* The user requesting an operation.
* Defaults to GuestUser
* @return
*/
public User getUser() {
if(user == null) {
user = GuestUser.getInstance();
}
return user;
}
/**
* The user requesting an operation.
* @param user
*/
public void setUser(User user) {
this.user = user;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
* This can be used to provide handlers with platform specific parameters without
* poluting base-packages with such dependencies.
* For example ThemeDisplay for Liferay could be passed here.
* Note that the component populating the params must fill this and
* the key needs to be known by both the populator and the handler using it.
* @param key
* @param obj
*/
public void putAdditionalParam(final String key, final Object obj) {
additionalParams.put(key, obj);
}
/**
* @see #putAdditionalParam
*/
public Object getAdditionalParam(final String key) {
return additionalParams.get(key);
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @return cleaned up value for the parameter as int
* @throws ActionParamsException if parameter is not found, is empty or can't be parsed as int
*/
public int getRequiredParamInt(final String key) throws ActionParamsException {
final String errMsg = "Required parameter '" + key + "' missing!";
final String val = getRequiredParam(key, errMsg);
try {
return Integer.parseInt(val);
} catch (Exception e) {
throw new ActionParamsException(errMsg);
}
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @return cleaned up value for the parameter as long
* @throws ActionParamsException if parameter is not found, is empty or can't be parsed as long
*/
public long getRequiredParamLong(final String key) throws ActionParamsException {
final String errMsg = "Required parameter '" + key + "' missing!";
final String val = getRequiredParam(key, errMsg);
try {
return Long.parseLong(val);
} catch (Exception e) {
throw new ActionParamsException(errMsg);
}
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @return cleaned up value for the parameter as double
* @throws ActionParamsException if parameter is not found, is empty or can't be parsed as double
*/
public double getRequiredParamDouble(final String key) throws ActionParamsException {
final String errMsg = "Required parameter '" + key + "' missing!";
final String val = getRequiredParam(key, errMsg);
try {
return Double.parseDouble(val);
} catch (Exception e) {
throw new ActionParamsException(errMsg);
}
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @return cleaned up value for the parameter
* @throws ActionParamsException if parameter is not found or is empty
*/
public String getRequiredParam(final String key) throws ActionParamsException {
return getRequiredParam(key, "Required parameter '" + key + "' missing!");
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @param msg message for exception to be thrown if parameter is not present
* @return cleaned up value for the parameter
* @throws ActionParamsException if parameter is not found or is empty
*/
public String getRequiredParam(final String key, final String msg) throws ActionParamsException {
if(msg == null) {
return getRequiredParam(key);
}
final String value = RequestHelper.cleanString(getRequest().getParameter(key));
if(value == null || value.isEmpty()) {
throw new ActionParamsException(msg);
}
return value;
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @return cleaned up value for the parameter or null if not found
*/
public String getHttpParam(final String key) {
return RequestHelper.cleanString(getRequest().getParameter(key));
}
/**
* Returns a cleaned up (think XSS) value for the requested parameter
* @param key parameter name
* @param defaultValue value to be returned if parameter is not present in the request
* @return cleaned up value for the parameter or given defaultValue if not found
*/
public String getHttpParam(final String key, final String defaultValue) {
return RequestHelper.getString(getRequest().getParameter(key), defaultValue);
}
/**
* Returns a parameter as integer or default value if not present/can't be parsed
* @param key parameter name for an integer parameter
* @param defaultValue value to be returned if parameter is not present in the request or can't be parsed
* @return cleaned up value for the parameter or given defaultValue if not found
*/
public int getHttpParam(final String key, final int defaultValue) {
return ConversionHelper.getInt(getHttpParam(key), defaultValue);
}
/**
* Returns a parameter as long or default value if not present/can't be parsed
* @param key parameter name for an long parameter
* @param defaultValue value to be returned if parameter is not present in the request or can't be parsed
* @return cleaned up value for the parameter or given defaultValue if not found
*/
public long getHttpParam(final String key, final long defaultValue) {
return ConversionHelper.getLong(getHttpParam(key), defaultValue);
}
/**
* Returns a parameter as boolean or default value if not present/can't be parsed
* @param key parameter name for a boolean parameter
* @param defaultValue value to be returned if parameter is not present in the request or can't be parsed
* @return cleaned up value for the parameter or given defaultValue if not found
*/
public boolean getHttpParam(final String key, final boolean defaultValue) {
return ConversionHelper.getBoolean(getHttpParam(key), defaultValue);
}
/**
* Returns a parameter as JSONObject
* @param key parameter name for a JSONObject parameter
* @return param value as a JSONObject or null if parameter wasn't present
* @throws ActionParamsException if param was present, but the value couldn't be parsed as a JSONObject
*/
public JSONObject getHttpParamAsJSON(final String key) throws ActionParamsException {
String json = getHttpParam(key);
if(json == null) {
return null;
}
try {
return new JSONObject(json);
} catch (JSONException ex) {
throw new ActionParamsException("Expected param '" + key + "' to have a JSON object as value");
}
}
/**
* Returns value of a header field matching given key
* @param key header name
* @return
*/
public String getHttpHeader(final String key) {
return getRequest().getHeader(key);
}
/**
* Returns clients ip from header "x-forwarded-for" or requests remote address.
* Defaults to "0.0.0.0" on exception.
* @return
*/
public String getClientIp() {
return getClientIp(getRequest());
}
public static String getClientIp(HttpServletRequest hsr) {
final String ip = hsr.getHeader("x-forwarded-for");
try {
return ip != null ? ip : hsr.getRemoteAddr();
} catch (Exception ignored) { }
return "0.0.0.0";
}
/**
* Returns the cookie matching the given name.
* @param name cookie name
* @return
*/
public Cookie getCookie(final String name) {
final Cookie[] cookies = request.getCookies();
if(cookies != null && name != null) {
for (int i=0; i < cookies.length; i++) {
if (cookies[i].getName().equals(name)) return cookies[i];
}
}
return null;
}
/**
* Calling this will throw an exception if user isn't logged in
* @throws ActionDeniedException if user is guest
*/
public void requireLoggedInUser() throws ActionDeniedException {
if(getUser().isGuest()) {
throw new ActionDeniedException("Session expired");
}
}
/**
* Calling this will throw an exception if user isn't an admin
* @throws ActionDeniedException if user is not admin
*/
public void requireAdminUser() throws ActionDeniedException {
requireLoggedInUser();
if(!getUser().isAdmin()) {
throw new ActionDeniedException("Admin only");
}
}
/**
* Returns an api key for the request
* @return
*/
public String getAPIkey() {
// TODO: use something better than session id
return getRequest().getSession().getId();
}
public String getPayLoad() throws ActionParamsException {
HttpServletRequest req = this.getRequest();
try (InputStream in = req.getInputStream()) {
final byte[] json = IOHelper.readBytes(in);
return new String(json, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new ActionParamsException("Unable to read payload", e);
}
}
/**
* Get play load JSON
* @return
*/
public JSONObject getPayLoadJSON() throws ActionParamsException {
try {
return new JSONObject(getPayLoad());
} catch (JSONException e) {
throw new ActionParamsException("Cannot get payload JSON", e);
}
}
}
|
package com.opengamma.sesame.engine;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.opengamma.DataNotFoundException;
import com.opengamma.component.tool.ToolContextUtils;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.core.convention.ConventionSource;
import com.opengamma.core.exchange.ExchangeSource;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.legalentity.LegalEntitySource;
import com.opengamma.core.marketdatasnapshot.MarketDataSnapshotSource;
import com.opengamma.core.position.PositionSource;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.tool.ToolContext;
import com.opengamma.util.ArgumentChecker;
/**
* Loads components using {@link ToolContext} configuration and puts them in a map.
* This isn't a long-term solution but will do for the time being.
* TODO rename ComponentLookup or create interface and have this implement it
* TODO would it be better to compose by delegation/chaining instead of with()?
*/
public final class ComponentMap {
private static final Logger s_logger = LoggerFactory.getLogger(ComponentMap.class);
/**
* The empty component map.
*/
public static final ComponentMap EMPTY = new ComponentMap(Collections.<Class<?>, Object>emptyMap());
private final ImmutableMap<Class<?>, Object> _components;
private ComponentMap(Map<Class<?>, Object> components) {
_components = ImmutableMap.copyOf(components);
}
/**
* @param toolContext a tool context containing the components
* @return The available components, keyed by type.
*/
public static ComponentMap loadComponents(ToolContext toolContext) {
ArgumentChecker.notNull(toolContext, "toolContext");
ImmutableMap.Builder<Class<?>, Object> builder = ImmutableMap.builder();
builder.put(ConfigSource.class, toolContext.getConfigSource());
builder.put(ConventionBundleSource.class, toolContext.getConventionBundleSource());
builder.put(ConventionSource.class, toolContext.getConventionSource());
builder.put(ExchangeSource.class, toolContext.getExchangeSource());
builder.put(HolidaySource.class, toolContext.getHolidaySource());
builder.put(LegalEntitySource.class, toolContext.getLegalEntitySource());
builder.put(PositionSource.class, toolContext.getPositionSource());
builder.put(RegionSource.class, toolContext.getRegionSource());
builder.put(SecuritySource.class, toolContext.getSecuritySource());
builder.put(HistoricalTimeSeriesSource.class, toolContext.getHistoricalTimeSeriesSource());
builder.put(MarketDataSnapshotSource.class, toolContext.getMarketDataSnapshotSource());
return new ComponentMap(builder.build());
}
/**
* @param location Location of the component config, can be a classpath: or file: resource or the URL of a remote
* server
* @return The available components, keyed by type.
*/
public static ComponentMap loadComponents(String location) {
ArgumentChecker.notEmpty(location, "location");
s_logger.info("Loading components from {}", location);
ToolContext toolContext = ToolContextUtils.getToolContext(location, ToolContext.class);
return loadComponents(toolContext);
}
/**
* Returns a component or throws an exception if there is no component available of the required type.
* @param type The required component type
* @param <T> The required component type
* @return A component of the required type, not null
* @throws DataNotFoundException If there is no component of the specified type
*/
@SuppressWarnings("unchecked")
public <T> T getComponent(Class<T> type) {
T component = (T) _components.get(ArgumentChecker.notNull(type, "type"));
if (component == null) {
throw new DataNotFoundException("No component found of type " + type);
}
return component;
}
/**
* Returns a component or null if there is no component available of the required type.
* @param type The required component type
* @param <T> The required component type
* @return A component of the required type or null if there isn't one
*/
@SuppressWarnings("unchecked")
public <T> T findComponent(Class<T> type) {
return (T) _components.get(ArgumentChecker.notNull(type, "type"));
}
public ComponentMap with(Map<Class<?>, Object> components) {
ArgumentChecker.notNull(components, "components");
ImmutableMap.Builder<Class<?>, Object> builder = ImmutableMap.builder();
return new ComponentMap(builder.putAll(_components).putAll(components).build());
}
public <T, U extends T> ComponentMap with(Class<T> type, U component) {
ArgumentChecker.notNull(type, "type");
ArgumentChecker.notNull(component, "component");
ImmutableMap.Builder<Class<?>, Object> builder = ImmutableMap.builder();
return new ComponentMap(builder.putAll(_components).put(type, component).build());
}
public static ComponentMap of(Map<Class<?>, Object> components) {
ArgumentChecker.notNull(components, "components");
return new ComponentMap(ImmutableMap.copyOf(components));
}
/**
* @return The components keyed by type
*/
public Map<Class<?>, Object> getComponents() {
return _components;
}
/**
* @return The types of the available components
*/
public Set<Class<?>> getComponentTypes() {
return _components.keySet();
}
}
|
package main.java;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TextView implements Observer
{
private final static Logger logger = LoggerFactory.getLogger(TextView.class);
private final static String NEWLINE = "\n";
private final static String TWO_SPACES = " ";
private static Map<Integer, Character> intToChar;
private static Map<Integer, Integer> intRowConversion;
public TextView()
{
buildIntToCharMap();
buildIntConversionMap();
}
/**
* Build map to convert column to a given character.
*/
void buildIntToCharMap()
{
intToChar = new HashMap<>();
intToChar.put(0, 'a');
intToChar.put(1, 'b');
intToChar.put(2, 'c');
intToChar.put(3, 'd');
intToChar.put(4, 'e');
intToChar.put(5, 'f');
intToChar.put(6, 'g');
intToChar.put(7, 'h');
}
/**
* Build map to convert a row number.
*/
void buildIntConversionMap()
{
intRowConversion = new HashMap<>();
intRowConversion.put(0, 8);
intRowConversion.put(1, 7);
intRowConversion.put(2, 6);
intRowConversion.put(3, 5);
intRowConversion.put(4, 4);
intRowConversion.put(5, 3);
intRowConversion.put(6, 2);
intRowConversion.put(7, 1);
}
/**
* Updates the console to display info from the current model.
*/
@Override
public void update(Observable o, Object arg)
{
Model model = (Model) o;
Board board = model.getBoard();
if (model.getValidMoves() != null)
{
showValidMoves(model.getValidMoves());
} else if (model.getExceptionThrown() != null)
{
System.out.println(model.getExceptionThrown().getMessage());
} else
{
drawHeader(model);
drawBoard(board);
}
}
/**
* Displays valid moves of a given piece.
*
* @param validPositions Positions on the board the piece can move to.
*
*/
void showValidMoves(List<Position> validPositions)
{
StringBuilder validMsg = new StringBuilder();
validMsg.append("Valid Moves: ");
for (Position currValidPosition : validPositions)
{
validMsg.append(intToChar.get(currValidPosition.getColumn()));
validMsg.append(intRowConversion.get(currValidPosition.getRow()));
validMsg.append(TWO_SPACES);
}
System.out.println(validMsg);
}
/**
* Displays high level game info.
*
* @param model
*/
void drawHeader(Model model)
{
StringBuilder header = new StringBuilder();
header.append("UPPERCASE: WHITE | lowercase: black");
header.append(NEWLINE);
header.append(model.getWhosTurn() + "'S Turn ");
header.append(NEWLINE);
header.append("Turn Number: " + model.getTurnCount());
header.append(NEWLINE);
System.out.println(header);
}
/**
* Iterates through board object printing to the console the correct
* abbreviation for a given piece and the outer frame of the board.
*
* @param board Current board state.
*/
void drawBoard(Board board)
{
String columnLabels = " a b c d e f g h ";
String horizontalBar = "+
StringBuilder boardString = new StringBuilder();
boardString.append(columnLabels);
boardString.append(NEWLINE);
boardString.append(TWO_SPACES);
boardString.append(horizontalBar);
boardString.append(NEWLINE);
for (int row = 0; row < Board.GRID_SIZE; row++)
{
int rowLabel = Board.GRID_SIZE - row;
for (int col = 0; col < Board.GRID_SIZE; col++)
{
Position currentPosition = null;
try
{
currentPosition = new Position(row, col);
} catch (InvalidPositionException ex)
{
logger.error(ex.getMessage());
System.exit(1);
}
Piece currentPiece = board.gridLookup(currentPosition);
String abbreviation = getAbbreviation(currentPiece);
if (col == 0)
{
boardString.append(rowLabel);
boardString.append(" | ");
boardString.append(abbreviation);
} else if (col == 7)
{
boardString.append(" | ");
boardString.append(abbreviation);
boardString.append(" | ");
boardString.append(NEWLINE);
} else
{
boardString.append(" | ");
boardString.append(abbreviation);
}
}
boardString.append(TWO_SPACES);
boardString.append(horizontalBar);
boardString.append(NEWLINE);
}
boardString.append(NEWLINE);
System.out.print(boardString);
}
String getAbbreviation(Piece piece)
{
PieceType pieceType = piece.getType();
String pieceAbr = "";
switch (pieceType)
{
case BISHOP:
pieceAbr = "BI";
break;
case KING:
pieceAbr = "KI";
break;
case KNIGHT:
pieceAbr = "KN";
break;
case PAWN:
pieceAbr = "PA";
break;
case QUEEN:
pieceAbr = "QU";
break;
case ROOK:
pieceAbr = "RO";
break;
case NO_PIECE:
pieceAbr = " ";
break;
default:
String msg = "Piece type isn't accounted for.";
logger.error(msg);
}
if (piece.getColor() == PieceColor.BLACK)
{
return pieceAbr.toLowerCase();
}
return pieceAbr;
}
}
|
package org.eclipse.birt.report.designer.data.ui.dataset;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.data.ui.property.AbstractDescriptionPropertyPage;
import org.eclipse.birt.report.designer.data.ui.util.ControlProvider;
import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider;
import org.eclipse.birt.report.designer.data.ui.util.DummyEngineTask;
import org.eclipse.birt.report.designer.data.ui.util.Utility;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ResourceEditDialog;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.impl.ReportEngine;
import org.eclipse.birt.report.engine.api.impl.ReportEngineFactory;
import org.eclipse.birt.report.engine.api.impl.ReportEngineHelper;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.activity.NotificationEvent;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.core.Listener;
import org.eclipse.birt.report.model.api.elements.structures.ColumnHint;
import org.eclipse.birt.report.model.core.Structure;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
/**
* Property page to edit output columns for all oda data sets.
*/
public class OutputColumnsPage extends AbstractDescriptionPropertyPage
implements
Listener
{
protected transient PropertyHandleTableViewer viewer = null;
// to indicate the status of dataset handle
private transient boolean modelChanged = true;
protected String originalAlias = ""; //$NON-NLS-1$
protected String originalDisplayName = ""; //$NON-NLS-1$
protected String originalDisplayNameKey = ""; //$NON-NLS-1$
protected static String[] cellLabels = new String[]{
Messages.getString( "dataset.editor.title.name" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.title.type" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.title.alias" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.title.displayName" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.title.displayNameKey" ) //$NON-NLS-1$
};
protected static String[] dialogLabels = new String[]{
Messages.getString( "dataset.editor.inputDialog.name" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.type" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.alias" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.displayName" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.displayNameKey" ) //$NON-NLS-1$
};
protected static String[] cellProperties = new String[]{
"name", "dataTypeDisplayName", "alias", "realDisplayName", "displayNameKey"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
};
/**
* The constructor.
*/
public OutputColumnsPage( )
{
super( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.IPropertyPage#createPageControl(org.eclipse.swt.widgets.Composite)
*/
public Control createContents( Composite parent )
{
createTableViewer( parent );
addListeners( );
( (DataSetHandle) getContainer( ).getModel( ) ).addListener( this );
return viewer.getControl( );
}
protected void createTableViewer( Composite parent )
{
viewer = new PropertyHandleTableViewer( parent, false, true, false );
TableColumn column = new TableColumn( viewer.getViewer( ).getTable( ),
SWT.LEFT );
column.setText( cellLabels[0] ); //$NON-NLS-1$
column.setWidth( 100 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[1] ); //$NON-NLS-1$
column.setWidth( 100 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[2] ); //$NON-NLS-1$
column.setWidth( 100 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[3] ); //$NON-NLS-1$
column.setWidth( 100 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[4] ); //$NON-NLS-1$
column.setWidth( 150 );
// TODO Add support to helpText after release 1
// column = new TableColumn( outputColumnsViewer.getViewer( ).getTable(
// ), SWT.LEFT );
// column.setText( Messages.getString( "dataset.editor.title.helpText" )
// ); //$NON-NLS-1$
// column.setWidth( 100 );
viewer.getViewer( )
.setContentProvider( new OutputColumnsContentProvider( ) );
viewer.getViewer( )
.setLabelProvider( new OutputColumnsLabelProvider( ) );
}
private void addListeners( )
{
viewer.getNewButton( ).addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
doEdit( );
}
} );
viewer.getViewer( ).getTable( ).addMouseListener( new MouseAdapter( ) {
public void mouseDoubleClick( MouseEvent e )
{
doEdit( );
}
} );
}
private void doEdit( )
{
int index = viewer.getViewer( ).getTable( ).getSelectionIndex( );
if ( index == -1 )
return;
DataSetViewData data = (DataSetViewData) viewer.getViewer( )
.getTable( )
.getItem( index )
.getData( );
originalAlias = data.getAlias( );
originalDisplayName = data.getRealDisplayName( );
originalDisplayNameKey = data.getDisplayNameKey( );
doEdit( data );
}
protected void doEdit( DataSetViewData data )
{
OutputColumnInputDialog dlg = new OutputColumnInputDialog( data );
if ( dlg.open( ) == Window.OK )
{
viewer.getViewer( ).update( data, null );
updateMessage( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.IPropertyPage#pageActivated()
*/
public void pageActivated( )
{
if ( modelChanged )
{
updateOutputColumns( );
modelChanged = false;
}
setPageProperties( );
getContainer( ).setMessage( Messages.getString( "dataset.editor.outputColumns" ), //$NON-NLS-1$
IMessageProvider.NONE );
viewer.getViewer( ).getTable( ).select( 0 );
}
private void setPageProperties( )
{
viewer.getNewButton( )
.setEnabled( viewer.getViewer( ).getInput( ) != null
&& ( (DataSetViewData[]) viewer.getViewer( ).getInput( ) ).length != 0 );
viewer.getNewButton( )
.setText( Messages.getString( "PropertyHandleTableViewer.Button.Edit" ) );//$NON-NLS-1$
viewer.getNewButton( )
.setToolTipText( Messages.getString( "OutputColumnPage.toolTipText.Edit" ) );//$NON-NLS-1$
viewer.getEditButton( ).setVisible( false );
viewer.getRemoveButton( ).setVisible( false );
viewer.getUpButton( ).setVisible( false );
viewer.getDownButton( ).setVisible( false );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#canLeave()
*/
public boolean canLeave( )
{
if ( isValid( ) )
{
saveOutputColumns( );
if( this.modelChanged )
{
( (DataSetEditor) this.getContainer( ) ).updateDataSetDesign( this );
this.modelChanged = false;
}
return super.canLeave( );
}
else
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performOk()
*/
public boolean performOk( )
{
if ( isValid( ) )
{
saveOutputColumns( );
( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this );
if( this.modelChanged )
{
( (DataSetEditor) this.getContainer( ) ).updateDataSetDesign( this );
this.modelChanged = false;
}
return super.performOk( );
}
else
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractDescriptionPropertyPage#getPageDescription()
*/
public String getPageDescription( )
{
return Messages.getString( "OutputColumnsPage.description" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#getToolTip()
*/
public String getToolTip( )
{
return Messages.getString( "OutputColumnPage.OutputColumns.Tooltip" ); //$NON-NLS-1$
}
/**
* update output columns page
*
*/
protected final void updateOutputColumns( )
{
clearOutputColumns( );
try
{
populateOutputColums( );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
/**
* populate output columns
*
* @throws BirtException
*/
private void populateOutputColums( ) throws BirtException
{
ClassLoader oldContextLoader = Thread.currentThread( )
.getContextClassLoader( );
ClassLoader parentLoader = oldContextLoader;
if ( parentLoader == null )
parentLoader = this.getClass( ).getClassLoader( );
ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader,
( (DataSetEditor) getContainer( ) ).getHandle( )
.getModuleHandle( ) );
ModuleHandle handle = ( (DataSetEditor) getContainer( ) ).getHandle( )
.getModuleHandle( );
DataSessionContext context;
if ( handle instanceof ReportDesignHandle )
{
Map dataSetMap = new HashMap( );
Map dataSourceMap = new HashMap( );
try
{
EngineConfig ec = new EngineConfig( );
ec.getAppContext( )
.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
newContextLoader );
ReportEngine engine = (ReportEngine) new ReportEngineFactory( ).createReportEngine( ec );
DataSetUIUtil.clearPropertyBindingMap( ( (DataSetEditor) getContainer( ) ).getHandle( ),
dataSetMap,
dataSourceMap );
DummyEngineTask engineTask = new DummyEngineTask( engine,
new ReportEngineHelper( engine ).openReportDesign( (ReportDesignHandle) handle ),
handle );
DataRequestSession session = engineTask.getDataSession( );
engineTask.run( );
DataSetViewData[] viewDatas = DataSetProvider.getCurrentInstance( )
.populateAllOutputColumns( ( (DataSetEditor) getContainer( ) ).getHandle( ),
session );
if ( viewDatas == null )
{
viewDatas = ( (DataSetEditor) getContainer( ) ).getCurrentItemModel( false,
false );
}
if ( ( (DataSetEditor) getContainer( ) ).getHandle( ) instanceof JointDataSetHandle )
{
PropertyHandle properyHandle = ( (DataSetEditor) getContainer( ) ).getHandle( )
.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP );
if ( properyHandle != null )
{
for ( int i = 0; i < viewDatas.length; i++ )
{
for ( Iterator columns = properyHandle.iterator( ); columns.hasNext( ); )
{
ColumnHintHandle column = (ColumnHintHandle) columns.next( );
if ( viewDatas[i].getName( )
.equals( column.getColumnName( ) ) )
{
viewDatas[i].setAlias( column.getAlias( ) );
break;
}
}
}
}
}
viewer.getViewer( ).setInput( viewDatas );
engineTask.close( );
engine.destroy( );
}
finally
{
DataSetUIUtil.resetPropertyBinding( ( (DataSetEditor) getContainer( ) ).getHandle( ),
dataSetMap,
dataSourceMap );
}
}
else
{
context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
( (DataSetEditor) getContainer( ) ).getHandle( )
.getModuleHandle( ) );
DataRequestSession session = DataRequestSession.newSession( context );
DataSetViewData[] viewDatas = DataSetProvider.getCurrentInstance( )
.populateAllOutputColumns( ( (DataSetEditor) getContainer( ) ).getHandle( ),
session );
if ( viewDatas == null )
{
viewDatas = ( (DataSetEditor) getContainer( ) ).getCurrentItemModel( false,
false );
}
viewer.getViewer( ).setInput( viewDatas );
session.shutdown( );
}
Thread.currentThread( ).setContextClassLoader( oldContextLoader );
}
/**
* clear output columns table viewer
*
*/
protected final void clearOutputColumns( )
{
viewer.getViewer( ).getTable( ).removeAll( );
}
protected void saveOutputColumns( )
{
PropertyHandle handle = ( (DataSetHandle) getContainer( ).getModel( ) ).getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP );
if ( viewer != null
&& viewer.getViewer( ) != null
&& viewer.getViewer( ).getInput( ) != null )
{
// Iterate through all the cached model items
DataSetViewData[] items = (DataSetViewData[]) viewer.getViewer( )
.getInput( );
String columnName = null;
boolean found = false;
for ( int n = 0; n < items.length; n++ )
{
columnName = items[n].getName( );
// Find this column name in the handle
found = false;
Iterator iter = handle.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) && !found )
{
ColumnHintHandle hint = (ColumnHintHandle) iter.next( );
if ( hint.getColumnName( ).equals( columnName ) )
{
found = true;
// Update the display name
if ( items[n].getRealDisplayName( ) == null
|| items[n].getRealDisplayName( )
.trim( )
.length( ) == 0 )
{
hint.setDisplayName( null );
}
else
{
hint.setDisplayName( items[n].getRealDisplayName( ) );
}
if ( items[n].getDisplayNameKey( ) == null
|| items[n].getDisplayNameKey( )
.trim( )
.length( ) == 0 )
{
hint.setDisplayNameKey( null );
}
else
{
hint.setDisplayNameKey( items[n].getDisplayNameKey( ) );
}
if ( items[n].getAlias( ) == null
|| items[n].getAlias( ).trim( ).length( ) == 0 )
{
hint.setAlias( null );
}
else
{
hint.setAlias( items[n].getAlias( ) );
}
if ( items[n].getHelpText( ) == null
|| items[n].getHelpText( ).trim( ).length( ) == 0 )
{
hint.setHelpText( null );
}
else
{
hint.setHelpText( items[n].getHelpText( ) );
}
}
}
}
// If not found then create a new item and add it in
if ( !found && isColumnHintRequired( items[n] ) )
{
ColumnHint hint = new ColumnHint( );
hint.setProperty( ColumnHint.COLUMN_NAME_MEMBER, columnName );
if ( items[n].getRealDisplayName( ) != null
&& items[n].getRealDisplayName( ).trim( ).length( ) > 0 )
{
hint.setProperty( ColumnHint.DISPLAY_NAME_MEMBER,
items[n].getRealDisplayName( ) );
}
if ( items[n].getDisplayNameKey( ) != null
&& items[n].getDisplayNameKey( ).trim( ).length( ) > 0 )
{
hint.setProperty( ColumnHint.DISPLAY_NAME_ID_MEMBER,
items[n].getDisplayNameKey( ) );
}
if ( items[n].getAlias( ) != null
&& items[n].getAlias( ).trim( ).length( ) > 0 )
{
hint.setProperty( ColumnHint.ALIAS_MEMBER,
items[n].getAlias( ) );
}
if ( items[n].getHelpText( ) != null
&& items[n].getHelpText( ).trim( ).length( ) > 0 )
{
hint.setProperty( ColumnHint.HELP_TEXT_MEMBER,
items[n].getHelpText( ) );
}
try
{
handle.addItem( hint );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
}
}
/**
* The alias name is unique or not
*
* @param newValue
* @return
*/
protected boolean isUnique( String newValue )
{
DataSetViewData[] items = null;
if ( viewer == null || viewer.getViewer( ) == null )
{
items = DataSetProvider.getCurrentInstance( )
.getColumns( ( (DataSetEditor) getContainer( ) ).getHandle( ),
false,
true,
true );
}
else
{
items = (DataSetViewData[]) viewer.getViewer( ).getInput( );
}
for ( int i = 0; i < items.length; i++ )
{
if ( ( items[i].getAlias( ) != null && items[i].getAlias( )
.equals( newValue ) )
|| ( items[i].getName( ) != null && items[i].getName( )
.equals( newValue ) ) )
{
return false;
}
}
return true;
}
/**
* validates that the new name/alias from a column hint or a new custom
* column doesn't conflict with existing column names or aliases
*
*/
private boolean isValid( )
{
boolean validate = true;
String newColumnNameOrAlias;
DataSetViewData[] items = null;
if ( viewer == null || viewer.getViewer( ) == null )
{
items = DataSetProvider.getCurrentInstance( )
.getColumns( ( (DataSetEditor) getContainer( ) ).getHandle( ),
false,
true,
true );
}
else
{
items = (DataSetViewData[]) viewer.getViewer( ).getInput( );
}
for ( int i = 0; items != null && i < items.length && validate; i++ )
{
newColumnNameOrAlias = items[i].getAlias( );
if ( newColumnNameOrAlias != null
&& newColumnNameOrAlias.length( ) > 0 )
{
for ( int n = 0; n < items.length; n++ )
{
if ( i == n )
continue;
if ( ( items[n].getName( ) != null && items[n].getName( )
.equals( newColumnNameOrAlias ) )
|| ( items[n].getAlias( ) != null && items[n].getAlias( )
.equals( newColumnNameOrAlias ) ) )
{
validate = false;
getContainer( ).setMessage( Messages.getFormattedString( "dataset.editor.error.columnOrAliasNameAlreadyUsed", //$NON-NLS-1$
new Object[]{
newColumnNameOrAlias,
new Integer( n + 1 )
} ),
IMessageProvider.ERROR );
break;
}
}
}
}
return validate;
}
/**
* update message
*
*/
protected void updateMessage( )
{
if ( isValid( ) )
getContainer( ).setMessage( Messages.getString( "dataset.editor.outputColumns" ), //$NON-NLS-1$
IMessageProvider.NONE );
}
/**
*
* @param model
* @return
*/
protected boolean isColumnHintRequired( DataSetViewData model )
{
return !( ( model.getRealDisplayName( ) == null || model.getRealDisplayName( )
.trim( )
.length( ) == 0 )
&& ( model.getDisplayNameKey( ) == null || model.getDisplayNameKey( )
.trim( )
.length( ) == 0 )
&& ( model.getAlias( ) == null || model.getAlias( )
.trim( )
.length( ) == 0 ) && ( model.getHelpText( ) == null || model.getHelpText( )
.trim( )
.length( ) == 0 ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.model.core.Listener#elementChanged(org.eclipse.birt.model.api.DesignElementHandle,
* org.eclipse.birt.model.activity.NotificationEvent)
*/
public void elementChanged( DesignElementHandle focus, NotificationEvent ev )
{
if ( focus.equals( getContainer( ).getModel( ) ) )
{
modelChanged = true;
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performCancel()
*/
public boolean performCancel( )
{
if ( viewer != null
&& viewer.getViewer( ) != null
&& viewer.getViewer( ).getInput( ) != null )
{
// Update the cached list from the model
// We have to do this because we are directly updating the column
// names in the cached list
DataSetProvider manager = DataSetProvider.getCurrentInstance( );
manager.updateModel( ( (DataSetEditor) getContainer( ) ).getHandle( ),
(DataSetViewData[]) viewer.getViewer( ).getInput( ) );
}
( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this );
return super.performCancel( );
}
private class OutputColumnInputDialog extends PropertyHandleInputDialog
{
DataSetViewData data = null;
protected OutputColumnInputDialog( Object structureOrHandle )
{
super( structureOrHandle );
data = (DataSetViewData) structureOrHandle;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#createCustomControls(org.eclipse.swt.widgets.Composite)
*/
protected void createCustomControls( Composite parent )
{
try
{
createCells( parent );
}
catch ( Exception e )
{
ExceptionHandler.handle( e );
}
}
private void createCells( Composite parent )
throws IllegalArgumentException, IntrospectionException,
IllegalAccessException, InvocationTargetException
{
for ( int i = 0; i < cellProperties.length; i++ )
{
ControlProvider.createLabel( parent, dialogLabels[i] );
if ( i == 4 )
{
createResourceCell( parent, i );
continue;
}
createTextCell( parent, i );
}
}
private void createTextCell( Composite parent, final int index )
throws IllegalArgumentException, IntrospectionException,
IllegalAccessException, InvocationTargetException
{
final Text tx = ControlProvider.createText( parent,
(String) Utility.getProperty( data, cellProperties[index] ) );
tx.setLayoutData( ControlProvider.getGridDataWithHSpan( 2 ) );
if ( index < 2 )// disable name and dataTypeName
{
tx.setEditable( false );
}
else
{
tx.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
try
{
if ( index == 2 )
{
boolean isUniqueName = isUnique( tx.getText( ) );
if ( !isUniqueName )
updateStatus( getMiscStatus( IStatus.ERROR,
Messages.getString( "OutputColumnPage.OutputColumns.DuplicatedName" ) ) ); //$NON-NLS-1$
else
updateStatus( getOKStatus( ) );
}
Object txText = tx.getText( );
if ( tx.getText( ).trim( ).length( ) == 0 )
txText = null;
Utility.setProperty( data,
cellProperties[index],
txText );
}
catch ( Exception e1 )
{
ExceptionHandler.handle( e1 );
}
}
} );
}
if ( index == 2 )
{
tx.setFocus( );
}
}
private void createResourceCell( Composite parent, final int index )
throws IllegalArgumentException, IntrospectionException,
IllegalAccessException, InvocationTargetException
{
final Text tx = ControlProvider.createText( parent,
(String) Utility.getProperty( data, cellProperties[index] ) );
tx.setLayoutData( ControlProvider.getGridDataWithHSpan( 1 ) );
tx.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
try
{
Utility.setProperty( data,
cellProperties[index],
tx.getText( ) );
}
catch ( Exception e1 )
{
ExceptionHandler.handle( e1 );
}
}
} );
SelectionAdapter listener = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
ResourceEditDialog dlg = new ResourceEditDialog( getShell( ),
Messages.getString( "ResourceKeyDescriptor.title.SelectKey" ) ); //$NON-NLS-1$
dlg.setResourceURL( getResourceURL( ) );
if ( dlg.open( ) == Window.OK )
{
tx.setText( (String) dlg.getResult( ) );
}
}
};
Button bt = new Button( parent, SWT.PUSH );
bt.setText( "..." ); //$NON-NLS-1$
bt.addSelectionListener( listener );
if ( getBaseName( ) == null )
bt.setEnabled( false );
}
private URL getResourceURL( )
{
return SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.findResource( getBaseName( ),
IResourceLocator.MESSAGE_FILE );
}
private String getBaseName( )
{
return SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.getIncludeResource( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#rollback()
*/
protected void rollback( )
{
data.setAlias( originalAlias );
data.setRealDisplayName( originalDisplayName );
data.setDisplayNameKey( originalDisplayNameKey );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#validateSemantics(java.lang.Object)
*/
protected IStatus validateSemantics( Object structureOrHandle )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#validateSyntax(java.lang.Object)
*/
protected IStatus validateSyntax( Object structureOrHandle )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#getTitle()
*/
protected String getTitle( )
{
if ( (Object) data instanceof Structure )
{
return Messages.getString( "OutputColumnPage.title.OutputColumnInputDialog.NewOutputColumn" ); //$NON-NLS-1$
}
return Messages.getString( "OutputColumnPage.title.OutputColumnInputDialog.EditOutputColumn" );//$NON-NLS-1$
}
}
}
class OutputColumnsContentProvider implements IStructuredContentProvider
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements( Object inputElement )
{
return (DataSetViewData[]) inputElement;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose( )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged( Viewer viewer, Object oldInput, Object newInput )
{
}
}
class OutputColumnsLabelProvider implements ITableLabelProvider
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object,
* int)
*/
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object,
* int)
*/
public String getColumnText( Object element, int columnIndex )
{
String value = null;
DataSetViewData item = (DataSetViewData) element;
switch ( columnIndex )
{
case 0 :
{
value = item.getName( );
break;
}
case 1 :
{
value = DataSetViewData.getDataTypeDisplayName( item.getDataTypeName( ) );
break;
}
case 2 :
{
value = item.getAlias( );
break;
}
case 3 :
{
value = item.getRealDisplayName( );
break;
}
case 4 :
{
value = item.getDisplayNameKey( );
break;
}
}
return ( ( value == null ) ? "" : value );//$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
public void addListener( ILabelProviderListener listener )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
*/
public void dispose( )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object,
* java.lang.String)
*/
public boolean isLabelProperty( Object element, String property )
{
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
public void removeListener( ILabelProviderListener listener )
{
}
}
|
package dr.app.bss;
import java.io.Serializable;
import dr.app.beagle.evomodel.branchmodel.BranchModel;
import dr.app.beagle.evomodel.branchmodel.HomogeneousBranchModel;
import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel;
import dr.app.beagle.evomodel.substmodel.EmpiricalAminoAcidModel;
import dr.app.beagle.evomodel.substmodel.FrequencyModel;
import dr.app.beagle.evomodel.substmodel.GTR;
import dr.app.beagle.evomodel.substmodel.GY94CodonModel;
import dr.app.beagle.evomodel.substmodel.HKY;
import dr.app.beagle.evomodel.substmodel.TN93;
import dr.evolution.coalescent.CoalescentSimulator;
import dr.evolution.coalescent.ConstantPopulation;
import dr.evolution.coalescent.DemographicFunction;
import dr.evolution.coalescent.ExponentialGrowth;
import dr.evolution.datatype.AminoAcids;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Taxa;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DiscretizedBranchRates;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.sitemodel.SiteModel;
import dr.evomodel.substmodel.Blosum62;
import dr.evomodel.substmodel.EmpiricalRateMatrix;
import dr.evomodel.tree.TreeModel;
import dr.evoxml.TaxaParser;
import dr.inference.distribution.ExponentialDistributionModel;
import dr.inference.distribution.InverseGaussianDistributionModel;
import dr.inference.distribution.LogNormalDistributionModel;
import dr.inference.distribution.ParametricDistributionModel;
import dr.inference.model.Parameter;
import dr.inferencexml.distribution.DistributionModelParser;
import dr.inferencexml.distribution.InverseGaussianDistributionModelParser;
import dr.inferencexml.distribution.LogNormalDistributionModelParser;
/**
* @author Filip Bielejec
* @version $Id$
*/
@SuppressWarnings("serial")
public class PartitionData implements Serializable {
public PartitionData() {
}// END: Constructor
public int from = 1;
public int to = 1000;
public int every = 1;
public int createPartitionSiteCount() {
return ((to - from) / every) + 1;
}
public void resetIdrefs() {
resetClockModelIdref();
resetFrequencyModelIdref();
resetSiteRateModelIdref();
resetSubstitutionModelIdref();
resetTreeModelIdref();
resetDemographicModelIdref();
resetTaxaIdref();
}
public int demographicModelIndex = 0;
public String demographicModelIdref = Utils.DEMOGRAPHIC_MODEL;
public void resetDemographicModelIdref() {
this.demographicModelIdref = Utils.DEMOGRAPHIC_MODEL;
}
public static String[] demographicModels = {
"No Model (user-specified tree)",
"Constant Population",
"Exponential Growth (Growth Rate)",
"Exponential Growth (Doubling Time)"
// "Logistic Growth (Growth Rate)",
// "Logistic Growth (Doubling Time)",
// "Expansion (Growth Rate)",
// "Expansion (Doubling Time)",
};
public static String[] demographicParameterNames = new String[] {
"Population Size", // Constant Population
"Population Size", // Exponential Growth (Growth Rate)
"Growth Rate", // Exponential Growth (Growth Rate)
"Population Size", // Exponential Growth (Doubling Time)
"Doubling Time" // Exponential Growth (Doubling Time)
// "Population Size", // Logistic Growth (Growth Rate)
// "Growth Rate", // Logistic Growth (Growth Rate)
// "Logistic Shape (Half-life)", // Logistic Growth (Growth Rate)
// "Population Size", // Logistic Growth (Doubling Time)
// "Doubling Time", // Logistic Growth (Doubling Time)
// "Logistic Shape (Half-life)", // Logistic Growth (Doubling Time)
// "Population Size", // Expansion (Growth Rate)
// "Ancestral Proportion", // Expansion (Growth Rate)
// "Growth Rate", // Expansion (Growth Rate)
// "Population Size", // Expansion (Doubling Time)
// "Ancestral Proportion", // Expansion (Doubling Time)
// "Doubling Time", // Expansion (Doubling Time)
};
public static int[][] demographicParameterIndices = {
{ }, // No model
{ 0 }, // Constant Population
{ 1, 2 }, // Exponential Growth (Growth Rate)
{ 3, 4 }// Exponential Growth (Doubling Time)
// { 5, 6, 7 }, // Logistic Growth (Growth Rate)
// { 8, 9, 10 }, // Logistic Growth (Doubling Time)
// { 11, 12, 13 }, // Expansion (Growth Rate)
// { 14, 15, 16 } // Expansion (Doubling Time)
};
public double[] demographicParameterValues = new double[] {
/*Constant Population*/
1000.0, // Population Size
/*Exponential Growth (Growth Rate)*/
1000.0, // Population Size
0.5, // Growth Rate
/*Exponential Growth (Doubling Time)*/
1000.0, // Population Size
10.0 // Doubling Time
// 1000.0, // Population Size
// 0.5, // Growth Rate
// 50.0, // Logistic Shape (Half-life)
// 1000.0, // Population Size
// 10.0, // Doubling Time
// 50.0, // Logistic Shape (Half-life)
// 1000.0, // Population Size
// 0.1, // Ancestral Proportion
// 0.5, // Growth Rate
// 1000.0, // Population Size
// 0.1, // Ancestral Proportion
// 10.0 // Doubling Time
};
public DemographicFunction createDemographicFunction() {
DemographicFunction demographicFunction = null;
if (this.demographicModelIndex == 0) { // No model
// do nothing
} else if (this.demographicModelIndex == 1) {// Constant Population
demographicFunction = new ConstantPopulation(Units.Type.YEARS);
((ConstantPopulation)demographicFunction).setN0(demographicParameterValues[0]);
} else if (this.demographicModelIndex == 2) {// Exponential Growth (Growth Rate)
demographicFunction = new ExponentialGrowth(Units.Type.YEARS);
((ExponentialGrowth) demographicFunction).setN0(demographicParameterValues[1]);
((ExponentialGrowth) demographicFunction).setGrowthRate(demographicParameterValues[2]);
} else if (this.demographicModelIndex == 3) {// Exponential Growth (Doubling Time)
demographicFunction = new ExponentialGrowth(Units.Type.YEARS);
((ExponentialGrowth) demographicFunction).setN0(demographicParameterValues[3]);
((ExponentialGrowth) demographicFunction).setDoublingTime(demographicParameterValues[4]);
// } else if (this.demographicModelIndex == 4) {// Logistic Growth (Growth Rate)
// demographicFunction = new LogisticGrowth(Units.Type.YEARS);
// ((LogisticGrowth) demographicFunction).setN0(demographicParameterValues[5]);
// ((LogisticGrowth) demographicFunction).setGrowthRate(demographicParameterValues[6]);
// ((LogisticGrowth) demographicFunction).setTime50(demographicParameterValues[7]);
// } else if (this.demographicModelIndex == 5) {// Logistic Growth (Doubling Time)
// demographicFunction = new LogisticGrowth(Units.Type.YEARS);
// ((LogisticGrowth) demographicFunction).setN0(demographicParameterValues[8]);
// ((LogisticGrowth) demographicFunction).setDoublingTime(demographicParameterValues[9]);
// ((LogisticGrowth) demographicFunction).setTime50(demographicParameterValues[10]);
// } else if (this.demographicModelIndex == 6) {// Expansion (Growth Rate)
// demographicFunction = new Expansion(Units.Type.YEARS);
// ((Expansion) demographicFunction).setN0(demographicParameterValues[11]);
// ((Expansion) demographicFunction).setProportion(demographicParameterValues[12]);
// ((Expansion) demographicFunction).setGrowthRate(demographicParameterValues[13]);
// } else if (this.demographicModelIndex == 7) {// Expansion (Doubling Time)
// demographicFunction = new Expansion(Units.Type.YEARS);
// ((Expansion) demographicFunction).setN0(demographicParameterValues[14]);
// ((Expansion) demographicFunction).setProportion(demographicParameterValues[15]);
// ((Expansion) demographicFunction).setDoublingTime(demographicParameterValues[16]);
} else {
System.out.println("Not yet implemented");
}
return demographicFunction;
}// END: createDemographicFunction
public TreesTableRecord record = null;
// public Taxa taxa = null;
public String taxaIdref = TaxaParser.TAXA;
public void resetTaxaIdref() {
this.taxaIdref = TaxaParser.TAXA;
}
// public Tree tree = null;
public String treeModelIdref = TreeModel.TREE_MODEL;
public void resetTreeModelIdref() {
this.treeModelIdref = TreeModel.TREE_MODEL;
}
public TreeModel createTreeModel() {
TreeModel treeModel = null;
if (this.demographicModelIndex == 0 && this.record.isTreeSet()) {
treeModel = new TreeModel(this.record.getTree());
} else if( (this.demographicModelIndex > 0 && this.demographicModelIndex <= 3) && this.record.isTreeSet()) {
Taxa taxa = new Taxa(this.record.getTree().asList());
CoalescentSimulator topologySimulator = new CoalescentSimulator();
treeModel = new TreeModel(topologySimulator.simulateTree(taxa, createDemographicFunction()));
} else if((this.demographicModelIndex > 0 && this.demographicModelIndex <= 3) && this.record.isTaxaSet()) {
Taxa taxa = this.record.getTaxa();
CoalescentSimulator topologySimulator = new CoalescentSimulator();
treeModel = new TreeModel(topologySimulator.simulateTree(taxa, createDemographicFunction()));
// } else if (this.demographicModelIndex == 0 && this.record.taxaSet) {
// throw new RuntimeException("Data and demographic model incompatible for partition ");
} else {
throw new RuntimeException("Data and demographic model incompatible.");
}// END: demo model check
return treeModel;
}//END: createTreeModel
// public int dataTypeIndex = 0;
// public static String[] dataTypes = { "Nucleotide", //
// "Codon" //
// public DataType createDataType() {
// DataType dataType = null;
// if (this.dataTypeIndex == 0) { // Nucleotide
// dataType = Nucleotides.INSTANCE;
// } else if (this.dataTypeIndex == 1) { // Codon
// dataType = Codons.UNIVERSAL;
// } else {
// System.out.println("Not yet implemented");
// return dataType;
// }// END: createDataType
//TODO: amino acid models
public int substitutionModelIndex = 0;
public String substitutionModelIdref = Utils.SUBSTITUTION_MODEL;
public void resetSubstitutionModelIdref() {
this.substitutionModelIdref = Utils.SUBSTITUTION_MODEL;
}
public static String[] substitutionModels = { "HKY",
"GTR",
"TN93",
"GY94CodonModel",
"Blosum62"
};
public static String[] substitutionParameterNames = new String[] {
"Kappa value", // HKY
"AC", // GTR
"AG", // GTR
"AT", // GTR
"CG", // GTR
"CT", // GTR
"GT", // GTR
"Kappa 1 (A-G)", // TN93
"Kappa 2 (C-T)", // TN93
"Omega value", // Yang Codon Model
"Kappa value" // Yang Codon Model
};
public static int[][] substitutionParameterIndices = { { 0 }, // HKY
{ 1, 2, 3, 4, 5, 6 }, // GTR
{ 7, 8 }, // TN93
{ 9, 10 }, // Yang Codon Model
{} // Blosum62
};
public double[] substitutionParameterValues = new double[] { 1.0, // Kappa-value
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0, // Kappa 1
1.0, // Kappa 2
0.1, // Omega value
1.0 // Kappa value
};
public BranchModel createBranchModel() {
BranchModel branchModel = null;
if (this.substitutionModelIndex == 0) { // HKY
Parameter kappa = new Parameter.Default(1, substitutionParameterValues[0]);
FrequencyModel frequencyModel = this.createFrequencyModel();
HKY hky = new HKY(kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(hky);
} else if (this.substitutionModelIndex == 1) { // GTR
Parameter ac = new Parameter.Default(1,
substitutionParameterValues[1]);
Parameter ag = new Parameter.Default(1,
substitutionParameterValues[2]);
Parameter at = new Parameter.Default(1,
substitutionParameterValues[3]);
Parameter cg = new Parameter.Default(1,
substitutionParameterValues[4]);
Parameter ct = new Parameter.Default(1,
substitutionParameterValues[5]);
Parameter gt = new Parameter.Default(1,
substitutionParameterValues[6]);
FrequencyModel frequencyModel = this.createFrequencyModel();
GTR gtr = new GTR(ac, ag, at, cg, ct, gt, frequencyModel);
branchModel = new HomogeneousBranchModel(gtr);
} else if (this.substitutionModelIndex == 2) { // TN93
Parameter kappa1 = new Parameter.Default(1,
substitutionParameterValues[7]);
Parameter kappa2 = new Parameter.Default(1,
substitutionParameterValues[8]);
FrequencyModel frequencyModel = this.createFrequencyModel();
TN93 tn93 = new TN93(kappa1, kappa2, frequencyModel);
branchModel = new HomogeneousBranchModel(tn93);
} else if (this.substitutionModelIndex == 3) { // Yang Codon Model
FrequencyModel frequencyModel = this.createFrequencyModel();
Parameter kappa = new Parameter.Default(1,
substitutionParameterValues[9]);
Parameter omega = new Parameter.Default(1,
substitutionParameterValues[10]);
GY94CodonModel yangCodonModel = new GY94CodonModel(
Codons.UNIVERSAL, omega, kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(yangCodonModel);
} else if (this.substitutionModelIndex == 4) { // Blosum62
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = Blosum62.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else {
System.out.println("Not yet implemented");
}
return branchModel;
}// END: createBranchSubstitutionModel
public int clockModelIndex = 0;
public String clockModelIdref = BranchRateModel.BRANCH_RATES;
public void resetClockModelIdref() {
this.clockModelIdref = BranchRateModel.BRANCH_RATES;
}
public static String[] clockModels = { "Strict Clock",
"Lognormal relaxed clock (Uncorrelated)",
"Exponential relaxed clock (Uncorrelated)",
"Inverse Gaussian relaxed clock"
};
public static String[] clockParameterNames = new String[] { "clock.rate", // StrictClock
"ucld.mean", // Lognormal relaxed clock
"ucld.stdev", // Lognormal relaxed clock
"ucld.offset", // Lognormal relaxed clock
"uced.mean", // Exponential relaxed clock
"uced.offset", // Exponential relaxed clock
"ig.mean", // Inverse Gaussian
"ig.stdev", // Inverse Gaussian
"ig.offset" // Inverse Gaussian
};
public static int[][] clockParameterIndices = { { 0 }, // StrictClock
{ 1, 2, 3 }, // Lognormal relaxed clock
{ 4, 5 }, // Exponential relaxed clock
{ 6, 7, 8 } // Inverse Gaussian
};
public double[] clockParameterValues = new double[] { 1.2E-2, // clockrate
1.0, // ucld.mean
2.0, // ucld.stdev
0.0, // ucld.offset
1.0, // uced.mean
0.0, // uced.offset
0.0, // ig.mean
1.0, // ig.stdev
0.0 // ig.offset
};
public BranchRateModel createClockRateModel() {
BranchRateModel branchRateModel = null;
if (this.clockModelIndex == 0) { // Strict Clock
Parameter rateParameter = new Parameter.Default(1, clockParameterValues[0]);
branchRateModel = new StrictClockBranchRates(rateParameter);
} else if (this.clockModelIndex == 1) {// Lognormal relaxed clock
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(LogNormalDistributionModelParser.MEAN, 1, clockParameterValues[1]);
Parameter stdev = new Parameter.Default(LogNormalDistributionModelParser.STDEV, 1, clockParameterValues[2]);
ParametricDistributionModel distributionModel = new LogNormalDistributionModel(mean, stdev, clockParameterValues[3], true, true);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), rateCategoryParameter,
distributionModel, 1, false, Double.NaN);
} else if(this.clockModelIndex == 2) { // Exponential relaxed clock
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(DistributionModelParser.MEAN, 1, clockParameterValues[4]);
ParametricDistributionModel distributionModel = new ExponentialDistributionModel(mean, clockParameterValues[5]);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), rateCategoryParameter,
distributionModel, 1, false, Double.NaN);
} else if(this.clockModelIndex == 3) { // Inverse Gaussian
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(InverseGaussianDistributionModelParser.MEAN, 1, clockParameterValues[6]);
Parameter stdev = new Parameter.Default(InverseGaussianDistributionModelParser.STDEV, 1, clockParameterValues[7]);
ParametricDistributionModel distributionModel = new InverseGaussianDistributionModel(
mean, stdev, clockParameterValues[8], false);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), rateCategoryParameter,
distributionModel, 1, false, Double.NaN);
} else {
System.out.println("Not yet implemented");
}
return branchRateModel;
}// END: createBranchRateModel
public String frequencyModelIdref = Utils.FREQUENCY_MODEL;
public void resetFrequencyModelIdref() {
this.frequencyModelIdref = Utils.FREQUENCY_MODEL;
}
public int frequencyModelIndex = 0;
public static String[] frequencyModels = { "Nucleotide frequencies",
"Codon frequencies",
"Amino acid frequencies"
};
public static String[] frequencyParameterNames = new String[] {
"A frequency", // Nucleotide frequencies
"C frequency", // Nucleotide frequencies
"G frequency", // Nucleotide frequencies
"T frequency", // Nucleotide frequencies
"AAA frequency", // Codon frequencies
"AAC frequency",
"AAG frequency",
"AAT frequency",
"ACA frequency",
"ACC frequency",
"ACG frequency",
"ACT frequency",
"AGA frequency",
"AGC frequency",
"AGG frequency",
"AGT frequency",
"ATA frequency",
"ATC frequency",
"ATG frequency",
"ATT frequency",
"CAA frequency",
"CAC frequency",
"CAG frequency",
"CAT frequency",
"CCA frequency",
"CCC frequency",
"CCG frequency",
"CCT frequency",
"CGA frequency",
"CGC frequency",
"CGG frequency",
"CGT frequency",
"CTA frequency",
"CTC frequency",
"CTG frequency",
"CTT frequency",
"GAA frequency",
"GAC frequency",
"GAG frequency",
"GAT frequency",
"GCA frequency",
"GCC frequency",
"GCG frequency",
"GCT frequency",
"GGA frequency",
"GGC frequency",
"GGG frequency",
"GGT frequency",
"GTA frequency",
"GTC frequency",
"GTG frequency",
"GTT frequency",
"TAC frequency",
"TAT frequency",
"TCA frequency",
"TCC frequency",
"TCG frequency",
"TCT frequency",
"TGC frequency",
"TGG frequency",
"TGT frequency",
"TTA frequency",
"TTC frequency",
"TTG frequency",
"TTT frequency", // Codon frequencies
"amino acid frequency 1",
"amino acid frequency 2",
"amino acid frequency 3",
"amino acid frequency 4",
"amino acid frequency 5",
"amino acid frequency 6",
"amino acid frequency 7",
"amino acid frequency 8",
"amino acid frequency 9",
"amino acid frequency 10",
"amino acid frequency 11",
"amino acid frequency 12",
"amino acid frequency 13",
"amino acid frequency 14",
"amino acid frequency 15",
"amino acid frequency 16",
"amino acid frequency 17",
"amino acid frequency 18",
"amino acid frequency 19",
"amino acid frequency 20"
};
public int[][] frequencyParameterIndices = { { 0, 1, 2, 3 }, // NucleotideFrequencies
{ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64 }, // CodonFrequencies
{ 65, 66, 67, 68, 69,
70, 71, 72, 73, 74,
75, 76, 77, 78, 79,
80, 81, 82, 83, 84
} // AminoAcidFrequencies
};
public double[] frequencyParameterValues = new double[] { 0.25, // A frequency
0.25, // C frequency
0.25, // G frequency
0.25, // T frequency
0.0163936, // AAA frequency
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344,
0.01639344, // TTT frequency
0.05, // aminoacidfrequency1
0.05, // aminoacidfrequency2
0.05, // aminoacidfrequency3
0.05, // aminoacidfrequency4
0.05, // aminoacidfrequency5
0.05, // aminoacidfrequency6
0.05, // aminoacidfrequency7
0.05, // aminoacidfrequency8
0.05, // aminoacidfrequency9
0.05, // aminoacidfrequency10
0.05, // aminoacidfrequency11
0.05, // aminoacidfrequency12
0.05, // aminoacidfrequency13
0.05, // aminoacidfrequency14
0.05, // aminoacidfrequency15
0.05, // aminoacidfrequency16
0.05, // aminoacidfrequency17
0.05, // aminoacidfrequency18
0.05, // aminoacidfrequency19
0.05 // aminoacidfrequency20
};
public FrequencyModel createFrequencyModel() {
FrequencyModel frequencyModel = null;
if (this.frequencyModelIndex == 0) { // Nucleotidefrequencies
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[0], frequencyParameterValues[1],
frequencyParameterValues[2], frequencyParameterValues[3] });
frequencyModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
} else if (this.frequencyModelIndex == 1) {
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[4], frequencyParameterValues[5],
frequencyParameterValues[6], frequencyParameterValues[7],
frequencyParameterValues[8], frequencyParameterValues[9],
frequencyParameterValues[10], frequencyParameterValues[11],
frequencyParameterValues[12], frequencyParameterValues[13],
frequencyParameterValues[14], frequencyParameterValues[15],
frequencyParameterValues[16], frequencyParameterValues[17],
frequencyParameterValues[18], frequencyParameterValues[19],
frequencyParameterValues[20], frequencyParameterValues[21],
frequencyParameterValues[22], frequencyParameterValues[23],
frequencyParameterValues[24], frequencyParameterValues[25],
frequencyParameterValues[26], frequencyParameterValues[27],
frequencyParameterValues[28], frequencyParameterValues[29],
frequencyParameterValues[30], frequencyParameterValues[31],
frequencyParameterValues[32], frequencyParameterValues[33],
frequencyParameterValues[34], frequencyParameterValues[35],
frequencyParameterValues[36], frequencyParameterValues[37],
frequencyParameterValues[38], frequencyParameterValues[39],
frequencyParameterValues[40], frequencyParameterValues[41],
frequencyParameterValues[42], frequencyParameterValues[43],
frequencyParameterValues[44], frequencyParameterValues[45],
frequencyParameterValues[46], frequencyParameterValues[47],
frequencyParameterValues[48], frequencyParameterValues[49],
frequencyParameterValues[50], frequencyParameterValues[51],
frequencyParameterValues[52], frequencyParameterValues[53],
frequencyParameterValues[54], frequencyParameterValues[55],
frequencyParameterValues[56], frequencyParameterValues[57],
frequencyParameterValues[58], frequencyParameterValues[59],
frequencyParameterValues[60], frequencyParameterValues[61],
frequencyParameterValues[62], frequencyParameterValues[63],
frequencyParameterValues[64] });
frequencyModel = new FrequencyModel(Codons.UNIVERSAL, freqs);
} else if (this.frequencyModelIndex == 2) {
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[65], frequencyParameterValues[66], frequencyParameterValues[67], frequencyParameterValues[68],
frequencyParameterValues[69], frequencyParameterValues[70], frequencyParameterValues[71], frequencyParameterValues[72],
frequencyParameterValues[73], frequencyParameterValues[74], frequencyParameterValues[75], frequencyParameterValues[76],
frequencyParameterValues[77], frequencyParameterValues[78], frequencyParameterValues[79], frequencyParameterValues[80],
frequencyParameterValues[81], frequencyParameterValues[82], frequencyParameterValues[83], frequencyParameterValues[84]
});
frequencyModel = new FrequencyModel(AminoAcids.INSTANCE, freqs);
} else {
System.out.println("Not yet implemented");
}
return frequencyModel;
}// END: createFrequencyModel
public int siteRateModelIndex = 0;
public String siteRateModelIdref = SiteModel.SITE_MODEL;
public void resetSiteRateModelIdref() {
this.siteRateModelIdref = SiteModel.SITE_MODEL;
}
public static String[] siteRateModels = { "No Model",
"Site Rate Model"
};
public static String[] siteRateModelParameterNames = new String[] {
"Gamma categories", // Gamma Site Rate Model
"Alpha", // Gamma Site Rate Model
"Invariant sites proportion" // Gamma Site Rate Model
};
public static int[][] siteRateModelParameterIndices = { {}, // NoModel
{ 0, 1, 2 }, // GammaSiteRateModel
};
public double[] siteRateModelParameterValues = new double[] { 4.0, // GammaCategories
0.5, // Alpha
0.0 // Invariant sites proportion
};
public GammaSiteRateModel createSiteRateModel() {
GammaSiteRateModel siteModel = null;
String name = "siteModel";
if (this.siteRateModelIndex == 0) { // no model
siteModel = new GammaSiteRateModel(name);
} else if (this.siteRateModelIndex == 1) { // GammaSiteRateModel
siteModel = new GammaSiteRateModel(name,
siteRateModelParameterValues[1],
(int) siteRateModelParameterValues[0], siteRateModelParameterValues[2]);
} else {
System.out.println("Not yet implemented");
}
return siteModel;
}// END: createGammaSiteRateModel
public String ancestralSequenceString = null;
public Sequence createAncestralSequence() {
Sequence sequence = new Sequence(ancestralSequenceString);
// sequence.appendSequenceString(ancestralSequenceString);
return sequence;
}
}// END: class
|
package io.toolisticon.annotationprocessortoolkit.tools.fluentfilter;
import io.toolisticon.annotationprocessortoolkit.tools.command.Command;
import io.toolisticon.annotationprocessortoolkit.tools.command.CommandWithReturnType;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.ExclusiveCriteriaCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.ExclusiveCriteriaElementBasedCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.ImplicitCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.ImplicitElementBasedCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.InclusiveCharacteristicElementBasedCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.InclusiveCriteriaCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.IsCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.corematcher.IsElementBasedCoreMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.filter.ExclusiveCriteriaElementFilter;
import io.toolisticon.annotationprocessortoolkit.tools.filter.InclusiveCriteriaElementFilter;
import io.toolisticon.annotationprocessortoolkit.tools.fluentfilter.impl.ElementBasedTransitionFilter;
import io.toolisticon.annotationprocessortoolkit.tools.fluentfilter.impl.TransitionFilter;
import io.toolisticon.annotationprocessortoolkit.tools.matcher.CriteriaMatcher;
import io.toolisticon.annotationprocessortoolkit.tools.validator.ExclusiveCriteriaElementValidator;
import io.toolisticon.annotationprocessortoolkit.tools.validator.InclusiveCriteriaElementValidator;
import javax.lang.model.element.Element;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Fluent Element Filter.
*/
public class FluentElementFilter<ELEMENT extends Element> {
/**
* The element list to filter.
*/
private final List<ELEMENT> elements;
/**
* Constructor to be called from inside the static builder function.
*
* @param elements the element list to filter
*/
private FluentElementFilter(List<ELEMENT> elements) {
this.elements = elements;
}
/**
* Validator step for exclusive criteria validators.
*
* @param <FILTER_ELEMENT> the filters element type
* @param <CRITERIA> the criteria type
*/
public class ExclusiveCharacteristicFluentFilter<FILTER_ELEMENT extends Element, CRITERIA> {
private final boolean inverted;
private final ExclusiveCriteriaElementFilter<FILTER_ELEMENT, CRITERIA, ExclusiveCriteriaElementValidator<FILTER_ELEMENT, CRITERIA, CriteriaMatcher<FILTER_ELEMENT, CRITERIA>>> filter;
private ExclusiveCharacteristicFluentFilter(ExclusiveCriteriaElementFilter<FILTER_ELEMENT, CRITERIA, ExclusiveCriteriaElementValidator<FILTER_ELEMENT, CRITERIA, CriteriaMatcher<FILTER_ELEMENT, CRITERIA>>> filter, boolean inverted) {
this.filter = filter;
this.inverted = inverted;
}
/**
* Filters by one of the passed criteria.
* elements won't be discarded if element matches exactly one of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByOneOf(CRITERIA... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByOneOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
/**
* Filters by none of the passed criteria.
* elements won't be discarded if element matches none of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByNoneOf(CRITERIA... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByNoneOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
}
/**
* Validator step for inclusive characteristics validators.
*
* @param <FILTER_ELEMENT>
* @param <CHARACTERISTIC>
*/
public class InclusiveCriteriaFluentFilter<FILTER_ELEMENT extends Element, CHARACTERISTIC> {
private final boolean inverted;
private final InclusiveCriteriaElementFilter<FILTER_ELEMENT, CHARACTERISTIC, InclusiveCriteriaElementValidator<FILTER_ELEMENT, CHARACTERISTIC, CriteriaMatcher<FILTER_ELEMENT, CHARACTERISTIC>>> filter;
private InclusiveCriteriaFluentFilter(InclusiveCriteriaElementFilter<FILTER_ELEMENT, CHARACTERISTIC, InclusiveCriteriaElementValidator<FILTER_ELEMENT, CHARACTERISTIC, CriteriaMatcher<FILTER_ELEMENT, CHARACTERISTIC>>> filter, boolean inverted) {
this.filter = filter;
this.inverted = inverted;
}
/**
* Filters by one of the passed criteria.
* elements won't be discarded if element matches exactly one of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByOneOf(CHARACTERISTIC... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByOneOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
/**
* Filters by none of the passed criteria.
* elements won't be discarded if element matches none of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByNoneOf(CHARACTERISTIC... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByNoneOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
/**
* Filters by at least one of the passed criteria.
* elements won't be discarded if element matches at least one of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByAtLeastOneOf(CHARACTERISTIC... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByAtLeastOneOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
/**
* Filters by all of the passed criteria.
* elements won't be discarded if element matches all of the passed criteria.
*
* @param criteria the criteria to be used for filtering
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> filterByAllOf(CHARACTERISTIC... criteria) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) filter.filterByAllOf((List<FILTER_ELEMENT>) elements, inverted, criteria));
}
}
// -- IS FILTERS
/**
* Applies is filter.
* Changes generic type of fluent filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<TARGET_ELEMENT> applyFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher) {
return new FluentElementFilter<TARGET_ELEMENT>((List<TARGET_ELEMENT>) coreMatcher.getFilter().filter(elements));
}
/**
* Applies inverted is filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<ELEMENT> applyInvertedFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher) {
return new FluentElementFilter<ELEMENT>(coreMatcher.getFilter().filter(elements, true));
}
/**
* Applies is element based filter.
* Changes generic type of fluent filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<TARGET_ELEMENT> applyFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher) {
return new FluentElementFilter<TARGET_ELEMENT>((List<TARGET_ELEMENT>) coreMatcher.getFilter().filter((List<Element>) elements));
}
/**
* Applies inverted implicit element based filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<ELEMENT> applyInvertedFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) coreMatcher.getFilter().filter((List<Element>) elements, true));
}
// -- IMPLICIT FILTERS
/**
* Applies implicit filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> applyFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) coreMatcher.getFilter().filter(elements));
}
/**
* Applies inverted implicit filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) coreMatcher.getFilter().filter(elements,true));
}
/**
* Applies implicit element based filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> applyFilter(ImplicitElementBasedCoreMatcher coreMatcher) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) coreMatcher.getFilter().filter((List<Element>) elements));
}
/**
* Applies inverted implicit element based filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitElementBasedCoreMatcher coreMatcher) {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) coreMatcher.getFilter().filter((List<Element>) elements, true));
}
// -- INCLUSIVE CRITERIA FILTERS
/**
* Applies inclusive criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CRITERIA> InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher) {
return new InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA>(coreMatcher.getFilter(), false);
}
/**
* Applies inverted inclusive criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CRITERIA> InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyInvertedFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher) {
return new InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA>(coreMatcher.getFilter(), true);
}
/**
* Applies inclusive criteria element based filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CRITERIA> InclusiveCriteriaFluentFilter<Element, CRITERIA> applyFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher) {
return new InclusiveCriteriaFluentFilter<Element, CRITERIA>(coreMatcher.getFilter(), false);
}
/**
* Applies inverted inclusive element based criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CRITERIA> InclusiveCriteriaFluentFilter<Element, CRITERIA> applyInvertedFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher) {
return new InclusiveCriteriaFluentFilter<Element, CRITERIA>(coreMatcher.getFilter(), true);
}
// -- EXPLICIT FILTERS
/**
* Applies exclusive criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CHARACTERISTIC> ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher) {
return new ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC>(coreMatcher.getFilter(), false);
}
/**
* Applies inverted exclusive criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CHARACTERISTIC> ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher) {
return new ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC>(coreMatcher.getFilter(), true);
}
/**
* Applies exclusive criteria element based filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CHARACTERISTIC> ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher) {
return new ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC>(coreMatcher.getFilter(), false);
}
/**
* Applies inverted exclusive element based criteria filter.
*
* @param coreMatcher the implicit core matcher to use
* @return the FluentElementFilter instance
*/
public <CHARACTERISTIC> ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher) {
return new ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC>(coreMatcher.getFilter(), true);
}
/**
* Applies transition filter.
*
* @param transitionFilter the transition filter to use
* @param <TARGET_ELEMENT>
* @return the new FluentElementFilter instance based on transition filter result
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(TransitionFilter<ELEMENT, TARGET_ELEMENT> transitionFilter) {
return new FluentElementFilter<TARGET_ELEMENT>(transitionFilter.transition(elements));
}
/**
* Applies transition filter.
*
* @param transitionFilter the transition filter to use
* @param <TARGET_ELEMENT>
* @return the new FluentElementFilter instance based on transition filter result
*/
public <TARGET_ELEMENT extends Element> FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(ElementBasedTransitionFilter<TARGET_ELEMENT> transitionFilter) {
return new FluentElementFilter<TARGET_ELEMENT>(transitionFilter.transition(elements));
}
/**
* Removes all duplicate values.
*
* @return this instance
*/
public FluentElementFilter<ELEMENT> removeDuplicates() {
return new FluentElementFilter<ELEMENT>((List<ELEMENT>) TransitionFilters.REMOVE_DUPLICATES_ELEMENTS.transition(elements));
}
/**
* Executes commands.
*
* @param command the command to be executed
*/
public void executeCommand(Command<ELEMENT> command) {
if (command != null) {
for (ELEMENT element : elements) {
command.execute(element);
}
}
}
/**
* Executes command with a return value.
* Returns a list that contains all return values of executed commands.
*
* @param command the command to be executed
* @param <RETURN_TYPE> the return type
* @return a list containing all results of executed commands
*/
public <RETURN_TYPE> List<RETURN_TYPE> executeCommand(CommandWithReturnType<ELEMENT, RETURN_TYPE> command) {
List<RETURN_TYPE> resultList = new ArrayList<RETURN_TYPE>();
if (command != null) {
for (ELEMENT element : elements) {
resultList.add(command.execute(element));
}
}
return resultList;
}
/**
* Gets the filter result.
*
* @return the filtered List
*/
public List<ELEMENT> getResult() {
return elements;
}
/**
* Checks if filter result is empty.
*
* @return true if filter result is empty, otherwise false
*/
public boolean isEmpty() {
return elements == null || elements.isEmpty();
}
/**
* Checks if filter result contains exactly one element.
*
* @return true if filter result contains exactly one element, otherwise false
*/
public boolean hasSingleElement() {
return elements != null && elements.size() == 1;
}
/**
* Checks if filter result contains more than one element.
*
* @return true if filter result contains more than one element, otherwise false
*/
public boolean hasMultipleElements() {
return elements != null && elements.size() > 1;
}
/**
* Checks whether the filter result has exactly the passed size.
*
* @param size the size to check for
* @return true if passed size matches the filter results size, otherwise false
*/
public boolean hasSize(int size) {
return elements != null && elements.size() == size;
}
/**
* Gets the result size.
*
* @return the filtered results size.
*/
public int getResultSize() {
return elements == null ? 0 : elements.size();
}
/**
* Factory method to create FluentElementFilter instance.
*
* @param elements the element list to filter
* @param <E> The element type
* @return the FluentElementFilter instance
*/
public static <E extends Element> FluentElementFilter<E> createFluentElementFilter(List<E> elements) {
return new FluentElementFilter<E>(elements);
}
/**
* Factory method to create FluentElementFilter instance.
*
* @param elements the elements to filter
* @param <E> The element type
* @return the FluentElementFilter instance
*/
public static <E extends Element> FluentElementFilter<E> createFluentElementFilter(E... elements) {
return new FluentElementFilter<E>(new ArrayList<E>(elements != null ? Arrays.asList(elements) : Collections.EMPTY_LIST));
}
}
|
package dr.app.tools;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.evolution.io.Importer;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.*;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.util.Version;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
/**
* @author Andrew Rambaut
*/
public class TreeSummary {
private final static Version version = new BeastVersion();
// Messages to stderr, output to stdout
private static PrintStream progressStream = System.err;
/**
* Burnin can be specified as the number of trees or the number of states
* (one or other should be zero).
* @param burninTrees
* @param burninStates
* @param posteriorLimit
* @param inputFileName
* @param outputFileName
* @throws java.io.IOException
*/
public TreeSummary(final int burninTrees,
final int burninStates,
double posteriorLimit,
String inputFileName,
String outputFileName
) throws IOException {
this.posteriorLimit = posteriorLimit;
CladeSystem cladeSystem = new CladeSystem();
int burnin = -1;
totalTrees = 10000;
totalTreesUsed = 0;
progressStream.println("Reading trees (bar assumes 10,000 trees)...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int stepSize = totalTrees / 60;
if (stepSize < 1) stepSize = 1;
cladeSystem = new CladeSystem();
FileReader fileReader = new FileReader(inputFileName);
TreeImporter importer = new NexusImporter(fileReader);
try {
totalTrees = 0;
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
int state = Integer.MAX_VALUE;
if (burninStates > 0) {
// if burnin has been specified in states, try to parse it out...
String name = tree.getId().trim();
if (name != null && name.length() > 0 && name.startsWith("STATE_")) {
state = Integer.parseInt(name.split("_")[1]);
}
}
if (totalTrees >= burninTrees && state >= burninStates) {
// if either of the two burnin thresholds have been reached...
if (burnin < 0) {
// if this is the first time this point has been reached,
// record the number of trees this represents for future use...
burnin = totalTrees;
}
cladeSystem.add(tree, true);
totalTreesUsed += 1;
}
if (totalTrees > 0 && totalTrees % stepSize == 0) {
progressStream.print("*");
progressStream.flush();
}
totalTrees++;
}
} catch (Importer.ImportException e) {
System.err.println("Error Parsing Input Tree: " + e.getMessage());
return;
}
fileReader.close();
progressStream.println();
progressStream.println();
if (totalTrees < 1) {
System.err.println("No trees");
return;
}
if (totalTreesUsed <= 1) {
if (burnin > 0) {
System.err.println("No trees to use: burnin too high");
return;
}
}
cladeSystem.calculateCladeCredibilities(totalTreesUsed);
progressStream.println("Total trees read: " + totalTrees);
if (burninTrees > 0) {
progressStream.println("Ignoring first " + burninTrees + " trees" +
(burninStates > 0 ? " (" + burninStates + " states)." : "." ));
} else if (burninStates > 0) {
progressStream.println("Ignoring first " + burninStates + " states (" + burnin + " trees).");
}
progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size());
progressStream.println();
progressStream.println("Finding summary tree...");
// MutableTree targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName /*, false*/));
Tree consensusTree = buildConsensusTree(cladeSystem);
progressStream.println("Writing consensus tree....");
try {
final PrintStream stream = outputFileName != null ?
new PrintStream(new FileOutputStream(outputFileName)) :
System.out;
new NexusExporter(stream).exportTree(consensusTree);
} catch (Exception e) {
System.err.println("Error writing consensus tree file: " + e.getMessage());
return;
}
}
private Tree buildConsensusTree(CladeSystem cladeSystem) {
List<BitSet> bitSets = new ArrayList<BitSet>(cladeSystem.getCladeMap().keySet());
Collections.sort(bitSets, new Comparator<BitSet>() {
@Override
public int compare(BitSet b1, BitSet b2) {
return b1.cardinality() - b2.cardinality();
}
});
SimpleNode root = null;
for (int i = 0; i < bitSets.size(); i++) {
BitSet key1 = bitSets.get(i);
CladeSystem.Clade clade1 = cladeSystem.getCladeMap().get(key1);
if (key1.cardinality() == 1) {
Taxon taxon = cladeSystem.getTaxon(key1.nextSetBit(0));
clade1.node = new SimpleNode();
clade1.node.setTaxon(taxon);
clade1.node.setAttribute("clade", clade1);
}
if (clade1.credibility >= posteriorLimit) {
for (int j = i + 1; j < bitSets.size(); j++) {
BitSet key2 = bitSets.get(j);
if (isSubSet(key1, key2) && cladeSystem.getCladeCredibility(key2) >= posteriorLimit) {
// the clades are ordered by size so this is the smallest clade for which
// clade1 is a subset and has high credibility.
CladeSystem.Clade clade2 = cladeSystem.getCladeMap().get(key2);
if (clade2.node == null) {
clade2.node = new SimpleNode();
}
if (clade1.node == null) {
throw new RuntimeException("null node");
}
clade2.node.addChild(clade1.node);
clade2.node.setAttribute("credibility", clade2.credibility);
clade2.node.setAttribute("clade", clade2);
if (key2.cardinality() == cladeSystem.taxonList.getTaxonCount()) {
root = clade2.node;
}
break;
}
}
}
}
SimpleTree tree = new SimpleTree(root);
return tree;
}
private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName)
throws IOException {
progressStream.println("Analyzing " + totalTreesUsed + " trees...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int stepSize = totalTrees / 60;
if (stepSize < 1) stepSize = 1;
int counter = 0;
int bestTreeNumber = 0;
TreeImporter importer = new NexusImporter(new FileReader(inputFileName));
try {
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
if (counter >= burnin) {
cladeSystem.addSubTrees(tree);
}
if (counter > 0 && counter % stepSize == 0) {
progressStream.print("*");
progressStream.flush();
}
counter++;
}
} catch (Importer.ImportException e) {
System.err.println("Error Parsing Input Tree: " + e.getMessage());
return null;
}
Tree bestTree = cladeSystem.getBestTree();
return bestTree;
}
private class CladeSystem {
public CladeSystem() {
}
public CladeSystem(TaxonList taxonList) {
this.taxonList = taxonList;
}
/**
* adds all the clades in the tree
*/
public void add(Tree tree, boolean includeTips) {
if (taxonList == null) {
taxonList = tree;
}
// Recurse over the tree and add all the clades (or increment their
// frequency if already present). The root clade is added too (for
// annotation purposes).
addClades(tree, tree.getRoot(), includeTips);
}
private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) {
BitSet bits = new BitSet();
if (tree.isExternal(node)) {
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
bits.set(index);
if (includeTips) {
addClade(bits);
}
} else {
for (int i = 0; i < tree.getChildCount(node); i++) {
NodeRef node1 = tree.getChild(node, i);
bits.or(addClades(tree, node1, includeTips));
}
addClade(bits);
}
return bits;
}
private void addClade(BitSet bits) {
Clade clade = cladeMap.get(bits);
if (clade == null) {
clade = new Clade(bits);
cladeMap.put(bits, clade);
}
clade.setCount(clade.getCount() + 1);
}
public void addSubTrees(Tree tree) {
addSubTrees(tree, tree.getRoot());
}
private BitSet addSubTrees(Tree tree, NodeRef node) {
BitSet bits = new BitSet();
if (tree.isExternal(node)) {
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
bits.set(index);
} else {
for (int i = 0; i < tree.getChildCount(node); i++) {
NodeRef node1 = tree.getChild(node, i);
BitSet bits2 = addSubTrees(tree, node1);
bits.or(bits2);
}
Clade clade = cladeMap.get(bits);
if (clade.credibility >= posteriorLimit) {
if (clade.conditionalCladeSystem == null) {
clade.conditionalCladeSystem = new CladeSystem(taxonList);
}
clade.conditionalCladeSystem.addClades(tree, node, false);
}
}
return bits;
}
public Map<BitSet, Clade> getCladeMap() {
return cladeMap;
}
public void calculateCladeCredibilities(int totalTreesUsed) {
for (Clade clade : cladeMap.values()) {
if (clade.getCount() > totalTreesUsed) {
throw new AssertionError("clade.getCount=(" + clade.getCount() +
") should be <= totalTreesUsed = (" + totalTreesUsed + ")");
}
clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed);
if (clade.conditionalCladeSystem != null) {
clade.conditionalCladeSystem.calculateCladeCredibilities(totalTreesUsed);
}
}
}
public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) {
double logCladeCredibility = 0.0;
if (tree.isExternal(node)) {
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
bits.set(index);
} else {
BitSet bits2 = new BitSet();
for (int i = 0; i < tree.getChildCount(node); i++) {
NodeRef node1 = tree.getChild(node, i);
logCladeCredibility += getLogCladeCredibility(tree, node1, bits2);
}
logCladeCredibility += Math.log(getCladeCredibility(bits2));
if (bits != null) {
bits.or(bits2);
}
}
return logCladeCredibility;
}
private double getCladeCredibility(BitSet bits) {
Clade clade = cladeMap.get(bits);
if (clade == null) {
return 0.0;
}
return clade.getCredibility();
}
public Tree getBestTree() {
return null;
}
public Taxon getTaxon(int index) {
return taxonList.getTaxon(index);
}
class Clade {
public Clade(BitSet bits) {
this.bits = bits;
count = 0;
credibility = 0.0;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getCredibility() {
return credibility;
}
public void setCredibility(double credibility) {
this.credibility = credibility;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Clade clade = (Clade) o;
return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null);
}
public int hashCode() {
return (bits != null ? bits.hashCode() : 0);
}
public String toString() {
return "clade " + bits.toString();
}
int count;
double credibility;
BitSet bits;
SimpleNode node;
CladeSystem conditionalCladeSystem;
}
// Private stuff
TaxonList taxonList = null;
Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>();
Tree targetTree;
}
int totalTrees = 0;
int totalTreesUsed = 0;
double posteriorLimit = 0.0;
Set<String> attributeNames = new HashSet<String>();
public static void printTitle() {
progressStream.println();
centreLine("TreeSummary " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC tree set summarizer", 60);
centreLine("by", 60);
centreLine("Andrew Rambaut", 60);
progressStream.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
progressStream.println();
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printUsage(Arguments arguments) {
arguments.printUsage("treesummary", "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: treesummary test.trees out.txt");
progressStream.println(" Example: treesummary -burnin 100 -heights mean test.trees out.txt");
progressStream.println();
}
//Main method
public static void main(String[] args) throws IOException {
// There is a major issue with languages that use the comma as a decimal separator.
// To ensure compatibility between programs in the package, enforce the US locale.
Locale.setDefault(Locale.US);
String inputFileName = null;
String outputFileName = null;
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"),
new Arguments.IntegerOption("burninTrees", "the number of trees to be considered as 'burn-in'"),
new Arguments.RealOption("limit", "the minimum posterior probability for a subtree to be included"),
new Arguments.Option("help", "option to print this message")
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
int burninStates = -1;
int burninTrees = -1;
if (arguments.hasOption("burnin")) {
burninStates = arguments.getIntegerOption("burnin");
}
if (arguments.hasOption("burninTrees")) {
burninTrees = arguments.getIntegerOption("burninTrees");
}
double posteriorLimit = 0.5;
if (arguments.hasOption("limit")) {
posteriorLimit = arguments.getRealOption("limit");
}
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
System.err.println("Unknown option: " + args2[2]);
System.err.println();
printUsage(arguments);
System.exit(1);
}
}
new TreeSummary(burninTrees, burninStates, posteriorLimit, inputFileName, outputFileName);
System.exit(0);
}
/**
* Is x a subset of y?
* @param x
* @param y
* @return
*/
static boolean isSubSet(BitSet x, BitSet y) {
y = (BitSet) y.clone();
y.and(x);
return y.equals(x);
}
}
|
package org.aracrown.commons.ui.security;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener;
import org.apache.wicket.authorization.UnauthorizedInstantiationException;
import org.apache.wicket.request.cycle.RequestCycle;
/**
* Handling class of unauthorized component instantiations.
*
* @author vicento.ramos
*
* @since 1.0.0
*
* @param <T>
* Concrete Login page implementation class type
*
*/
public abstract class SimpleUnauthorizedComponentInstantiationListener<T extends Page> implements IUnauthorizedComponentInstantiationListener {
@Override
public void onUnauthorizedInstantiation(Component component) {
// If there is a sign in page class declared, and the
// unauthorized component is a page, but it's not the
// sign in page
if (component instanceof Page) {
// Save original request for redirect purposes
HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
WebUtils.saveRequest(request);
// Redirect to page to let the user sign in
throw new RestartResponseAtInterceptPageException(getLoginPage());
} else {
// The component was not a page, so throw exception
throw new UnauthorizedInstantiationException(component.getClass());
}
}
/**
* Returns login page, containing sign-in form.
*
* @return login page class
*/
protected abstract Class<T> getLoginPage();
}
|
package org.ovirt.engine.core.bll.host.provider.foreman;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.ovirt.engine.core.bll.host.provider.HostProviderProxy;
import org.ovirt.engine.core.bll.provider.BaseProviderProxy;
import org.ovirt.engine.core.common.businessentities.Erratum;
import org.ovirt.engine.core.common.businessentities.Erratum.ErrataSeverity;
import org.ovirt.engine.core.common.businessentities.Erratum.ErrataType;
import org.ovirt.engine.core.common.businessentities.ExternalComputeResource;
import org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost;
import org.ovirt.engine.core.common.businessentities.ExternalHostGroup;
import org.ovirt.engine.core.common.businessentities.ExternalOperatingSystem;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.errors.EngineError;
import org.ovirt.engine.core.common.errors.EngineException;
import org.ovirt.engine.core.uutils.crypto.CryptMD5;
public class ForemanHostProviderProxy extends BaseProviderProxy implements HostProviderProxy {
private ObjectMapper objectMapper = new ObjectMapper();
private static final String API_ENTRY_POINT = "/api/v2";
private static final String JSON_FORMAT = "format=json";
private static final String HOSTS_ENTRY_POINT = API_ENTRY_POINT + "/hosts";
private static final String ALL_HOSTS_QUERY = HOSTS_ENTRY_POINT + "?" + JSON_FORMAT;
private static final String SEARCH_SECTION_FORMAT = "search=%1$s";
private static final String SEARCH_QUERY_FORMAT = "?" + SEARCH_SECTION_FORMAT + "&" + JSON_FORMAT;
private static final String HOST_GROUPS_ENTRY_POINT = API_ENTRY_POINT + "/hostgroups";
private static final String HOST_GROUPS_QUERY = HOST_GROUPS_ENTRY_POINT + "?" + JSON_FORMAT;
private static final String COMPUTE_RESOURCES_HOSTS_ENTRY_POINT = API_ENTRY_POINT
+ "/compute_resources?search=" + URLEncoder.encode("oVirt|RHEV");
private static final String DISCOVERED_HOSTS = "/discovered_hosts";
private static final String DISCOVERED_HOSTS_ENTRY_POINT = API_ENTRY_POINT + DISCOVERED_HOSTS;
private static final String OPERATION_SYSTEM_ENTRY_POINT = API_ENTRY_POINT + "/operatingsystems";
private static final String OPERATION_SYSTEM_QUERY = OPERATION_SYSTEM_ENTRY_POINT + "?" + JSON_FORMAT;
private static final String KATELLO_API_ENTRY_POINT = "/katello/api/v2";
private static final String CONTENT_HOSTS_ENTRY_POINT = KATELLO_API_ENTRY_POINT + "/systems";
/**
* per_page=99999 used to bypass Satellite pagination limit (20 by default), while pagination is not
* supported by Katello.
*/
private static final String CONTENT_HOST_ERRATA_ENTRY_POINT = CONTENT_HOSTS_ENTRY_POINT
+ "/%1$s/errata?per_page=99999";
private static final String CONTENT_HOST_ERRATUM_ENTRY_POINT = CONTENT_HOSTS_ENTRY_POINT + "/%1$s/errata/%2$s";
public ForemanHostProviderProxy(Provider<?> hostProvider) {
super(hostProvider);
objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
private byte[] runHttpGetMethod(String relativeUrl) {
return runHttpMethod(
HttpMethodType.GET,
"application/json; charset=utf-8",
relativeUrl,
null);
}
private List<VDS> runHostListMethod(String relativeUrl) {
try {
ForemanHostWrapper fhw = objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanHostWrapper.class);
return mapHosts(Arrays.asList(fhw.getResults()));
} catch (IOException e) {
return null;
}
}
private List<ExternalDiscoveredHost> runDiscoveredHostListMethod(String relativeUrl) {
try {
ForemanDiscoveredHostWrapper fdw =
objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanDiscoveredHostWrapper.class);
return mapDiscoveredHosts(Arrays.asList(fdw.getResults()));
} catch (IOException e) {
return null;
}
}
private List<ExternalHostGroup> runHostGroupListMethod(String relativeUrl) {
try {
ForemanHostGroupWrapper fhgw =
objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanHostGroupWrapper.class);
return mapHostGroups(Arrays.asList(fhgw.getResults()));
} catch (IOException e) {
return null;
}
}
private List<ExternalOperatingSystem> runOperationSystemMethod(String relativeUrl) {
try {
ForemanOperatingSystemWrapper fosw =
objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanOperatingSystemWrapper.class);
return mapOperationSystem(Arrays.asList(fosw.getResults()));
} catch (IOException e) {
return null;
}
}
private List<ExternalComputeResource> runComputeResourceMethod(String relativeUrl) {
try {
ForemanComputerResourceWrapper fcrw =
objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanComputerResourceWrapper.class);
return mapComputeResource(Arrays.asList(fcrw.getResults()));
} catch (IOException e) {
return null;
}
}
// Mapping
private List<ExternalComputeResource> mapComputeResource(List<ForemanComputerResource> foremanCrs) {
List<ExternalComputeResource> crs = new ArrayList<>(foremanCrs.size());
for (ForemanComputerResource cr : foremanCrs) {
ExternalComputeResource computeResource = new ExternalComputeResource();
computeResource.setName(cr.getName());
computeResource.setUrl(cr.getUrl());
computeResource.setId(cr.getId());
computeResource.setProvider(cr.getProvider());
computeResource.setUser(cr.getUser());
crs.add(computeResource);
}
return crs;
}
private List<ExternalOperatingSystem> mapOperationSystem(List<ForemanOperatingSystem> foremanOss) {
List<ExternalOperatingSystem> oss = new ArrayList<>(foremanOss.size());
for (ForemanOperatingSystem os : foremanOss) {
ExternalOperatingSystem eos = new ExternalOperatingSystem();
eos.setName(os.getName());
eos.setId(os.getId());
oss.add(eos);
}
return oss;
}
private List<ExternalDiscoveredHost> mapDiscoveredHosts(List<ForemanDiscoveredHost> foremanHosts) {
List<ExternalDiscoveredHost> hosts = new ArrayList<>(foremanHosts.size());
for (ForemanDiscoveredHost host : foremanHosts) {
ExternalDiscoveredHost dhost = new ExternalDiscoveredHost();
dhost.setName(host.getName());
dhost.setIp(host.getIp());
dhost.setMac(host.getMac());
dhost.setLastReport(host.getLast_report());
dhost.setSubnetName(host.getSubnet_name());
hosts.add(dhost);
}
return hosts;
}
private List<VDS> mapHosts(List<ForemanHost> foremanHosts) {
List<VDS> hosts = new ArrayList<>(foremanHosts.size());
for (ForemanHost host : foremanHosts) {
VDS vds = new VDS();
vds.setVdsName(host.getName());
vds.setHostName(host.getName());
hosts.add(vds);
}
return hosts;
}
private List<ExternalHostGroup> mapHostGroups(List<ForemanHostGroup> foremanHostGroups) {
Map<Integer, ExternalHostGroup> hostGroups = new HashMap<>();
for (ForemanHostGroup hostGroup : foremanHostGroups) {
ExternalHostGroup hostgroup = new ExternalHostGroup();
hostgroup.setHostgroupId(hostGroup.getId());
hostgroup.setName(hostGroup.getName());
hostgroup.setOperatingsystemId(hostGroup.getOperatingsystem_id());
hostgroup.setEnvironmentId(hostGroup.getEnvironment_id());
hostgroup.setDomainId(hostGroup.getDomain_id());
hostgroup.setSubnetId(hostGroup.getSubnet_id());
hostgroup.setParameters(hostGroup.getParameters());
hostgroup.setMediumId(hostGroup.getMedium_id());
hostgroup.setArchitectureId(hostGroup.getArchitecture_id());
hostgroup.setPtableId(hostGroup.getPtable_id());
hostgroup.setOperatingsystemName(hostGroup.getOperatingsystem_name());
hostgroup.setDomainName(hostGroup.getDomain_name());
hostgroup.setSubnetName(hostGroup.getSubnet_name());
hostgroup.setArchitectureName(hostGroup.getArchitecture_name());
hostgroup.setAncestry(hostGroup.getAncestry());
hostgroup.setEnvironmentName(hostGroup.getEnvironment_name());
hostgroup.setPtableName(hostGroup.getPtable_name());
hostgroup.setMediumName(hostGroup.getMedium_name());
hostGroups.put(hostGroup.getId(), hostgroup);
}
List<ExternalHostGroup> ret = new ArrayList<>(foremanHostGroups.size());
for (ForemanHostGroup hostGroup : foremanHostGroups) {
if (hostGroup.getAncestry() != null) {
String[] ancestries = hostGroup.getAncestry().split("/");
if (hostGroup.getMedium_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String medName = hg.getMediumName();
if (medName != null) {
int medId = hg.getMediumId();
hostGroups.get(hostGroup.getId()).setMediumName(medName);
hostGroups.get(hostGroup.getId()).setMediumId(medId);
break;
}
}
}
if (hostGroup.getEnvironment_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String envName = hg.getEnvironmentName();
if (envName != null) {
int envId = hg.getEnvironmentId();
hostGroups.get(hostGroup.getId()).setEnvironmentName(envName);
hostGroups.get(hostGroup.getId()).setEnvironmentId(envId);
break;
}
}
}
if (hostGroup.getPtable_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String ptableName = hg.getPtableName();
if (ptableName != null) {
int ptableId = hg.getPtableId();
hostGroups.get(hostGroup.getId()).setPtableName(ptableName);
hostGroups.get(hostGroup.getId()).setPtableId(ptableId);
break;
}
}
}
if (hostGroup.getArchitecture_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String archName = hg.getArchitectureName();
if (archName != null) {
int archId = hg.getArchitectureId();
hostGroups.get(hostGroup.getId()).setArchitectureName(archName);
hostGroups.get(hostGroup.getId()).setArchitectureId(archId);
break;
}
}
}
if (hostGroup.getOperatingsystem_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String osName = hg.getOperatingsystemName();
if (osName != null) {
int osId = hg.getOperatingsystemId();
hostGroups.get(hostGroup.getId()).setOperatingsystemName(osName);
hostGroups.get(hostGroup.getId()).setOperatingsystemId(osId);
break;
}
}
}
if (hostGroup.getDomain_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String domainName = hg.getDomainName();
if (domainName != null) {
int domainId = hg.getDomainId();
hostGroups.get(hostGroup.getId()).setDomainName(domainName);
hostGroups.get(hostGroup.getId()).setDomainId(domainId);
break;
}
}
}
if (hostGroup.getSubnet_name() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
String subnetName = hg.getSubnetName();
if (subnetName != null) {
int subnetId = hg.getSubnetId();
hostGroups.get(hostGroup.getId()).setSubnetName(subnetName);
hostGroups.get(hostGroup.getId()).setSubnetId(subnetId);
break;
}
}
}
if (hostGroup.getParameters() == null) {
for (int i = ancestries.length - 1; i >= 0; i
ExternalHostGroup hg = hostGroups.get(Integer.parseInt(ancestries[i]));
Map<String, String> parameters = hg.getParameters();
if (parameters != null) {
hostGroups.get(hostGroup.getId()).setParameters(parameters);
break;
}
}
}
}
ret.add(hostGroups.get(hostGroup.getId()));
}
return ret;
}
@Override
public List<VDS> getAll() {
return runHostListMethod(ALL_HOSTS_QUERY);
}
@Override
public List<VDS> getFiltered(String filter) {
return runHostListMethod(HOSTS_ENTRY_POINT + String.format(SEARCH_QUERY_FORMAT, filter));
}
@Override
public List<ExternalDiscoveredHost> getDiscoveredHosts() {
return runDiscoveredHostListMethod(DISCOVERED_HOSTS_ENTRY_POINT);
}
@Override
public List<ExternalHostGroup> getHostGroups() {
return runHostGroupListMethod(HOST_GROUPS_QUERY);
}
@Override
public List<ExternalComputeResource> getComputeResources() {
return runComputeResourceMethod(COMPUTE_RESOURCES_HOSTS_ENTRY_POINT);
}
private List<ExternalOperatingSystem> getOperationSystems() {
return runOperationSystemMethod(OPERATION_SYSTEM_QUERY);
}
@Override
public void provisionHost(VDS vds,
ExternalHostGroup hg,
ExternalComputeResource computeResource,
String mac,
String discoverName,
String rootPassword,
String ip) {
final String entityBody = "{\n" +
" \"discovered_host\": {\n" +
" \"name\": \"" + vds.getName() + "\",\n" +
" \"hostgroup_id\": \"" + hg.getHostgroupId() + "\",\n" +
" \"environment_id\": \"" + hg.getEnvironmentId() + "\",\n" +
" \"mac\": \"" + mac + "\",\n" +
" \"domain_id\": \"" + hg.getDomainId() + "\",\n" +
" \"subnet_id\": \"" + hg.getSubnetId() + "\",\n" +
" \"ip\": \"" + ip + "\",\n" +
" \"architecture_id\": \"" + hg.getArchitectureId() + "\",\n" +
" \"operatingsystem_id\": \"" + hg.getOperatingsystemId() + "\",\n" +
" \"medium_id\": \"" + hg.getMediumId() + "\",\n" +
" \"ptable_id\": \"" + hg.getPtableId() + "\",\n" +
" \"root_pass\": \"" + rootPassword + "\",\n" +
" \"host_parameters_attributes\": [\n" +
" {\n" +
" \"name\": \"host_ovirt_id\",\n" +
" \"value\": \"" + vds.getStaticData().getId() + "\",\n" +
" \"_destroy\": \"false\",\n" +
" \"nested\": \"\"\n" +
" },\n" +
" {\n" +
" \"name\": \"compute_resource_id\",\n" +
" \"value\": \"" + computeResource.getId() + "\",\n" +
" \"_destroy\": \"false\",\n" +
" \"nested\": \"\"\n" +
" },\n" +
" {\n" +
" \"name\": \"pass\",\n" +
" \"value\": \"" + CryptMD5.crypt(rootPassword) + "\",\n" +
" \"_destroy\": \"false\",\n" +
" \"nested\": \"\"\n" +
" },\n" +
" {\n" +
" \"name\": \"management\",\n" +
" \"value\": \"" + computeResource.getUrl().replaceAll("(http://|/api|/ovirt-engine)", "") + "\",\n" +
" \"_destroy\": \"false\",\n" +
" \"nested\": \"\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
runHttpMethod(
HttpMethodType.PUT,
"application/json; charset=utf-8",
DISCOVERED_HOSTS_ENTRY_POINT + "/" + discoverName,
entityBody
);
}
@Override
protected void afterReadResponse(HttpURLConnection connection, byte[] response) throws Exception {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
&& connection.getResponseCode() != HttpURLConnection.HTTP_MOVED_TEMP) {
ForemanErrorWrapper ferr = objectMapper.readValue(response, ForemanErrorWrapper.class);
String err = StringUtils.join(ferr.getForemanError().getFull_messages(), ", ");
throw new EngineException(EngineError.PROVIDER_FAILURE, err);
}
}
@Override
public void testConnection() {
runHttpGetMethod(API_ENTRY_POINT);
getDiscoveredHosts();
getHostGroups();
}
@Override
public void onAddition() {
}
@Override
public void onModification() {
}
@Override
public void onRemoval() {
}
@Override
public ContentHost findContentHost(String hostName) {
final String hostNameFact = "facts.network.hostname:" + hostName;
final List<ContentHost> contentHosts =
runContentHostListMethod(CONTENT_HOSTS_ENTRY_POINT + String.format(SEARCH_QUERY_FORMAT, hostNameFact));
if (contentHosts.isEmpty()) {
return null;
}
ContentHost latestRegisteredHost = contentHosts.get(0);
for (int i = 1; i < contentHosts.size(); i++) {
ContentHost candidateHost = contentHosts.get(i);
if (candidateHost.getCreated().after(latestRegisteredHost.getCreated())) {
latestRegisteredHost = candidateHost;
}
}
return latestRegisteredHost;
}
private List<ContentHost> runContentHostListMethod(String relativeUrl) {
try {
ContentHostsWrapper wrapper =
objectMapper.readValue(runHttpGetMethod(relativeUrl), ContentHostsWrapper.class);
return Arrays.asList(wrapper.getResults());
} catch (IOException e) {
return Collections.emptyList();
}
}
private List<Erratum> runErrataListMethod(String relativeUrl) {
try {
ErrataWrapper wrapper = objectMapper.readValue(runHttpGetMethod(relativeUrl), ErrataWrapper.class);
return mapErrata(Arrays.asList(wrapper.getResults()));
} catch (IOException e) {
return null;
}
}
private List<Erratum> mapErrata(List<ExternalErratum> externalErrata) {
ArrayList<Erratum> errata = new ArrayList<>(externalErrata.size());
for (ExternalErratum externalErratum : externalErrata) {
Erratum erratum = mapErratum(externalErratum);
errata.add(erratum);
}
return errata;
}
private Erratum mapErratum(ExternalErratum externalErratum) {
Erratum erratum = new Erratum();
erratum.setId(externalErratum.getId());
erratum.setIssued(externalErratum.getIssued());
erratum.setTitle(externalErratum.getTitle());
erratum.setSummary(externalErratum.getSummary());
erratum.setSolution(externalErratum.getSolution());
erratum.setDescription(externalErratum.getDescription());
erratum.setSeverity(ErrataSeverity.byDescription(externalErratum.getSeverity()));
erratum.setType(ErrataType.byDescription(externalErratum.getType()));
erratum.setPackages(Arrays.asList(externalErratum.getPackages()));
return erratum;
}
@Override
public List<Erratum> getErrataForHost(String hostName) {
ContentHost contentHost = findContentHost(hostName);
if (contentHost == null) {
log.error("Failed to find host on provider '{}' by host name '{}' ", getProvider().getName(), hostName);
return Collections.emptyList();
}
return runErrataListMethod(String.format(CONTENT_HOST_ERRATA_ENTRY_POINT, contentHost.getUuid()));
}
@Override
public Erratum getErratumForHost(String hostName, String erratumId) {
ContentHost contentHost = findContentHost(hostName);
if (contentHost == null) {
log.error("Failed to find host on provider '{}' by host name '{}' ", getProvider().getName(), hostName);
return null;
}
return runErratumMethod(String.format(CONTENT_HOST_ERRATUM_ENTRY_POINT, contentHost.getUuid(), erratumId));
}
private Erratum runErratumMethod(String relativeUrl) {
try {
ExternalErratum erratum = objectMapper.readValue(runHttpGetMethod(relativeUrl), ExternalErratum.class);
return mapErratum(erratum);
} catch (IOException e) {
return null;
}
}
}
|
package droplauncher.ini;
import adakite.debugging.Debugging;
import adakite.utils.AdakiteUtils;
import droplauncher.util.Constants;
import droplauncher.util.MemoryFile;
import droplauncher.util.Settings;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Logger;
public class IniFile {
private static final Logger LOGGER = Logger.getLogger(IniFile.class.getName());
private static final boolean CLASS_DEBUG = (Constants.DEBUG && true);
public static final String FILE_EXTENSION = ".ini";
public static final String VARIABLE_DELIMITER = "=";
public static final String COMMENT_DELIMITER = ";";
private MemoryFile memoryFile;
private Settings settings;
public IniFile() {
this.memoryFile = new MemoryFile();
this.settings = new Settings();
}
public Settings getSettings() {
return this.settings;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
public int getLineIndexByKey(String key) {
for (int i = 0; i < this.memoryFile.getLines().size(); i++) {
String line = this.memoryFile.getLines().get(i);
if (line.startsWith(key)
&& line.indexOf(VARIABLE_DELIMITER) < line.indexOf(key)) {
return i;
}
}
return -1;
}
public boolean open(File file) {
this.memoryFile.clear();
this.settings.clear();
if (file == null) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, Debugging.nullObject());
}
return false;
}
if (!this.memoryFile.open(file)) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, Debugging.openFail(file));
}
return false;
}
int index;
String key;
String val;
ArrayList<String> lines = this.memoryFile.getLines();
for (String line : lines) {
line = line.trim();
if (AdakiteUtils.isNullOrEmpty(line) || line.startsWith(COMMENT_DELIMITER)) {
continue;
}
index = line.indexOf(COMMENT_DELIMITER);
if (index >= 0) {
/* Ignore comments. */
line = line.substring(0, index);
}
index = line.indexOf(VARIABLE_DELIMITER);
if (index < 0) {
/* Skip line if the variable delimiter is not found. */
continue;
}
key = line.substring(0, index).trim();
val = line.substring(index + VARIABLE_DELIMITER.length(), line.length()).trim();
this.settings.setVariable(key, val);
System.out.println("Read variable: " + key + " = " + val);
}
return true;
}
public boolean refresh() {
return open(this.memoryFile.getFile());
}
public boolean setVariable(String key, String val, String comment) {
if (!this.settings.isVariableSet(key)) {
/* If the variable does not exist, do not add it since this code
does not handle sections yet. */
return false;
}
this.settings.setVariable(key, val);
int lineIndex = getLineIndexByKey(key);
int commentIndex;
String line = this.memoryFile.getLines().get(lineIndex);
String tmpComment;
if (comment != null) {
if (comment.length() > 0) {
tmpComment = " " + COMMENT_DELIMITER + " " + comment;
} else {
tmpComment = "";
}
} else if ((commentIndex = line.indexOf(COMMENT_DELIMITER)) >= 0) {
tmpComment = " " + line.substring(commentIndex, line.length());
} else {
tmpComment = "";
}
String entry = key + " " + VARIABLE_DELIMITER + " " + val + tmpComment;
this.memoryFile.getLines().set(lineIndex, entry);
this.memoryFile.dumpToFile();
refresh();
return true;
}
public boolean setVariable(String key, String val) {
return setVariable(key, val, null);
}
public boolean enableVariable(String key) {
if (this.settings.isVariableSet(key)) {
return true;
}
for (int i = 0; i < this.memoryFile.getLines().size(); i++) {
String line = this.memoryFile.getLines().get(i);
if (line.contains(COMMENT_DELIMITER)
&& line.contains(key)
&& line.contains(VARIABLE_DELIMITER)
&& line.indexOf(COMMENT_DELIMITER) < line.indexOf(key)
&& line.indexOf(key) < line.indexOf(VARIABLE_DELIMITER)) {
int commentIndex = line.indexOf(COMMENT_DELIMITER);
line = line.substring(commentIndex + COMMENT_DELIMITER.length(), line.length()).trim();
this.memoryFile.getLines().set(i, line);
this.memoryFile.dumpToFile();
refresh();
return true;
}
}
return false;
}
public void disableVariable(String key) {
if (!this.settings.isVariableSet(key)) {
/* Return if the variable is not set/found. */
return;
}
int lineIndex = getLineIndexByKey(key);
if (lineIndex < 0) {
if (CLASS_DEBUG) {
/* The lineIndex should always be greater than 0 if
"isVariableSet" is functioning properly. */
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, "should not see this logic error");
}
return;
}
String line = this.memoryFile.getLines().get(lineIndex);
line = COMMENT_DELIMITER + line;
this.memoryFile.getLines().set(lineIndex, line);
this.memoryFile.dumpToFile();
this.settings.getVariables().remove(key);
refresh();
}
}
|
package org.ovirt.engine.core.dal.dbbroker.auditloghandling;
import static org.mockito.Mockito.RETURNS_DEFAULTS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class AuditLogDirectorTest {
@Test
public void testResolveUnknownVariable() {
final String message = "This is my ${Variable}";
final String expectedResolved = String.format("This is my %1s", AuditLogDirector.UNKNOWN_VARIABLE_VALUE);
Map<String, String> values = Collections.emptyMap();
String resolvedMessage = AuditLogDirector.resolveMessage(message, values);
Assert.assertEquals(expectedResolved, resolvedMessage);
}
@Test
public void testResolveKnownVariable() {
final String message = "This is my ${Variable}";
final String expectedResolved = "This is my value";
Map<String, String> values = Collections.singletonMap("variable", "value");
String resolvedMessage = AuditLogDirector.resolveMessage(message, values);
Assert.assertEquals(expectedResolved, resolvedMessage);
}
@Test
public void testResolveCombinedMessage() {
final String message =
"${first} equals one, ${second} equals two, '${blank}' equals blank and ${nonExist} is unknown";
final String expectedResolved =
String.format("one equals one, two equals two, ' ' equals blank and %1s is unknown",
AuditLogDirector.UNKNOWN_VARIABLE_VALUE);
Map<String, String> values = new HashMap<String, String>();
values.put("first", "one");
values.put("second", "two");
values.put("blank", " ");
String resolvedMessage = AuditLogDirector.resolveMessage(message, values);
Assert.assertEquals(expectedResolved, resolvedMessage);
}
@Test
public void testResolveAuditLogableBase() {
final String vdsName = "TestVDS";
final String vmName = "TestVM";
final String message =
"The VM name is ${vmName}, the VDS name is ${vdsName} and the template name is ${vmTemplateName}";
final String expectedResolved =
String.format("The VM name is %1s, the VDS name is %2s and the template name is %3s",
vmName,
vdsName,
AuditLogDirector.UNKNOWN_VARIABLE_VALUE);
AuditLogableBase logable = mock(AuditLogableBase.class, RETURNS_DEFAULTS);
when(logable.getVdsName()).thenReturn("TestVDS");
when(logable.getVmName()).thenReturn("TestVM");
String resolvedMessage = AuditLogDirector.resolveMessage(message, logable);
Assert.assertEquals(expectedResolved, resolvedMessage);
}
}
|
package org.bitrepository.integrityservice.workflow.step;
import org.bitrepository.access.ContributorQuery;
import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE;
import org.bitrepository.client.eventhandler.OperationEvent;
import org.bitrepository.client.eventhandler.OperationEvent.OperationEventType;
import org.bitrepository.client.eventhandler.OperationFailedEvent;
import org.bitrepository.common.settings.Settings;
import org.bitrepository.common.utils.SettingsUtils;
import org.bitrepository.integrityservice.alerter.IntegrityAlerter;
import org.bitrepository.integrityservice.cache.IntegrityModel;
import org.bitrepository.integrityservice.collector.IntegrityCollectorEventHandler;
import org.bitrepository.integrityservice.collector.IntegrityInformationCollector;
import org.bitrepository.integrityservice.workflow.IntegrityContributors;
import org.bitrepository.service.exception.WorkflowAbortedException;
import org.bitrepository.service.workflow.AbstractWorkFlowStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* The step for collecting the checksums of all files from all pillars.
*/
public abstract class UpdateChecksumsStep extends AbstractWorkFlowStep {
private final Logger log = LoggerFactory.getLogger(getClass());
private final IntegrityInformationCollector collector;
protected final IntegrityModel store;
private final ChecksumSpecTYPE checksumType;
private final IntegrityAlerter alerter;
private final Duration timeout;
private final Integer maxNumberOfResultsPerConversation;
protected final String collectionID;
private boolean abortInCaseOfFailure = true;
private final IntegrityContributors integrityContributors;
/**
* @param collector The client for collecting the checksums.
* @param store The storage for the integrity data.
* @param alerter The alerter for sending failures.
* @param checksumType The type of checksum to collect.
*/
public UpdateChecksumsStep(IntegrityInformationCollector collector, IntegrityModel store, IntegrityAlerter alerter,
ChecksumSpecTYPE checksumType, Settings settings, String collectionID,
IntegrityContributors integrityContributors) {
this.collector = collector;
this.store = store;
this.checksumType = checksumType;
this.alerter = alerter;
this.collectionID = collectionID;
this.integrityContributors = integrityContributors;
this.timeout = settings.getIdentificationTimeout().plus(settings.getOperationTimeout());
this.maxNumberOfResultsPerConversation = SettingsUtils.getMaxClientPageSize();
if (settings.getReferenceSettings().getIntegrityServiceSettings().isSetAbortOnFailedContributor()) {
abortInCaseOfFailure = settings.getReferenceSettings().getIntegrityServiceSettings().isAbortOnFailedContributor();
}
}
/**
* Method to implement early/pre-performStep action
*/
protected void initialStepAction() {}
/**
* Method to implement late/post-perform actions.
*/
protected void finalStepAction() {}
@Override
public synchronized void performStep() throws WorkflowAbortedException {
try {
initialStepAction();
Set<String> pillarsToCollectFrom = integrityContributors.getActiveContributors();
log.debug("Collecting checksums from '" + pillarsToCollectFrom + "' for collection '" + collectionID + "'.");
while (!pillarsToCollectFrom.isEmpty()) {
IntegrityCollectorEventHandler eventHandler = new IntegrityCollectorEventHandler(store, timeout, integrityContributors);
ContributorQuery[] queries = getQueries(pillarsToCollectFrom);
collector.getChecksums(collectionID, pillarsToCollectFrom, checksumType, null, "IntegrityService: " + getName(), queries,
eventHandler);
OperationEvent event = eventHandler.getFinish();
if (event.getEventType() == OperationEventType.FAILED) {
handleFailureEvent(event);
}
log.debug("Collecting of checksums ids had the final event: " + event);
pillarsToCollectFrom = integrityContributors.getActiveContributors();
}
finalStepAction();
} catch (InterruptedException e) {
log.warn("Interrupted while collecting checksums.", e);
}
}
/**
* Handle a failure event. This includes checking if any contributors have failed (if not just retry),
* checking to see if the workflow should be aborted, and sending alarms if needed.
*/
private void handleFailureEvent(OperationEvent event) throws WorkflowAbortedException {
if (integrityContributors.getFailedContributors().isEmpty()) {
log.info("Get failure event, but no contributors marked as failed, retrying");
} else {
OperationFailedEvent ofe = (OperationFailedEvent) event;
if (abortInCaseOfFailure) {
alerter.integrityFailed("Integrity check aborted while getting checksums due to failed contributors: " +
integrityContributors.getFailedContributors(), collectionID);
throw new WorkflowAbortedException("Aborting workflow due to failure collecting checksums. " + "Cause: " + ofe.toString());
} else {
log.info("Failure occurred collecting fileIDs, continuing collecting checksums. Failure {}", ofe.toString());
alerter.integrityFailed("Failure while collecting checksums, the check will continue " +
"with the information available. The failed contributors were: " + integrityContributors.getFailedContributors(),
collectionID);
}
}
}
/**
* Define the queries for the collection of FileIDs for the given pillars.
*
* @param pillars The pillars to collect from.
* @return The queries for the pillars for collecting the file ids.
*/
private ContributorQuery[] getQueries(Collection<String> pillars) {
List<ContributorQuery> res = new ArrayList<>();
for (String pillar : pillars) {
Date latestChecksumEntry = store.getDateForNewestChecksumEntryForPillar(pillar, collectionID);
res.add(new ContributorQuery(pillar, latestChecksumEntry, null, maxNumberOfResultsPerConversation));
}
return res.toArray(new ContributorQuery[pillars.size()]);
}
}
|
package com.adobe.granite.ide.eclipse.ui.wizards.np;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.sling.ide.eclipse.core.ISlingLaunchpadServer;
import org.apache.sling.ide.eclipse.ui.wizards.MavenHelper;
import org.apache.sling.ide.eclipse.ui.wizards.np.AbstractNewSlingApplicationWizard;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.wst.server.core.IServer;
import com.adobe.granite.ide.eclipse.ui.internal.SharedImages;
public class NewGraniteProjectWizard extends AbstractNewSlingApplicationWizard {
public NewGraniteProjectWizard() {
// TODO Auto-generated constructor stub
}
@Override
public ImageDescriptor getLogo() {
return SharedImages.GRANITE_MEDIUM_LOGO;
}
@Override
public String doGetWindowTitle() {
return "Create new Adobe Granite application";
}
@Override
public boolean acceptsArchetype(Archetype archetype2) {
return (archetype2.getArtifactId().startsWith("com.adobe.granite") ||
archetype2.getGroupId().startsWith("com.adobe.granite") );
}
private IProject getParentProject(List<IProject> projects) {
for (Iterator<IProject> it = projects.iterator(); it.hasNext();) {
IProject project = it.next();
Model mavenModel = MavenHelper.getMavenModel(project);
if (mavenModel==null) {
continue;
}
if ("pom".equals(mavenModel.getPackaging()) && "parent".equals(mavenModel.getArtifactId())) {
return project;
}
}
return null;
}
private String calculateRelativePath(IProject from, IProject to) {
IPath fromPath = from.getRawLocation();
IPath toPath = to.getRawLocation();
int ssc = fromPath.matchingFirstSegments(toPath);
fromPath = fromPath.removeFirstSegments(ssc);
toPath = toPath.removeFirstSegments(ssc);
StringBuffer relPath = new StringBuffer();
for(int i=0; i<fromPath.segmentCount(); i++) {
if (relPath.length()!=0) {
relPath.append("/");
}
relPath.append("..");
}
if (relPath.length()!=0) {
relPath.append("/");
}
relPath.append(toPath.toString());
return relPath.toString();
}
private void fixParentProject(IProject p, IProject parentProject)
throws CoreException {
IFile existingPom = p.getFile("pom.xml");
Model model = MavenPlugin.getMavenModelManager().readMavenModel(existingPom);
Model parent = MavenPlugin.getMavenModelManager().readMavenModel(parentProject.getFile("pom.xml"));
//Parent oldParent = model.getParent();
Parent newParent = new Parent();
newParent.setGroupId(parent.getGroupId());
newParent.setArtifactId(parent.getArtifactId());
newParent.setRelativePath(calculateRelativePath(p, parentProject));
newParent.setVersion(parent.getVersion());
model.setParent(newParent);
existingPom.delete(true, false, null);
MavenPlugin.getMavenModelManager().createMavenModel(p.getFile("pom.xml"), model);
}
@Override
protected void configureContentProject(IProject aContentProject,
List<IProject> projects, IProgressMonitor monitor)
throws CoreException{
IProject parentProject = getParentProject(projects);
if (parentProject!=null) {
fixParentProject(aContentProject, parentProject);
}
super.configureContentProject(aContentProject, projects, monitor);
}
@Override
protected void configureBundleProject(IProject aBundleProject,
List<IProject> projects, IProgressMonitor monitor)
throws CoreException {
IProject parentProject = getParentProject(projects);
if (parentProject!=null) {
fixParentProject(aBundleProject, parentProject);
}
super.configureBundleProject(aBundleProject, projects, monitor);
}
@Override
protected void finishConfiguration(List<IProject> projects, IServer server,
IProgressMonitor monitor) throws CoreException {
IProject parentProject = getParentProject(projects);
if (parentProject!=null) {
// set granite.host and granite.port
IFile existingPom = parentProject.getFile("pom.xml");
Model model = MavenPlugin.getMavenModelManager().readMavenModel(existingPom);
Properties props = model.getProperties();
props.put("granite.host", server.getHost());
props.put("granite.port", String.valueOf(server.getAttribute(ISlingLaunchpadServer.PROP_PORT, 4502)));
existingPom.delete(true, false, null);
MavenPlugin.getMavenModelManager().createMavenModel(parentProject.getFile("pom.xml"), model);
}
super.finishConfiguration(projects, server, monitor);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.