diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/Test.java b/src/Test.java
index cfb4bec..859c8b4 100644
--- a/src/Test.java
+++ b/src/Test.java
@@ -1,86 +1,86 @@
import com.williballenthin.rejistry.Cell;
import com.williballenthin.rejistry.HBIN;
import com.williballenthin.rejistry.RegistryHiveFile;
import com.williballenthin.rejistry.RegistryParseException;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Iterator;
public class Test {
/**
* This is silly, but it formats the same way Python does by default.
* @param b
* @return
*/
private static String getBooleanString(boolean b) {
if (b) {
return "True";
} else {
return "False";
}
}
private static DateFormat isoformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
private static String getDatetimeString(GregorianCalendar c) {
return isoformat.format(c.getTime());
}
/**
* @param args
* @throws IOException
* @throws RegistryParseException
*/
public static void main(String[] args) throws IOException, RegistryParseException {
File f = new File(args[0]);
RegistryHiveFile reg = new RegistryHiveFile(f);
System.out.println("hive name: " + reg.getHeader().getHiveName());
System.out.println("major version: " + reg.getHeader().getMajorVersion());
System.out.println("minor version: " + reg.getHeader().getMinorVersion());
int count = 0;
for (Iterator<HBIN> it = reg.getHeader().getHBINs(); it.hasNext(); it.next()) {
count++;
}
System.out.println("number of hbins: " + count);
System.out.println("last hbin offset: " + reg.getHeader().getLastHbinOffset());
int i = 0;
Iterator<HBIN> it = reg.getHeader().getHBINs();
while (it.hasNext()) {
HBIN hbin = it.next();
System.out.println("hbin " + i + ", relative offset first hbin: " + hbin.getRelativeOffsetFirstHBIN());
System.out.println("hbin " + i + ", relative offset next hbin: " + hbin.getRelativeOffsetNextHBIN());
int j = 0;
Iterator<Cell> ic = hbin.getCells();
while (ic.hasNext()) {
Cell cell = ic.next();
if (cell.isActive()) {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: yes");
} else {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: no");
}
System.out.println("hbin " + i + ", cell " + j + ", length: " + cell.getLength());
j++;
}
i++;
//break; // TODO(wb): removeme
}
System.out.println("root nkrecord has classname: " + getBooleanString(reg.getHeader().getRootNKRecord().hasClassname()));
System.out.println("root nkrecord classname: " + reg.getHeader().getRootNKRecord().getClassname());
System.out.println("root nkrecord timestamp: " + getDatetimeString(reg.getHeader().getRootNKRecord().getTimestamp()));
System.out.println("root nkrecord is root: " + getBooleanString(reg.getHeader().getRootNKRecord().isRootKey()));
System.out.println("root nkrecord name: " + reg.getHeader().getRootNKRecord().getName());
System.out.println("root nkrecord has parent: " + getBooleanString(reg.getHeader().getRootNKRecord().hasParentRecord()));
System.out.println("root nkrecord number of values: " + reg.getHeader().getRootNKRecord().getNumberOfValues());
- System.out.println("root nkrecord number of subkeys: " + reg.getHeader().getRootNKRecord().getNumberOfSubkeys());
+ System.out.println("root nkrecord number of subkeys: " + reg.getHeader().getRootNKRecord().getSubkeyCount());
}
}
| true | true | public static void main(String[] args) throws IOException, RegistryParseException {
File f = new File(args[0]);
RegistryHiveFile reg = new RegistryHiveFile(f);
System.out.println("hive name: " + reg.getHeader().getHiveName());
System.out.println("major version: " + reg.getHeader().getMajorVersion());
System.out.println("minor version: " + reg.getHeader().getMinorVersion());
int count = 0;
for (Iterator<HBIN> it = reg.getHeader().getHBINs(); it.hasNext(); it.next()) {
count++;
}
System.out.println("number of hbins: " + count);
System.out.println("last hbin offset: " + reg.getHeader().getLastHbinOffset());
int i = 0;
Iterator<HBIN> it = reg.getHeader().getHBINs();
while (it.hasNext()) {
HBIN hbin = it.next();
System.out.println("hbin " + i + ", relative offset first hbin: " + hbin.getRelativeOffsetFirstHBIN());
System.out.println("hbin " + i + ", relative offset next hbin: " + hbin.getRelativeOffsetNextHBIN());
int j = 0;
Iterator<Cell> ic = hbin.getCells();
while (ic.hasNext()) {
Cell cell = ic.next();
if (cell.isActive()) {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: yes");
} else {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: no");
}
System.out.println("hbin " + i + ", cell " + j + ", length: " + cell.getLength());
j++;
}
i++;
//break; // TODO(wb): removeme
}
System.out.println("root nkrecord has classname: " + getBooleanString(reg.getHeader().getRootNKRecord().hasClassname()));
System.out.println("root nkrecord classname: " + reg.getHeader().getRootNKRecord().getClassname());
System.out.println("root nkrecord timestamp: " + getDatetimeString(reg.getHeader().getRootNKRecord().getTimestamp()));
System.out.println("root nkrecord is root: " + getBooleanString(reg.getHeader().getRootNKRecord().isRootKey()));
System.out.println("root nkrecord name: " + reg.getHeader().getRootNKRecord().getName());
System.out.println("root nkrecord has parent: " + getBooleanString(reg.getHeader().getRootNKRecord().hasParentRecord()));
System.out.println("root nkrecord number of values: " + reg.getHeader().getRootNKRecord().getNumberOfValues());
System.out.println("root nkrecord number of subkeys: " + reg.getHeader().getRootNKRecord().getNumberOfSubkeys());
}
| public static void main(String[] args) throws IOException, RegistryParseException {
File f = new File(args[0]);
RegistryHiveFile reg = new RegistryHiveFile(f);
System.out.println("hive name: " + reg.getHeader().getHiveName());
System.out.println("major version: " + reg.getHeader().getMajorVersion());
System.out.println("minor version: " + reg.getHeader().getMinorVersion());
int count = 0;
for (Iterator<HBIN> it = reg.getHeader().getHBINs(); it.hasNext(); it.next()) {
count++;
}
System.out.println("number of hbins: " + count);
System.out.println("last hbin offset: " + reg.getHeader().getLastHbinOffset());
int i = 0;
Iterator<HBIN> it = reg.getHeader().getHBINs();
while (it.hasNext()) {
HBIN hbin = it.next();
System.out.println("hbin " + i + ", relative offset first hbin: " + hbin.getRelativeOffsetFirstHBIN());
System.out.println("hbin " + i + ", relative offset next hbin: " + hbin.getRelativeOffsetNextHBIN());
int j = 0;
Iterator<Cell> ic = hbin.getCells();
while (ic.hasNext()) {
Cell cell = ic.next();
if (cell.isActive()) {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: yes");
} else {
System.out.println("hbin " + i + ", cell " + j + ", is allocated: no");
}
System.out.println("hbin " + i + ", cell " + j + ", length: " + cell.getLength());
j++;
}
i++;
//break; // TODO(wb): removeme
}
System.out.println("root nkrecord has classname: " + getBooleanString(reg.getHeader().getRootNKRecord().hasClassname()));
System.out.println("root nkrecord classname: " + reg.getHeader().getRootNKRecord().getClassname());
System.out.println("root nkrecord timestamp: " + getDatetimeString(reg.getHeader().getRootNKRecord().getTimestamp()));
System.out.println("root nkrecord is root: " + getBooleanString(reg.getHeader().getRootNKRecord().isRootKey()));
System.out.println("root nkrecord name: " + reg.getHeader().getRootNKRecord().getName());
System.out.println("root nkrecord has parent: " + getBooleanString(reg.getHeader().getRootNKRecord().hasParentRecord()));
System.out.println("root nkrecord number of values: " + reg.getHeader().getRootNKRecord().getNumberOfValues());
System.out.println("root nkrecord number of subkeys: " + reg.getHeader().getRootNKRecord().getSubkeyCount());
}
|
diff --git a/src/ch/jachen/dev/flickr/Syno2Flickr.java b/src/ch/jachen/dev/flickr/Syno2Flickr.java
index 5186073..28d8adb 100644
--- a/src/ch/jachen/dev/flickr/Syno2Flickr.java
+++ b/src/ch/jachen/dev/flickr/Syno2Flickr.java
@@ -1,467 +1,467 @@
package ch.jachen.dev.flickr;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import org.jickr.Auth;
import org.jickr.Flickr;
import org.jickr.FlickrException;
import org.jickr.MimeType;
import org.jickr.Permission;
import org.jickr.Photo;
import org.jickr.PhotoSet;
import org.jickr.PhotoUpload;
import org.jickr.Privacy;
import org.jickr.RequestEvent;
import org.jickr.RequestListener;
import org.jickr.User;
import org.jickr.UserLimitations;
/**
* Class to animate progress uploading in Console output
* @author jbrek
*
*/
class ProgressUpload extends Thread{
private final double progress;
private final double total;
private boolean stop=false;
private boolean interrupt=false;
private static long calls = 0;
public ProgressUpload(double progress, double total) {
this.progress = progress;
this.total = total;
}
private final static int width = 50; // progress bar width in chars
private final static char[] animationChars = new char[] { '-', '\\', '|', '/' };
/**
* Show progress of upload in Console
* @param progress progress in bytes
* @param total total in bytes
* @param finished is the progress finished
*/
public static void showProgress(double progress, double total, boolean finished){
double progressPercentage = progress / total;
synchronized (System.out) {
System.out.print("\rProcessing: |");
int i = 0;
int max = 0;
for (; i <= (max = (int) (progressPercentage * width)); i++) {
System.out.print(((i < max || finished) ? "="
: animationChars[(int)(calls++ % 4)]));
}
for (; i <= width; i++) {
System.out.print(" ");
}
System.out.print("| "
+ String.format("%3d", (finished ? 100 : progressPercentage==1?99:(int) (progressPercentage * 100)))
+ "% (" + String.format("%.1fMB/%.1fMB", progress/(1024*1024), total/(1024*1024)) + ")");
}
}
/**
* Stop thread
* Ends animation progress and show total progress
*/
public void stopRun(){
stop = true;
}
/**
* Interrupt thread
* Ends animation progress wihtout output
*/
public void interruptRun(){
interrupt = true;
}
@Override
public void run() {
// Update progress
while(!stop && !interrupt){
// Show animation
showProgress(progress, total, false);
try {
Thread.sleep(200);
} catch (InterruptedException e) { }
}
// If process finished but not interrupted
if (!interrupt && progress==total)
showProgress(total, total, true);
}
}
/**
* Main class
*
* @author jbrek
*
*/
public class Syno2Flickr {
/**
* Progress bar for console output
* @param progressPercentage progress (0.0. to 1.0)
*/
private static Stack<Thread> progressList = new Stack<Thread>();
private static void stopAllThreads(){
while(!progressList.empty()){
ProgressUpload p = (ProgressUpload) progressList.pop();
p.stopRun();
}
}
/**
* Interrupt all threads
* Interrupt animation (used in error/exception case)
*/
private static void interruptAllThreads(){
while(!progressList.empty()){
ProgressUpload p = (ProgressUpload) progressList.pop();
p.interruptRun();
}
}
/**
* Authentication to flickr
* Authenticates to flickr and register this app to the flickr account if needed
*
* @param user
* @param perm
*/
private static User authenticationToFlickr(User user, Permission perm){
// Establish Flickr auth. or ask permission to
try {
user = Auth.getDefaultAuthUser(); // Check to see if we've already
// authenticated
} catch (FlickrException e1) {
user = null;
}
try {
// if need to authenticated
if (user == null || !Auth.isAuthenticated(user, perm)) {
// Give the URL to enter in the browser
System.out
.println("Please enter the following URL into a browser, "
+ "follow the instructions, and then come back");
String authURL = Auth.getAuthURL(perm);
System.out.println(authURL);
// Wait for them to come back
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
in.readLine();
// Alright, now that we're cleared with Flickr, let's try to
// authenticate
System.out.println("Trying to get " + perm + " access.");
try {
user = Auth.authenticate();
} catch (FlickrException ex) {
System.out.println("Failure to authenticate.");
System.exit(1);
}
if (Auth.isAuthenticated(user, perm)) {
System.out.println("We're authenticated with "
+ Auth.getPermLevel(user) + " access.");
Auth.setDefaultAuthUser(user);
} else {
// Shouldn't ever get here - we throw an exception above if
// we
// can't authenticate.
System.out.println("Oddly unauthenticated");
System.exit(2);
}
} // if (user == null || !Auth.isAuthenticated(user, perm)) {
} catch (FlickrException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
} catch (IOException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
}
// Set authentication context for user (credentials)
Auth.resetAuthContext();
Auth.setAuthContext(user);
try {
user = User.findByNSID(user.getNSID());
} catch (FlickrException e) {
System.out.println("Error: can't retrieve user NSID: "+user.getNSID());
}
// Show infos
System.out.println("\n\nHello "+user.getRealName());
System.out.println("\tYou have " +user.getPhotoCount()+" photos");
return user;
}
/**
* Welcome message
*/
public static void printWelcome(){
System.out.println("**********************************************************************");
- System.out.println("* Syno2Flickr v0.1.1 07/2013 *");
+ System.out.println("* Syno2Flickr v0.1.2 07/2013 *");
System.out.println("* *");
System.out.println("**********************************************************************");
}
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
// Initialization
String syncFolder = null; // folder to upload
String archiveFolderString = null; // archive folder
String defaultSetId = null; // id of default set for new photos
Privacy defaultPrivacy = null; // default privacy
org.jickr.Permission perm = Permission.WRITE; // access level we want
org.jickr.User user = null; // User Flickr authenticated
// Welcome
printWelcome();
// Get property values
try {
// Test first arg (must be the path of the properties file)
if (args != null && args.length > 0)
if (new File(args[0]).exists())
Syno2FlickrProperties.setPropertyFile(args[0]);
// Set key/secret
Flickr.setApiKey(Syno2FlickrProperties.getApiKey());
Flickr.setSharedSecret(Syno2FlickrProperties.getSharedSecret());
// Get folder to sync
syncFolder = Syno2FlickrProperties.getFolderToSync();
// Archive folder
archiveFolderString = Syno2FlickrProperties.getArchiveFolder();
// Default set id
defaultSetId = Syno2FlickrProperties.getDefaultSetId();
// Default privacy
String privacyString = Syno2FlickrProperties.getDefaultPrivacy();
defaultPrivacy = Privacy.valueOf(Integer.parseInt(privacyString));
} catch (Syno2FlickrException e) {
// Error message
System.out.println(e.getMessage());
System.exit(0);
} catch (NumberFormatException e){
// Error while getting the default privacy
System.out.println("Error while getting default privacy, value must be between 0 and 4. Default privacy will be set to private");
defaultPrivacy = Privacy.PRIVATE;
}
// Auth
user = authenticationToFlickr(user, perm);
// Check default set
PhotoSet defaultSet=null;
try {
defaultSet = PhotoSet.findByID(defaultSetId);
} catch (FlickrException e3) {}
// Show params
System.out.println("\n\nParameters:");
System.out.println("\tSync folder: "+syncFolder);
System.out.println("\tArchive folder: "+archiveFolderString);
if(defaultSet!=null)
System.out.println("\tDefault Set: "+defaultSet.getTitle());
else
System.out.println("\tDefault Set: none");
System.out.println("\tDefault privacy: "+defaultPrivacy);
// Get user upload limitations
UserLimitations userLimits = new UserLimitations();
// Show limit / usage
try {
System.out.println("\n\n"+userLimits.showUsageAndLimitations());
} catch (FlickrException e2) {
System.out.println("Error: impossible to show usage and restrictions for user "+user.getUserName()+"\n"+e2.getMessage());
}
// Sync folder
File folder = new File(syncFolder);
// Check upload folder
if (!folder.exists()){
System.out.println("Error: sync folder does not exist ("+folder.getPath()+"). Please verify the syno2flickr.properties config file.");
System.exit(0);
}
// List files to upload
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
try {
return !pathname.isDirectory() && !pathname.isHidden();
} catch (Exception e) {
return false;
}
}
});
// Show nb files founds
System.out.println("\nStart uploading: "+listOfFiles.length+ " files found to upload");
// Synchronize (upload photos/video)
long denomMega=1024L*1024L;
File archiveFolder = new File(archiveFolderString);
// Check archive folder folder
if (!archiveFolder.exists()){
System.out.println("Warning: archive folder does not exist ("+archiveFolder.getPath()+").");
}
int noFile = 0;
try {
// Get bandwith remaining
long bandwidthRemaingBytes = userLimits.getBandwidthRemainingBytes();
for (File f : listOfFiles) {
// init
//ProgressUpload.calls = 0;
noFile++;
// Check limitations/file type
if(!userLimits.isBandwidthUnlimited() && (bandwidthRemaingBytes-f.length()) < 0){
System.out.println("Error: user " + user.getUserName() +
" has reached his monthly bandwidth limit ("+
userLimits.getBandwidthMaxBytes()/denomMega+
"MB). Upload cancelled.");
break;
}
String mime=null;
try {
mime = MimeType.getMimeType("file://"+f.getPath());
} catch (IOException e1) {}
if (mime!=null && mime.contains("image")) {
if (f.length() > userLimits.getFilesizeMaxBytes()){
System.out.println("Error: image " + f.getName()+ " exceeds the maximum accepted size (max. "+
userLimits.getFilesizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
} else {
if (f.length() > userLimits.getVideosizeMaxBytes()){
System.out.println("Error: " + f.getName()+
" exceeds the maximum accepted size (max. "+
userLimits.getVideosizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
}
// Info
System.out.println("\nSending "+f.getName()+ " ("+noFile+"/"+listOfFiles.length+")");
// Generate metadata for the upload
PhotoUpload uploader = new PhotoUpload.Builder(f)
.familyFlag(defaultPrivacy.equals(Privacy.FAMILY) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.friendFlag(defaultPrivacy.equals(Privacy.FRIENDS) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.publicFlag(defaultPrivacy.equals(Privacy.PUBLIC))
.build();
try {
// Upload the content
String id;
id = Photo.uploadNewPhoto(uploader, new RequestListener() {
@Override
public void progressRequest(RequestEvent event) {
stopAllThreads();
ProgressUpload r = new ProgressUpload(event.getProgress(), event.getTotalProgress());
progressList.push(r);
r.start();
}
});
// Stop all threads
stopAllThreads();
// Put in default set
if (defaultSet!=null){
try {
defaultSet.add(id);
} catch(FlickrException e){
System.out.println("Error while adding photo (id: "+id+") to set (id: "+defaultSet.getID()+").\n"+e.getMessage());
}
}
// Move uploaded file to archive
if (archiveFolder.exists()){
f.renameTo(new File( archiveFolder.getPath()+File.separator+f.getName()));
}
if (!userLimits.isBandwidthUnlimited()) bandwidthRemaingBytes-=f.length();
} catch (FlickrException e) {
interruptAllThreads();
System.out.println("\nERROR: An error occured while uploading file "
+ f.getPath()+":\n"+e.getMessage());
if (e.getCode()==6 || e.getCode()==-999) break;
}
}
} catch (FlickrException e){
System.out.println("\nA grave error occurs:\n"+e.getMessage());
}
// Summary and notify
try { Thread.sleep(500); } catch (InterruptedException e) {}
System.out.println("\n\nSend completed.\nBye.");
}
}
| true | true | private static User authenticationToFlickr(User user, Permission perm){
// Establish Flickr auth. or ask permission to
try {
user = Auth.getDefaultAuthUser(); // Check to see if we've already
// authenticated
} catch (FlickrException e1) {
user = null;
}
try {
// if need to authenticated
if (user == null || !Auth.isAuthenticated(user, perm)) {
// Give the URL to enter in the browser
System.out
.println("Please enter the following URL into a browser, "
+ "follow the instructions, and then come back");
String authURL = Auth.getAuthURL(perm);
System.out.println(authURL);
// Wait for them to come back
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
in.readLine();
// Alright, now that we're cleared with Flickr, let's try to
// authenticate
System.out.println("Trying to get " + perm + " access.");
try {
user = Auth.authenticate();
} catch (FlickrException ex) {
System.out.println("Failure to authenticate.");
System.exit(1);
}
if (Auth.isAuthenticated(user, perm)) {
System.out.println("We're authenticated with "
+ Auth.getPermLevel(user) + " access.");
Auth.setDefaultAuthUser(user);
} else {
// Shouldn't ever get here - we throw an exception above if
// we
// can't authenticate.
System.out.println("Oddly unauthenticated");
System.exit(2);
}
} // if (user == null || !Auth.isAuthenticated(user, perm)) {
} catch (FlickrException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
} catch (IOException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
}
// Set authentication context for user (credentials)
Auth.resetAuthContext();
Auth.setAuthContext(user);
try {
user = User.findByNSID(user.getNSID());
} catch (FlickrException e) {
System.out.println("Error: can't retrieve user NSID: "+user.getNSID());
}
// Show infos
System.out.println("\n\nHello "+user.getRealName());
System.out.println("\tYou have " +user.getPhotoCount()+" photos");
return user;
}
/**
* Welcome message
*/
public static void printWelcome(){
System.out.println("**********************************************************************");
System.out.println("* Syno2Flickr v0.1.1 07/2013 *");
System.out.println("* *");
System.out.println("**********************************************************************");
}
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
// Initialization
String syncFolder = null; // folder to upload
String archiveFolderString = null; // archive folder
String defaultSetId = null; // id of default set for new photos
Privacy defaultPrivacy = null; // default privacy
org.jickr.Permission perm = Permission.WRITE; // access level we want
org.jickr.User user = null; // User Flickr authenticated
// Welcome
printWelcome();
// Get property values
try {
// Test first arg (must be the path of the properties file)
if (args != null && args.length > 0)
if (new File(args[0]).exists())
Syno2FlickrProperties.setPropertyFile(args[0]);
// Set key/secret
Flickr.setApiKey(Syno2FlickrProperties.getApiKey());
Flickr.setSharedSecret(Syno2FlickrProperties.getSharedSecret());
// Get folder to sync
syncFolder = Syno2FlickrProperties.getFolderToSync();
// Archive folder
archiveFolderString = Syno2FlickrProperties.getArchiveFolder();
// Default set id
defaultSetId = Syno2FlickrProperties.getDefaultSetId();
// Default privacy
String privacyString = Syno2FlickrProperties.getDefaultPrivacy();
defaultPrivacy = Privacy.valueOf(Integer.parseInt(privacyString));
} catch (Syno2FlickrException e) {
// Error message
System.out.println(e.getMessage());
System.exit(0);
} catch (NumberFormatException e){
// Error while getting the default privacy
System.out.println("Error while getting default privacy, value must be between 0 and 4. Default privacy will be set to private");
defaultPrivacy = Privacy.PRIVATE;
}
// Auth
user = authenticationToFlickr(user, perm);
// Check default set
PhotoSet defaultSet=null;
try {
defaultSet = PhotoSet.findByID(defaultSetId);
} catch (FlickrException e3) {}
// Show params
System.out.println("\n\nParameters:");
System.out.println("\tSync folder: "+syncFolder);
System.out.println("\tArchive folder: "+archiveFolderString);
if(defaultSet!=null)
System.out.println("\tDefault Set: "+defaultSet.getTitle());
else
System.out.println("\tDefault Set: none");
System.out.println("\tDefault privacy: "+defaultPrivacy);
// Get user upload limitations
UserLimitations userLimits = new UserLimitations();
// Show limit / usage
try {
System.out.println("\n\n"+userLimits.showUsageAndLimitations());
} catch (FlickrException e2) {
System.out.println("Error: impossible to show usage and restrictions for user "+user.getUserName()+"\n"+e2.getMessage());
}
// Sync folder
File folder = new File(syncFolder);
// Check upload folder
if (!folder.exists()){
System.out.println("Error: sync folder does not exist ("+folder.getPath()+"). Please verify the syno2flickr.properties config file.");
System.exit(0);
}
// List files to upload
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
try {
return !pathname.isDirectory() && !pathname.isHidden();
} catch (Exception e) {
return false;
}
}
});
// Show nb files founds
System.out.println("\nStart uploading: "+listOfFiles.length+ " files found to upload");
// Synchronize (upload photos/video)
long denomMega=1024L*1024L;
File archiveFolder = new File(archiveFolderString);
// Check archive folder folder
if (!archiveFolder.exists()){
System.out.println("Warning: archive folder does not exist ("+archiveFolder.getPath()+").");
}
int noFile = 0;
try {
// Get bandwith remaining
long bandwidthRemaingBytes = userLimits.getBandwidthRemainingBytes();
for (File f : listOfFiles) {
// init
//ProgressUpload.calls = 0;
noFile++;
// Check limitations/file type
if(!userLimits.isBandwidthUnlimited() && (bandwidthRemaingBytes-f.length()) < 0){
System.out.println("Error: user " + user.getUserName() +
" has reached his monthly bandwidth limit ("+
userLimits.getBandwidthMaxBytes()/denomMega+
"MB). Upload cancelled.");
break;
}
String mime=null;
try {
mime = MimeType.getMimeType("file://"+f.getPath());
} catch (IOException e1) {}
if (mime!=null && mime.contains("image")) {
if (f.length() > userLimits.getFilesizeMaxBytes()){
System.out.println("Error: image " + f.getName()+ " exceeds the maximum accepted size (max. "+
userLimits.getFilesizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
} else {
if (f.length() > userLimits.getVideosizeMaxBytes()){
System.out.println("Error: " + f.getName()+
" exceeds the maximum accepted size (max. "+
userLimits.getVideosizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
}
// Info
System.out.println("\nSending "+f.getName()+ " ("+noFile+"/"+listOfFiles.length+")");
// Generate metadata for the upload
PhotoUpload uploader = new PhotoUpload.Builder(f)
.familyFlag(defaultPrivacy.equals(Privacy.FAMILY) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.friendFlag(defaultPrivacy.equals(Privacy.FRIENDS) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.publicFlag(defaultPrivacy.equals(Privacy.PUBLIC))
.build();
try {
// Upload the content
String id;
id = Photo.uploadNewPhoto(uploader, new RequestListener() {
@Override
public void progressRequest(RequestEvent event) {
stopAllThreads();
ProgressUpload r = new ProgressUpload(event.getProgress(), event.getTotalProgress());
progressList.push(r);
r.start();
}
});
// Stop all threads
stopAllThreads();
// Put in default set
if (defaultSet!=null){
try {
defaultSet.add(id);
} catch(FlickrException e){
System.out.println("Error while adding photo (id: "+id+") to set (id: "+defaultSet.getID()+").\n"+e.getMessage());
}
}
// Move uploaded file to archive
if (archiveFolder.exists()){
f.renameTo(new File( archiveFolder.getPath()+File.separator+f.getName()));
}
if (!userLimits.isBandwidthUnlimited()) bandwidthRemaingBytes-=f.length();
} catch (FlickrException e) {
interruptAllThreads();
System.out.println("\nERROR: An error occured while uploading file "
+ f.getPath()+":\n"+e.getMessage());
if (e.getCode()==6 || e.getCode()==-999) break;
}
}
} catch (FlickrException e){
System.out.println("\nA grave error occurs:\n"+e.getMessage());
}
// Summary and notify
try { Thread.sleep(500); } catch (InterruptedException e) {}
System.out.println("\n\nSend completed.\nBye.");
}
}
| private static User authenticationToFlickr(User user, Permission perm){
// Establish Flickr auth. or ask permission to
try {
user = Auth.getDefaultAuthUser(); // Check to see if we've already
// authenticated
} catch (FlickrException e1) {
user = null;
}
try {
// if need to authenticated
if (user == null || !Auth.isAuthenticated(user, perm)) {
// Give the URL to enter in the browser
System.out
.println("Please enter the following URL into a browser, "
+ "follow the instructions, and then come back");
String authURL = Auth.getAuthURL(perm);
System.out.println(authURL);
// Wait for them to come back
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
in.readLine();
// Alright, now that we're cleared with Flickr, let's try to
// authenticate
System.out.println("Trying to get " + perm + " access.");
try {
user = Auth.authenticate();
} catch (FlickrException ex) {
System.out.println("Failure to authenticate.");
System.exit(1);
}
if (Auth.isAuthenticated(user, perm)) {
System.out.println("We're authenticated with "
+ Auth.getPermLevel(user) + " access.");
Auth.setDefaultAuthUser(user);
} else {
// Shouldn't ever get here - we throw an exception above if
// we
// can't authenticate.
System.out.println("Oddly unauthenticated");
System.exit(2);
}
} // if (user == null || !Auth.isAuthenticated(user, perm)) {
} catch (FlickrException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
} catch (IOException e1) {
System.out.println("Error while Flickr authentication\n" + e1.getMessage());
System.exit(0);
}
// Set authentication context for user (credentials)
Auth.resetAuthContext();
Auth.setAuthContext(user);
try {
user = User.findByNSID(user.getNSID());
} catch (FlickrException e) {
System.out.println("Error: can't retrieve user NSID: "+user.getNSID());
}
// Show infos
System.out.println("\n\nHello "+user.getRealName());
System.out.println("\tYou have " +user.getPhotoCount()+" photos");
return user;
}
/**
* Welcome message
*/
public static void printWelcome(){
System.out.println("**********************************************************************");
System.out.println("* Syno2Flickr v0.1.2 07/2013 *");
System.out.println("* *");
System.out.println("**********************************************************************");
}
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
// Initialization
String syncFolder = null; // folder to upload
String archiveFolderString = null; // archive folder
String defaultSetId = null; // id of default set for new photos
Privacy defaultPrivacy = null; // default privacy
org.jickr.Permission perm = Permission.WRITE; // access level we want
org.jickr.User user = null; // User Flickr authenticated
// Welcome
printWelcome();
// Get property values
try {
// Test first arg (must be the path of the properties file)
if (args != null && args.length > 0)
if (new File(args[0]).exists())
Syno2FlickrProperties.setPropertyFile(args[0]);
// Set key/secret
Flickr.setApiKey(Syno2FlickrProperties.getApiKey());
Flickr.setSharedSecret(Syno2FlickrProperties.getSharedSecret());
// Get folder to sync
syncFolder = Syno2FlickrProperties.getFolderToSync();
// Archive folder
archiveFolderString = Syno2FlickrProperties.getArchiveFolder();
// Default set id
defaultSetId = Syno2FlickrProperties.getDefaultSetId();
// Default privacy
String privacyString = Syno2FlickrProperties.getDefaultPrivacy();
defaultPrivacy = Privacy.valueOf(Integer.parseInt(privacyString));
} catch (Syno2FlickrException e) {
// Error message
System.out.println(e.getMessage());
System.exit(0);
} catch (NumberFormatException e){
// Error while getting the default privacy
System.out.println("Error while getting default privacy, value must be between 0 and 4. Default privacy will be set to private");
defaultPrivacy = Privacy.PRIVATE;
}
// Auth
user = authenticationToFlickr(user, perm);
// Check default set
PhotoSet defaultSet=null;
try {
defaultSet = PhotoSet.findByID(defaultSetId);
} catch (FlickrException e3) {}
// Show params
System.out.println("\n\nParameters:");
System.out.println("\tSync folder: "+syncFolder);
System.out.println("\tArchive folder: "+archiveFolderString);
if(defaultSet!=null)
System.out.println("\tDefault Set: "+defaultSet.getTitle());
else
System.out.println("\tDefault Set: none");
System.out.println("\tDefault privacy: "+defaultPrivacy);
// Get user upload limitations
UserLimitations userLimits = new UserLimitations();
// Show limit / usage
try {
System.out.println("\n\n"+userLimits.showUsageAndLimitations());
} catch (FlickrException e2) {
System.out.println("Error: impossible to show usage and restrictions for user "+user.getUserName()+"\n"+e2.getMessage());
}
// Sync folder
File folder = new File(syncFolder);
// Check upload folder
if (!folder.exists()){
System.out.println("Error: sync folder does not exist ("+folder.getPath()+"). Please verify the syno2flickr.properties config file.");
System.exit(0);
}
// List files to upload
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
try {
return !pathname.isDirectory() && !pathname.isHidden();
} catch (Exception e) {
return false;
}
}
});
// Show nb files founds
System.out.println("\nStart uploading: "+listOfFiles.length+ " files found to upload");
// Synchronize (upload photos/video)
long denomMega=1024L*1024L;
File archiveFolder = new File(archiveFolderString);
// Check archive folder folder
if (!archiveFolder.exists()){
System.out.println("Warning: archive folder does not exist ("+archiveFolder.getPath()+").");
}
int noFile = 0;
try {
// Get bandwith remaining
long bandwidthRemaingBytes = userLimits.getBandwidthRemainingBytes();
for (File f : listOfFiles) {
// init
//ProgressUpload.calls = 0;
noFile++;
// Check limitations/file type
if(!userLimits.isBandwidthUnlimited() && (bandwidthRemaingBytes-f.length()) < 0){
System.out.println("Error: user " + user.getUserName() +
" has reached his monthly bandwidth limit ("+
userLimits.getBandwidthMaxBytes()/denomMega+
"MB). Upload cancelled.");
break;
}
String mime=null;
try {
mime = MimeType.getMimeType("file://"+f.getPath());
} catch (IOException e1) {}
if (mime!=null && mime.contains("image")) {
if (f.length() > userLimits.getFilesizeMaxBytes()){
System.out.println("Error: image " + f.getName()+ " exceeds the maximum accepted size (max. "+
userLimits.getFilesizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
} else {
if (f.length() > userLimits.getVideosizeMaxBytes()){
System.out.println("Error: " + f.getName()+
" exceeds the maximum accepted size (max. "+
userLimits.getVideosizeMaxBytes()/denomMega+"MB). Skipped.");
continue;
}
}
// Info
System.out.println("\nSending "+f.getName()+ " ("+noFile+"/"+listOfFiles.length+")");
// Generate metadata for the upload
PhotoUpload uploader = new PhotoUpload.Builder(f)
.familyFlag(defaultPrivacy.equals(Privacy.FAMILY) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.friendFlag(defaultPrivacy.equals(Privacy.FRIENDS) || defaultPrivacy.equals(Privacy.FRIENDSANDFAMILY))
.publicFlag(defaultPrivacy.equals(Privacy.PUBLIC))
.build();
try {
// Upload the content
String id;
id = Photo.uploadNewPhoto(uploader, new RequestListener() {
@Override
public void progressRequest(RequestEvent event) {
stopAllThreads();
ProgressUpload r = new ProgressUpload(event.getProgress(), event.getTotalProgress());
progressList.push(r);
r.start();
}
});
// Stop all threads
stopAllThreads();
// Put in default set
if (defaultSet!=null){
try {
defaultSet.add(id);
} catch(FlickrException e){
System.out.println("Error while adding photo (id: "+id+") to set (id: "+defaultSet.getID()+").\n"+e.getMessage());
}
}
// Move uploaded file to archive
if (archiveFolder.exists()){
f.renameTo(new File( archiveFolder.getPath()+File.separator+f.getName()));
}
if (!userLimits.isBandwidthUnlimited()) bandwidthRemaingBytes-=f.length();
} catch (FlickrException e) {
interruptAllThreads();
System.out.println("\nERROR: An error occured while uploading file "
+ f.getPath()+":\n"+e.getMessage());
if (e.getCode()==6 || e.getCode()==-999) break;
}
}
} catch (FlickrException e){
System.out.println("\nA grave error occurs:\n"+e.getMessage());
}
// Summary and notify
try { Thread.sleep(500); } catch (InterruptedException e) {}
System.out.println("\n\nSend completed.\nBye.");
}
}
|
diff --git a/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/ui/AbstractTreeTestLanguageUiModule.java b/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/ui/AbstractTreeTestLanguageUiModule.java
index 46c3e9d3b..45bda6978 100644
--- a/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/ui/AbstractTreeTestLanguageUiModule.java
+++ b/tests/org.eclipse.xtext.xtend.tests/src-gen/org/eclipse/xtext/xtend/ui/AbstractTreeTestLanguageUiModule.java
@@ -1,176 +1,176 @@
/*
* generated by Xtext
*/
package org.eclipse.xtext.xtend.ui;
import org.eclipse.xtext.xtend.TreeTestLanguageRuntimeModule;
/**
* Manual modifications go to {org.eclipse.xtext.xtend.ui.TreeTestLanguageUiModule}
*/
public abstract class AbstractTreeTestLanguageUiModule extends TreeTestLanguageRuntimeModule {
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
- public Class<? extends org.eclipse.xtext.ui.ILocationInFileProvider> bindILocationInFileProvider() {
- return org.eclipse.xtext.ui.DefaultLocationInFileProvider.class;
+ public Class<? extends org.eclipse.xtext.resource.ILocationInFileProvider> bindILocationInFileProvider() {
+ return org.eclipse.xtext.resource.DefaultLocationInFileProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.text.hyperlink.IHyperlinkDetector> bindIHyperlinkDetector() {
return org.eclipse.xtext.ui.editor.hyperlinking.DefaultHyperlinkDetector.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.text.reconciler.IReconciler> bindIReconciler() {
return org.eclipse.xtext.ui.editor.reconciler.XtextReconciler.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.toggleComments.ISingleLineCommentHelper> bindISingleLineCommentHelper() {
return org.eclipse.xtext.ui.editor.toggleComments.DefaultSingleLineCommentHelper.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.outline.transformer.ISemanticModelTransformer> bindISemanticModelTransformer() {
return org.eclipse.xtext.ui.editor.outline.transformer.DefaultSemanticModelTransformer.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.outline.IOutlineTreeProvider> bindIOutlineTreeProvider() {
return org.eclipse.xtext.ui.editor.outline.transformer.TransformingTreeProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.ui.views.contentoutline.IContentOutlinePage> bindIContentOutlinePage() {
return org.eclipse.xtext.ui.editor.outline.XtextContentOutlinePage.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.outline.actions.IActionBarContributor> bindIActionBarContributor() {
return org.eclipse.xtext.ui.editor.outline.actions.IActionBarContributor.DefaultActionBarContributor.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingHelper> bindIHighlightingHelper() {
return org.eclipse.xtext.ui.editor.syntaxcoloring.HighlightingHelper.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.viewers.ILabelProvider> bindILabelProvider() {
return org.eclipse.xtext.ui.DefaultLabelProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider> bindDelegatingStyledCellLabelProvider$IStyledLabelProvider() {
return org.eclipse.xtext.ui.DefaultLabelProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.emf.common.notify.AdapterFactory> bindAdapterFactory() {
return org.eclipse.xtext.ui.InjectableAdapterFactory.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider> bindAdapterFactoryLabelProvider() {
return org.eclipse.xtext.ui.InjectableAdapterFactoryLabelProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public org.eclipse.emf.edit.provider.ComposedAdapterFactory.Descriptor.Registry bindComposedAdapterFactory$Descriptor$RegistryToInstance() {
return org.eclipse.emf.edit.provider.ComposedAdapterFactory.Descriptor.Registry.INSTANCE;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.IContentAssistantFactory> bindIContentAssistantFactory() {
return org.eclipse.xtext.ui.editor.contentassist.DefaultContentAssistantFactory.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.text.contentassist.IContentAssistProcessor> bindIContentAssistProcessor() {
return org.eclipse.xtext.ui.editor.contentassist.XtextContentAssistProcessor.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalPostProcessor> bindICompletionProposalPostProcessor() {
return org.eclipse.xtext.ui.editor.contentassist.DefaultCompletionProposalPostProcessor.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.IFollowElementCalculator> bindIFollowElementCalculator() {
return org.eclipse.xtext.ui.editor.contentassist.DefaultFollowElementCalculator.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.ITemplateProposalProvider> bindITemplateProposalProvider() {
return org.eclipse.xtext.ui.editor.templates.DefaultTemplateProposalProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.text.templates.persistence.TemplateStore> bindTemplateStore() {
return org.eclipse.xtext.ui.editor.templates.XtextTemplateStore.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.jface.text.templates.ContextTypeRegistry> bindContextTypeRegistry() {
return org.eclipse.xtext.ui.editor.templates.XtextTemplateContextTypeRegistry.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.IContentProposalProvider> bindIContentProposalProvider() {
return org.eclipse.xtext.common.ui.contentassist.TerminalsProposalProvider.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.ui.editor.formatting.IContentFormatterFactory> bindIContentFormatterFactory() {
return org.eclipse.xtext.ui.editor.formatting.ContentFormatterFactory.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public void configureXtextEditorErrorTickUpdater(com.google.inject.Binder binder) {
binder.bind(org.eclipse.xtext.ui.editor.IXtextEditorCallback.class).annotatedWith(com.google.inject.name.Names.named("IXtextEditorCallBack")).to(org.eclipse.xtext.ui.editor.XtextEditorErrorTickUpdater.class);
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public Class<? extends org.eclipse.xtext.resource.IExternalContentSupport.IExternalContentProvider> bindIExternalContentSupport$IExternalContentProvider() {
return org.eclipse.xtext.ui.editor.IDirtyStateManager.class;
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public com.google.inject.Provider<org.eclipse.xtext.ui.editor.IDirtyStateManager> provideIDirtyStateManager() {
return new org.eclipse.xtext.ui.editor.DirtyStateManagerProvider();
}
// contributed by org.eclipse.xtext.ui.generator.ImplicitUiFragment
public com.google.inject.Provider<org.eclipse.xtext.ui.notification.IStateChangeEventBroker> provideIStateChangeEventBroker() {
return new org.eclipse.xtext.ui.notification.StateChangeEventBrokerProvider();
}
// contributed by de.itemis.xtext.antlr.XtextAntlrGeneratorFragment
public Class<? extends org.eclipse.jface.text.rules.ITokenScanner> bindITokenScanner() {
return org.eclipse.xtext.ui.editor.syntaxcoloring.antlr.AntlrTokenScanner.class;
}
// contributed by de.itemis.xtext.antlr.XtextAntlrGeneratorFragment
public Class<? extends org.eclipse.xtext.ui.editor.contentassist.IProposalConflictHelper> bindIProposalConflictHelper() {
return org.eclipse.xtext.ui.editor.contentassist.antlr.AntlrProposalConflictHelper.class;
}
// contributed by de.itemis.xtext.antlr.XtextAntlrGeneratorFragment
public Class<? extends org.eclipse.xtext.ui.editor.IDamagerRepairer> bindIDamagerRepairer() {
return org.eclipse.xtext.ui.editor.XtextDamagerRepairer.class;
}
// contributed by de.itemis.xtext.antlr.XtextAntlrGeneratorFragment
public void configureHighlightingLexer(com.google.inject.Binder binder) {
binder.bind(org.eclipse.xtext.parser.antlr.Lexer.class).annotatedWith(com.google.inject.name.Names.named(org.eclipse.xtext.ui.LexerUIBindings.HIGHLIGHTING)).to(org.eclipse.xtext.xtend.parser.antlr.internal.InternalTreeTestLanguageLexer.class);
}
// contributed by de.itemis.xtext.antlr.XtextAntlrGeneratorFragment
public void configureHighlightingTokenDefProvider(com.google.inject.Binder binder) {
binder.bind(org.eclipse.xtext.parser.antlr.ITokenDefProvider.class).annotatedWith(com.google.inject.name.Names.named(org.eclipse.xtext.ui.LexerUIBindings.HIGHLIGHTING)).to(org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider.class);
}
}
| true | true | public Class<? extends org.eclipse.xtext.ui.ILocationInFileProvider> bindILocationInFileProvider() {
return org.eclipse.xtext.ui.DefaultLocationInFileProvider.class;
}
| public Class<? extends org.eclipse.xtext.resource.ILocationInFileProvider> bindILocationInFileProvider() {
return org.eclipse.xtext.resource.DefaultLocationInFileProvider.class;
}
|
diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java
index bbe0d3285..01635c538 100644
--- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java
+++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java
@@ -1,467 +1,470 @@
// ========================================================================
// Copyright (c) 2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.webapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.eclipse.jetty.util.resource.Resource;
/**
* MetaData
*
* All data associated with the configuration and deployment of a web application.
*/
public class MetaData
{
public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs";
public enum Origin {NotSet, WebXml, WebDefaults, WebOverride, WebFragment, Annotation};
protected Map<String, OriginInfo> _origins =new HashMap<String,OriginInfo>();
protected WebDescriptor _webDefaultsRoot;
protected WebDescriptor _webXmlRoot;
protected WebDescriptor _webOverrideRoot;
protected boolean _metaDataComplete;
protected final List<DiscoveredAnnotation> _annotations = new ArrayList<DiscoveredAnnotation>();
protected final List<DescriptorProcessor> _descriptorProcessors = new ArrayList<DescriptorProcessor>();
protected final List<FragmentDescriptor> _webFragmentRoots = new ArrayList<FragmentDescriptor>();
protected final Map<String,FragmentDescriptor> _webFragmentNameMap = new HashMap<String,FragmentDescriptor>();
protected final Map<Resource, FragmentDescriptor> _webFragmentResourceMap = new HashMap<Resource, FragmentDescriptor>();
protected final Map<Resource, List<DiscoveredAnnotation>> _webFragmentAnnotations = new HashMap<Resource, List<DiscoveredAnnotation>>();
protected final List<Resource> _webInfJars = new ArrayList<Resource>();
protected final List<Resource> _orderedWebInfJars = new ArrayList<Resource>();
protected final List<Resource> _orderedContainerJars = new ArrayList<Resource>();
protected Ordering _ordering;//can be set to RelativeOrdering by web-default.xml, web.xml, web-override.xml
public static class OriginInfo
{
protected String name;
protected Origin origin;
protected Descriptor descriptor;
public OriginInfo (String n, Descriptor d)
{
name = n;
descriptor = d;
if (d == null)
throw new IllegalArgumentException("No descriptor");
if (d instanceof FragmentDescriptor)
origin = Origin.WebFragment;
if (d instanceof OverrideDescriptor)
origin = Origin.WebOverride;
if (d instanceof DefaultsDescriptor)
origin = Origin.WebDefaults;
origin = Origin.WebXml;
}
public OriginInfo (String n)
{
name = n;
origin = Origin.Annotation;
}
public OriginInfo(String n, Origin o)
{
name = n;
origin = o;
}
public String getName()
{
return name;
}
public Origin getOriginType()
{
return origin;
}
public Descriptor getDescriptor()
{
return descriptor;
}
}
public MetaData ()
{
}
public void setDefaults (Resource webDefaults)
throws Exception
{
_webDefaultsRoot = new DefaultsDescriptor(webDefaults);
_webDefaultsRoot.parse();
if (_webDefaultsRoot.isOrdered())
{
if (_ordering == null)
_ordering = new Ordering.AbsoluteOrdering(this);
List<String> order = _webDefaultsRoot.getOrdering();
for (String s:order)
{
if (s.equalsIgnoreCase("others"))
((Ordering.AbsoluteOrdering)_ordering).addOthers();
else
((Ordering.AbsoluteOrdering)_ordering).add(s);
}
}
}
public void setWebXml (Resource webXml)
throws Exception
{
_webXmlRoot = new WebDescriptor(webXml);
_webXmlRoot.parse();
_metaDataComplete=_webXmlRoot.getMetaDataComplete() == WebDescriptor.MetaDataComplete.True;
if (_webXmlRoot.isOrdered())
{
if (_ordering == null)
_ordering = new Ordering.AbsoluteOrdering(this);
List<String> order = _webXmlRoot.getOrdering();
for (String s:order)
{
if (s.equalsIgnoreCase("others"))
((Ordering.AbsoluteOrdering)_ordering).addOthers();
else
((Ordering.AbsoluteOrdering)_ordering).add(s);
}
}
}
public void setOverride (Resource override)
throws Exception
{
_webOverrideRoot = new OverrideDescriptor(override);
_webOverrideRoot.setValidating(false);
_webOverrideRoot.parse();
switch(_webOverrideRoot.getMetaDataComplete())
{
case True:
_metaDataComplete=true;
break;
case False:
_metaDataComplete=true;
break;
case NotSet:
break;
}
if (_webOverrideRoot.isOrdered())
{
if (_ordering == null)
_ordering = new Ordering.AbsoluteOrdering(this);
List<String> order = _webOverrideRoot.getOrdering();
for (String s:order)
{
if (s.equalsIgnoreCase("others"))
((Ordering.AbsoluteOrdering)_ordering).addOthers();
else
((Ordering.AbsoluteOrdering)_ordering).add(s);
}
}
}
/**
* Add a web-fragment.xml
*
* @param jarResource the jar the fragment is contained in
* @param xmlResource the resource representing the xml file
* @throws Exception
*/
public void addFragment (Resource jarResource, Resource xmlResource)
throws Exception
{
if (_metaDataComplete)
return; //do not process anything else if web.xml/web-override.xml set metadata-complete
//Metadata-complete is not set, or there is no web.xml
FragmentDescriptor descriptor = new FragmentDescriptor(xmlResource);
_webFragmentResourceMap.put(jarResource, descriptor);
_webFragmentRoots.add(descriptor);
descriptor.parse();
if (descriptor.getName() != null)
_webFragmentNameMap.put(descriptor.getName(), descriptor);
//If web.xml has specified an absolute ordering, ignore any relative ordering in the fragment
if (_ordering != null && _ordering.isAbsolute())
return;
if (_ordering == null && descriptor.isOrdered())
_ordering = new Ordering.RelativeOrdering(this);
}
/**
* Annotations not associated with a WEB-INF/lib fragment jar.
* These are from WEB-INF/classes or the ??container path??
* @param annotations
*/
public void addDiscoveredAnnotations(List<DiscoveredAnnotation> annotations)
{
_annotations.addAll(annotations);
}
public void addDiscoveredAnnotations(Resource resource, List<DiscoveredAnnotation> annotations)
{
_webFragmentAnnotations.put(resource, new ArrayList<DiscoveredAnnotation>(annotations));
}
public void addDescriptorProcessor(DescriptorProcessor p)
{
_descriptorProcessors.add(p);
}
public void orderFragments ()
{
//if we have already ordered them don't do it again
if (_orderedWebInfJars.size()==_webInfJars.size())
return;
if (_ordering != null)
_orderedWebInfJars.addAll(_ordering.order(_webInfJars));
else
_orderedWebInfJars.addAll(_webInfJars);
}
/**
* Resolve all servlet/filter/listener metadata from all sources: descriptors and annotations.
*
*/
public void resolve (WebAppContext context)
throws Exception
{
//Ensure origins is fresh
_origins.clear();
// Set the ordered lib attribute
- List<String> orderedLibs = new ArrayList<String>();
- for (Resource webInfJar:_orderedWebInfJars)
+ if (_ordering != null)
{
- //get just the name of the jar file
- String fullname = webInfJar.getName();
- int i = fullname.indexOf(".jar");
- int j = fullname.lastIndexOf("/", i);
- orderedLibs.add(fullname.substring(j+1,i+4));
+ List<String> orderedLibs = new ArrayList<String>();
+ for (Resource webInfJar:_orderedWebInfJars)
+ {
+ //get just the name of the jar file
+ String fullname = webInfJar.getName();
+ int i = fullname.indexOf(".jar");
+ int j = fullname.lastIndexOf("/", i);
+ orderedLibs.add(fullname.substring(j+1,i+4));
+ }
+ context.setAttribute(ORDERED_LIBS, orderedLibs);
}
- context.setAttribute(ORDERED_LIBS, orderedLibs);
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,getWebDefault());
p.process(context,getWebXml());
p.process(context,getOverrideWeb());
}
for (DiscoveredAnnotation a:_annotations)
a.apply();
List<Resource> resources = getOrderedWebInfJars();
for (Resource r:resources)
{
FragmentDescriptor fd = _webFragmentResourceMap.get(r);
if (fd != null)
{
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,fd);
}
}
List<DiscoveredAnnotation> fragAnnotations = _webFragmentAnnotations.get(r);
if (fragAnnotations != null)
{
for (DiscoveredAnnotation a:fragAnnotations)
a.apply();
}
}
}
public boolean isDistributable ()
{
boolean distributable = (
(_webDefaultsRoot != null && _webDefaultsRoot.isDistributable())
|| (_webXmlRoot != null && _webXmlRoot.isDistributable())
|| (_webOverrideRoot != null && _webOverrideRoot.isDistributable()));
List<Resource> orderedResources = getOrderedWebInfJars();
for (Resource r: orderedResources)
{
FragmentDescriptor d = _webFragmentResourceMap.get(r);
if (d!=null)
distributable = distributable && d.isDistributable();
}
return distributable;
}
public WebDescriptor getWebXml ()
{
return _webXmlRoot;
}
public WebDescriptor getOverrideWeb ()
{
return _webOverrideRoot;
}
public WebDescriptor getWebDefault ()
{
return _webDefaultsRoot;
}
public List<FragmentDescriptor> getFragments ()
{
return _webFragmentRoots;
}
public List<Resource> getOrderedWebInfJars()
{
return _orderedWebInfJars == null? new ArrayList<Resource>(): _orderedWebInfJars;
}
public List<FragmentDescriptor> getOrderedFragments ()
{
List<FragmentDescriptor> list = new ArrayList<FragmentDescriptor>();
if (_orderedWebInfJars == null)
return list;
for (Resource r:_orderedWebInfJars)
{
FragmentDescriptor fd = _webFragmentResourceMap.get(r);
if (fd != null)
list.add(fd);
}
return list;
}
public Ordering getOrdering()
{
return _ordering;
}
public void setOrdering (Ordering o)
{
_ordering = o;
}
public FragmentDescriptor getFragment (Resource jar)
{
return _webFragmentResourceMap.get(jar);
}
public FragmentDescriptor getFragment(String name)
{
return _webFragmentNameMap.get(name);
}
public Resource getJarForFragment (String name)
{
FragmentDescriptor f = getFragment(name);
if (f == null)
return null;
Resource jar = null;
for (Resource r: _webFragmentResourceMap.keySet())
{
if (_webFragmentResourceMap.get(r).equals(f))
jar = r;
}
return jar;
}
public Map<String,FragmentDescriptor> getNamedFragments ()
{
return Collections.unmodifiableMap(_webFragmentNameMap);
}
public Origin getOrigin (String name)
{
OriginInfo x = _origins.get(name);
if (x == null)
return Origin.NotSet;
return x.getOriginType();
}
public Descriptor getOriginDescriptor (String name)
{
OriginInfo o = _origins.get(name);
if (o == null)
return null;
return o.getDescriptor();
}
public void setOrigin (String name, Descriptor d)
{
OriginInfo x = new OriginInfo (name, d);
_origins.put(name, x);
}
public void setOrigin (String name)
{
if (name == null)
return;
OriginInfo x = new OriginInfo (name, Origin.Annotation);
_origins.put(name, x);
}
public boolean isMetaDataComplete()
{
return _metaDataComplete;
}
public void addWebInfJar(Resource newResource)
{
_webInfJars.add(newResource);
}
public List<Resource> getWebInfJars()
{
return Collections.unmodifiableList(_webInfJars);
}
public List<Resource> getOrderedContainerJars()
{
return _orderedContainerJars;
}
public void addContainerJar(Resource jar)
{
_orderedContainerJars.add(jar);
}
}
| false | true | public void resolve (WebAppContext context)
throws Exception
{
//Ensure origins is fresh
_origins.clear();
// Set the ordered lib attribute
List<String> orderedLibs = new ArrayList<String>();
for (Resource webInfJar:_orderedWebInfJars)
{
//get just the name of the jar file
String fullname = webInfJar.getName();
int i = fullname.indexOf(".jar");
int j = fullname.lastIndexOf("/", i);
orderedLibs.add(fullname.substring(j+1,i+4));
}
context.setAttribute(ORDERED_LIBS, orderedLibs);
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,getWebDefault());
p.process(context,getWebXml());
p.process(context,getOverrideWeb());
}
for (DiscoveredAnnotation a:_annotations)
a.apply();
List<Resource> resources = getOrderedWebInfJars();
for (Resource r:resources)
{
FragmentDescriptor fd = _webFragmentResourceMap.get(r);
if (fd != null)
{
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,fd);
}
}
List<DiscoveredAnnotation> fragAnnotations = _webFragmentAnnotations.get(r);
if (fragAnnotations != null)
{
for (DiscoveredAnnotation a:fragAnnotations)
a.apply();
}
}
}
| public void resolve (WebAppContext context)
throws Exception
{
//Ensure origins is fresh
_origins.clear();
// Set the ordered lib attribute
if (_ordering != null)
{
List<String> orderedLibs = new ArrayList<String>();
for (Resource webInfJar:_orderedWebInfJars)
{
//get just the name of the jar file
String fullname = webInfJar.getName();
int i = fullname.indexOf(".jar");
int j = fullname.lastIndexOf("/", i);
orderedLibs.add(fullname.substring(j+1,i+4));
}
context.setAttribute(ORDERED_LIBS, orderedLibs);
}
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,getWebDefault());
p.process(context,getWebXml());
p.process(context,getOverrideWeb());
}
for (DiscoveredAnnotation a:_annotations)
a.apply();
List<Resource> resources = getOrderedWebInfJars();
for (Resource r:resources)
{
FragmentDescriptor fd = _webFragmentResourceMap.get(r);
if (fd != null)
{
for (DescriptorProcessor p:_descriptorProcessors)
{
p.process(context,fd);
}
}
List<DiscoveredAnnotation> fragAnnotations = _webFragmentAnnotations.get(r);
if (fragAnnotations != null)
{
for (DiscoveredAnnotation a:fragAnnotations)
a.apply();
}
}
}
|
diff --git a/src/com/android/calculator2/CalculatorEditText.java b/src/com/android/calculator2/CalculatorEditText.java
index 8a29f72..3af08c7 100644
--- a/src/com/android/calculator2/CalculatorEditText.java
+++ b/src/com/android/calculator2/CalculatorEditText.java
@@ -1,48 +1,48 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calculator2;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.Toast;
public class CalculatorEditText extends EditText {
public CalculatorEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean performLongClick() {
Editable text = getText();
if (TextUtils.isEmpty(text)) {
return false;
}
setSelection(0, text.length());
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);
- clipboard.setPrimaryClip(ClipData.newPlainText(null, null, getText()));
+ clipboard.setPrimaryClip(ClipData.newPlainText(null, getText()));
Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
return true;
}
}
| true | true | public boolean performLongClick() {
Editable text = getText();
if (TextUtils.isEmpty(text)) {
return false;
}
setSelection(0, text.length());
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText(null, null, getText()));
Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
return true;
}
| public boolean performLongClick() {
Editable text = getText();
if (TextUtils.isEmpty(text)) {
return false;
}
setSelection(0, text.length());
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText(null, getText()));
Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
return true;
}
|
diff --git a/plugins/maven-patch-tracker-plugin/src/main/java/org/apache/maven/plugins/patchtracker/PostPatchMojo.java b/plugins/maven-patch-tracker-plugin/src/main/java/org/apache/maven/plugins/patchtracker/PostPatchMojo.java
index 286dbddd3..5a82c5571 100644
--- a/plugins/maven-patch-tracker-plugin/src/main/java/org/apache/maven/plugins/patchtracker/PostPatchMojo.java
+++ b/plugins/maven-patch-tracker-plugin/src/main/java/org/apache/maven/plugins/patchtracker/PostPatchMojo.java
@@ -1,80 +1,85 @@
package org.apache.maven.plugins.patchtracker;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.patchtracker.tracking.PatchTracker;
import org.apache.maven.plugins.patchtracker.tracking.PatchTrackerException;
import org.apache.maven.plugins.patchtracker.tracking.PatchTrackerRequest;
import org.apache.maven.plugins.patchtracker.tracking.PatchTrackerResult;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
/**
* Goal which create a diff/patch file from the current project and post it in the selected patch tracker
* (with jira an issue in the project with attaching the created patch file)
*/
@Mojo (name = "post", aggregator = true)
public class PostPatchMojo
extends AbstractPatchMojo
{
public void execute()
throws MojoExecutionException
{
// TODO do a status before and complains if some files in to be added status ?
String patchContent = getPatchContent();
if ( StringUtils.isEmpty( patchContent ) )
{
getLog().info( "No patch content found so skip posting patch" );
return;
}
try
{
PatchTracker patchTracker = getPatchTracker();
PatchTrackerRequest patchTrackerRequest = buidPatchTrackerRequest( true );
patchTrackerRequest.setPatchContent( patchContent );
getLog().debug( patchTrackerRequest.toString() );
PatchTrackerResult result = patchTracker.createPatch( patchTrackerRequest, getLog() );
- getLog().info( "issue created with id:" + result.getPatchId() + ", url:" + result.getPatchUrl() );
+ StringBuilder msg = new StringBuilder( "Patch posted to patch tracker" );
+ if ( result.getPatchId() != null )
+ {
+ msg.append( ". Review created with id:" + result.getPatchId() + ", url:" + result.getPatchUrl() );
+ }
+ getLog().info( msg.toString() );
}
catch ( ComponentLookupException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( PatchTrackerException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
}
| true | true | public void execute()
throws MojoExecutionException
{
// TODO do a status before and complains if some files in to be added status ?
String patchContent = getPatchContent();
if ( StringUtils.isEmpty( patchContent ) )
{
getLog().info( "No patch content found so skip posting patch" );
return;
}
try
{
PatchTracker patchTracker = getPatchTracker();
PatchTrackerRequest patchTrackerRequest = buidPatchTrackerRequest( true );
patchTrackerRequest.setPatchContent( patchContent );
getLog().debug( patchTrackerRequest.toString() );
PatchTrackerResult result = patchTracker.createPatch( patchTrackerRequest, getLog() );
getLog().info( "issue created with id:" + result.getPatchId() + ", url:" + result.getPatchUrl() );
}
catch ( ComponentLookupException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( PatchTrackerException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
| public void execute()
throws MojoExecutionException
{
// TODO do a status before and complains if some files in to be added status ?
String patchContent = getPatchContent();
if ( StringUtils.isEmpty( patchContent ) )
{
getLog().info( "No patch content found so skip posting patch" );
return;
}
try
{
PatchTracker patchTracker = getPatchTracker();
PatchTrackerRequest patchTrackerRequest = buidPatchTrackerRequest( true );
patchTrackerRequest.setPatchContent( patchContent );
getLog().debug( patchTrackerRequest.toString() );
PatchTrackerResult result = patchTracker.createPatch( patchTrackerRequest, getLog() );
StringBuilder msg = new StringBuilder( "Patch posted to patch tracker" );
if ( result.getPatchId() != null )
{
msg.append( ". Review created with id:" + result.getPatchId() + ", url:" + result.getPatchUrl() );
}
getLog().info( msg.toString() );
}
catch ( ComponentLookupException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( PatchTrackerException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
|
diff --git a/src/main/java/com/blockmar/persistence/mongo/MongoRepositoryQueryResult.java b/src/main/java/com/blockmar/persistence/mongo/MongoRepositoryQueryResult.java
index f7dcbf3..c0cd8a0 100644
--- a/src/main/java/com/blockmar/persistence/mongo/MongoRepositoryQueryResult.java
+++ b/src/main/java/com/blockmar/persistence/mongo/MongoRepositoryQueryResult.java
@@ -1,67 +1,67 @@
package com.blockmar.persistence.mongo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.blockmar.persistence.RepositoryQueryResult;
import com.google.code.morphia.query.Query;
public class MongoRepositoryQueryResult<T> implements RepositoryQueryResult<T> {
private final Query<? extends MongoRepositoryObject<T>> query;
public MongoRepositoryQueryResult(Query<? extends MongoRepositoryObject<T>> query) {
this.query = query;
}
public List<T> all() {
List<T> result = new ArrayList<T>();
for (MongoRepositoryObject<T> object : query) {
result.add(object.get());
}
return result;
}
public List<T> limit(int count) {
List<T> result = new ArrayList<T>();
Iterator<? extends MongoRepositoryObject<T>> iterator = query.iterator();
- while (iterator.hasNext() && result.size() <= count) {
+ while (iterator.hasNext() && result.size() < count) {
result.add(iterator.next().get());
}
return result;
}
@Override
public Iterator<T> iterator() {
return new RepositoryQueryResultIterator(query.iterator());
}
private class RepositoryQueryResultIterator implements Iterator<T> {
private final Iterator<? extends MongoRepositoryObject<T>> iterator;
public RepositoryQueryResultIterator(
Iterator<? extends MongoRepositoryObject<T>> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
MongoRepositoryObject<T> object = iterator.next();
return (object == null ? null : object.get());
}
@Override
public void remove() {
iterator.remove();
}
}
}
| true | true | public List<T> limit(int count) {
List<T> result = new ArrayList<T>();
Iterator<? extends MongoRepositoryObject<T>> iterator = query.iterator();
while (iterator.hasNext() && result.size() <= count) {
result.add(iterator.next().get());
}
return result;
}
| public List<T> limit(int count) {
List<T> result = new ArrayList<T>();
Iterator<? extends MongoRepositoryObject<T>> iterator = query.iterator();
while (iterator.hasNext() && result.size() < count) {
result.add(iterator.next().get());
}
return result;
}
|
diff --git a/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java b/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java
index 1902f0383..adb555ff5 100644
--- a/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java
+++ b/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java
@@ -1,407 +1,407 @@
/*
* Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author: José Pinto
* Jul 12, 2012
*/
package pt.up.fe.dceg.neptus.plugins.ais;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Vector;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.mozilla.javascript.edu.emory.mathcs.backport.java.util.Collections;
import pt.up.fe.dceg.neptus.NeptusLog;
import pt.up.fe.dceg.neptus.console.ConsoleLayout;
import pt.up.fe.dceg.neptus.gui.PropertiesEditor;
import pt.up.fe.dceg.neptus.i18n.I18n;
import pt.up.fe.dceg.neptus.planeditor.IEditorMenuExtension;
import pt.up.fe.dceg.neptus.planeditor.IMapPopup;
import pt.up.fe.dceg.neptus.plugins.NeptusProperty;
import pt.up.fe.dceg.neptus.plugins.PluginDescription;
import pt.up.fe.dceg.neptus.plugins.SimpleRendererInteraction;
import pt.up.fe.dceg.neptus.plugins.update.IPeriodicUpdates;
import pt.up.fe.dceg.neptus.plugins.update.PeriodicUpdatesService;
import pt.up.fe.dceg.neptus.renderer2d.LayerPriority;
import pt.up.fe.dceg.neptus.renderer2d.StateRenderer2D;
import pt.up.fe.dceg.neptus.types.coord.LocationType;
import pt.up.fe.dceg.neptus.util.GuiUtils;
import com.google.gson.Gson;
/**
* @author zp
*
*/
@PluginDescription(author = "ZP", name = "AIS Overlay", icon = "pt/up/fe/dceg/neptus/plugins/ais/mt.png")
@LayerPriority(priority=-50)
public class AisOverlay extends SimpleRendererInteraction implements IPeriodicUpdates, IEditorMenuExtension {
private static final long serialVersionUID = 1L;
@NeptusProperty(name = "Show vessel names")
public boolean showNames = true;
@NeptusProperty(name = "Show vessel speeds")
public boolean showSpeeds = true;
@NeptusProperty(name = "Milliseconds between vessel updates")
public long updateMillis = 60000;
@NeptusProperty(name = "Show only when selected")
public boolean showOnlyWhenInteractionIsActive = true;
@NeptusProperty(name = "Show stationary vessels")
public boolean showStoppedShips = false;
@NeptusProperty(name = "Interpolate and predict positions")
public boolean interpolate = false;
@NeptusProperty(name = "Moving vessel color")
public Color movingColor = Color.blue.darker();
@NeptusProperty(name = "Stationary vessel color")
public Color stationaryColor = Color.gray.darker();
@NeptusProperty(name = "Vessel label color")
public Color labelColor = Color.black;
@NeptusProperty(name = "Show speed in knots")
public boolean useKnots = false;
protected boolean active = false;
protected Vector<AisShip> shipsOnMap = new Vector<AisShip>();
protected StateRenderer2D renderer = null;
protected boolean updating = false;
/**
* @param console
*/
public AisOverlay(ConsoleLayout console) {
super(console);
}
@Override
public boolean isExclusive() {
return true;
}
@Override
public void setActive(boolean mode, StateRenderer2D source) {
super.setActive(mode, source);
active = mode;
if (active)
update();
}
@Override
public String getName() {
return super.getName();
}
@Override
public long millisBetweenUpdates() {
return updateMillis;
}
protected Thread lastThread = null;
protected GeneralPath path = new GeneralPath();
{
path.moveTo(0, 5);
path.lineTo(-5, 3.5);
path.lineTo(-5, -5);
path.lineTo(5, -5);
path.lineTo(5, 3.5);
path.lineTo(0, 5);
path.closePath();
}
@Override
public boolean update() {
if (showOnlyWhenInteractionIsActive && !active)
return true;
// don't let more than one thread be running at a time
if (lastThread != null)
return true;
lastThread = new Thread() {
public void run() {
updating = true;
try {
if (renderer == null) {
lastThread = null;
return;
}
LocationType topLeft = renderer.getTopLeftLocationType();
LocationType bottomRight = renderer.getBottomRightLocationType();
shipsOnMap = getShips(bottomRight.getLatitudeAsDoubleValue(), topLeft.getLongitudeAsDoubleValue(),
topLeft.getLatitudeAsDoubleValue(), bottomRight.getLongitudeAsDoubleValue(), showStoppedShips);
lastThread = null;
renderer.repaint();
}
finally {
updating = false;
}
};
};
lastThread.setName("AIS Fetcher thread");
lastThread.setDaemon(true);
lastThread.start();
return true;
}
private HttpClient client = new HttpClient();
private Gson gson = new Gson();
protected Vector<AisShip> getShips(double minLat, double minLon, double maxLat, double maxLon,
boolean includeStationary) {
Vector<AisShip> ships = new Vector<>();
// area is too large
if (maxLat - minLat > 2)
return ships;
try {
URL url = new URL("http://www.marinetraffic.com/ais/getjson.aspx?sw_x=" + minLon + "&sw_y=" + minLat
+ "&ne_x=" + maxLon + "&ne_y=" + maxLat + "&zoom=12" + "&fleet=&station=0&id=null");
GetMethod get = new GetMethod(url.toString());
get.setRequestHeader("Referer", "http://www.marinetraffic.com/ais/");
client.executeMethod(get);
String json = get.getResponseBodyAsString();
String[][] res = gson.fromJson(json, String[][].class);
for (int i = 0; i < res.length; i++) {
double knots = Double.parseDouble(res[i][5]) / 10;
if (!includeStationary && knots <= 0.2)
continue;
AisShip ship = new AisShip();
ship.setLatitude(Double.parseDouble(res[i][0]));
ship.setLongitude(Double.parseDouble(res[i][1]));
ship.setName(res[i][2]);
ship.setMMSI(Integer.parseInt(res[i][7]));
ship.setSpeed(knots);
if (res[i][4] != null)
ship.setCourse(Double.parseDouble(res[i][4]));
if (res[i][6] != null)
ship.setCountry(res[i][6]);
if (res[i][8] != null)
ship.setLength(Double.parseDouble(res[i][8]));
ships.add(ship);
}
}
catch (Exception e) {
NeptusLog.pub().warn(e);
}
return ships;
}
@Override
public void cleanSubPanel() {
PeriodicUpdatesService.unregister(this);
shipsOnMap.clear();
}
@Override
public void mouseClicked(MouseEvent event, StateRenderer2D source) {
super.mouseClicked(event, source);
JPopupMenu popup = new JPopupMenu();
popup.add("AIS settings").addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PropertiesEditor.editProperties(AisOverlay.this, getConsole(), true);
}
});
popup.add("Update ships").addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
update();
}
});
popup.add(getShipInfoMenu());
popup.show(source, event.getX(), event.getY());
}
@Override
public void paint(Graphics2D g, StateRenderer2D renderer) {
super.paint(g, renderer);
this.renderer = renderer;
if (showOnlyWhenInteractionIsActive && !active)
return;
if (lastThread != null) {
//String strUpdateAIS = I18n.text("Updating AIS layer...");
g.drawString(I18n.text("Updating AIS layer..."), 10, 15);
}
else {
//String strVisShips = I18n.text(" visible ships");
- g.drawString(shipsOnMap.size() + I18n.text(" visible ships"), 10, 15);
+ g.drawString(I18n.textf("%numberOfShips visible ships", shipsOnMap.size()), 10, 15);
}
for (AisShip ship : shipsOnMap) {
Graphics2D clone = (Graphics2D) g.create();
LocationType shipLoc = ship.getLocation();
if (interpolate) {
double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0;
double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps();
double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps();
shipLoc.translatePosition(tx, ty, 0);
}
Point2D pt = renderer.getScreenPosition(shipLoc);
clone.translate(pt.getX(), pt.getY());
Graphics2D clone2 = (Graphics2D) clone.create();
Color c = movingColor;
if (ship.getSpeedKnots() <= 0.2)
c = stationaryColor;
double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9;
double scaleY = (renderer.getZoom() / 10) * ship.getLength();
clone.rotate(Math.PI + ship.getHeadingRads() - renderer.getRotation());
clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128));
clone.setStroke(new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, new float[]{3f, 10f}, 0.0f));
clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60
* renderer.getZoom()));
clone.scale(scaleX, scaleY);
clone.setColor(c);
clone.fill(path);
clone.dispose();
//clone2.rotate(-Math.PI/2 + ship.getHeadingRads());
clone2.setFont(new Font("Helvetica", Font.PLAIN, 8));
clone2.setColor(labelColor);
clone2.drawLine(-3, 0, 3, 0);
clone2.drawLine(0, -3, 0, 3);
if (showNames) {
clone2.drawString(ship.getName(), 5, 5);
}
if (showSpeeds && ship.getSpeedKnots() > 0.2) {
if (useKnots)
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15);
else
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15);
}
clone2.dispose();
}
}
protected JMenu getShipInfoMenu() {
Vector<AisShip> ships = new Vector<>();
JMenu menu = new JMenu("Ship Info");
ships.addAll(shipsOnMap);
Collections.sort(ships);
if (ships.size() > 0 && Desktop.isDesktopSupported()) {
for (final AisShip s : ships) {
menu.add(s.getName()).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Desktop desktop = Desktop.getDesktop();
try {
URI uri = new URI(s.getShipInfoURL());
desktop.browse(uri);
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
});
}
}
else {
menu.setEnabled(false);
}
return menu;
}
@Override
public Collection<JMenuItem> getApplicableItems(LocationType loc, IMapPopup source) {
Vector<JMenuItem> items = new Vector<>();
if (!shipsOnMap.isEmpty())
items.add(getShipInfoMenu());
return items;
}
@Override
public void initSubPanel() {
Vector<IMapPopup> r = getConsole().getSubPanelsOfInterface(IMapPopup.class);
for (IMapPopup str2d : r) {
str2d.addMenuExtension(this);
}
}
}
| true | true | public void paint(Graphics2D g, StateRenderer2D renderer) {
super.paint(g, renderer);
this.renderer = renderer;
if (showOnlyWhenInteractionIsActive && !active)
return;
if (lastThread != null) {
//String strUpdateAIS = I18n.text("Updating AIS layer...");
g.drawString(I18n.text("Updating AIS layer..."), 10, 15);
}
else {
//String strVisShips = I18n.text(" visible ships");
g.drawString(shipsOnMap.size() + I18n.text(" visible ships"), 10, 15);
}
for (AisShip ship : shipsOnMap) {
Graphics2D clone = (Graphics2D) g.create();
LocationType shipLoc = ship.getLocation();
if (interpolate) {
double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0;
double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps();
double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps();
shipLoc.translatePosition(tx, ty, 0);
}
Point2D pt = renderer.getScreenPosition(shipLoc);
clone.translate(pt.getX(), pt.getY());
Graphics2D clone2 = (Graphics2D) clone.create();
Color c = movingColor;
if (ship.getSpeedKnots() <= 0.2)
c = stationaryColor;
double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9;
double scaleY = (renderer.getZoom() / 10) * ship.getLength();
clone.rotate(Math.PI + ship.getHeadingRads() - renderer.getRotation());
clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128));
clone.setStroke(new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, new float[]{3f, 10f}, 0.0f));
clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60
* renderer.getZoom()));
clone.scale(scaleX, scaleY);
clone.setColor(c);
clone.fill(path);
clone.dispose();
//clone2.rotate(-Math.PI/2 + ship.getHeadingRads());
clone2.setFont(new Font("Helvetica", Font.PLAIN, 8));
clone2.setColor(labelColor);
clone2.drawLine(-3, 0, 3, 0);
clone2.drawLine(0, -3, 0, 3);
if (showNames) {
clone2.drawString(ship.getName(), 5, 5);
}
if (showSpeeds && ship.getSpeedKnots() > 0.2) {
if (useKnots)
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15);
else
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15);
}
clone2.dispose();
}
}
| public void paint(Graphics2D g, StateRenderer2D renderer) {
super.paint(g, renderer);
this.renderer = renderer;
if (showOnlyWhenInteractionIsActive && !active)
return;
if (lastThread != null) {
//String strUpdateAIS = I18n.text("Updating AIS layer...");
g.drawString(I18n.text("Updating AIS layer..."), 10, 15);
}
else {
//String strVisShips = I18n.text(" visible ships");
g.drawString(I18n.textf("%numberOfShips visible ships", shipsOnMap.size()), 10, 15);
}
for (AisShip ship : shipsOnMap) {
Graphics2D clone = (Graphics2D) g.create();
LocationType shipLoc = ship.getLocation();
if (interpolate) {
double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0;
double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps();
double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps();
shipLoc.translatePosition(tx, ty, 0);
}
Point2D pt = renderer.getScreenPosition(shipLoc);
clone.translate(pt.getX(), pt.getY());
Graphics2D clone2 = (Graphics2D) clone.create();
Color c = movingColor;
if (ship.getSpeedKnots() <= 0.2)
c = stationaryColor;
double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9;
double scaleY = (renderer.getZoom() / 10) * ship.getLength();
clone.rotate(Math.PI + ship.getHeadingRads() - renderer.getRotation());
clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128));
clone.setStroke(new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, new float[]{3f, 10f}, 0.0f));
clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60
* renderer.getZoom()));
clone.scale(scaleX, scaleY);
clone.setColor(c);
clone.fill(path);
clone.dispose();
//clone2.rotate(-Math.PI/2 + ship.getHeadingRads());
clone2.setFont(new Font("Helvetica", Font.PLAIN, 8));
clone2.setColor(labelColor);
clone2.drawLine(-3, 0, 3, 0);
clone2.drawLine(0, -3, 0, 3);
if (showNames) {
clone2.drawString(ship.getName(), 5, 5);
}
if (showSpeeds && ship.getSpeedKnots() > 0.2) {
if (useKnots)
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15);
else
clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15);
}
clone2.dispose();
}
}
|
diff --git a/de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/Start.java b/de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/Start.java
index 5523e4e5..5833d5ac 100644
--- a/de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/Start.java
+++ b/de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/Start.java
@@ -1,119 +1,112 @@
package de.unisiegen.gtitool.ui;
import java.io.File;
import java.util.Locale;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.log4j.Logger;
import de.unisiegen.gtitool.ui.logic.MainWindow;
import de.unisiegen.gtitool.ui.preferences.PreferenceManager;
/**
* The main starter class for the GTITool project.
*
* @author Christian Fehler
* @version $Id$
*/
public final class Start
{
/**
* The {@link Logger} for this class.
*/
private static final Logger logger = Logger.getLogger ( Start.class );
/**
* The main entry point for the GTI Tool project. This method also sets up
* look and feel for the platform if possible.
*
* @param arguments The command line arguments.
*/
public final static void main ( final String [] arguments )
{
/*
* Install TinyLaF, if it is not the last active look and feel. Otherwise it
* will be installed while set it up.
*/
if ( !PreferenceManager.getInstance ().getLookAndFeelItem ()
.getClassName ().equals ( "de.muntjak.tinylookandfeel.TinyLookAndFeel" ) ) //$NON-NLS-1$
{
UIManager.installLookAndFeel ( "TinyLaF", //$NON-NLS-1$
"de.muntjak.tinylookandfeel.TinyLookAndFeel" ); //$NON-NLS-1$
}
/*
* Set the last active look and feel
*/
try
{
- if ( !PreferenceManager.getInstance ().getLookAndFeelItem ()
- .getClassName ().equals (
- "de.muntjak.tinylookandfeel.TinyLookAndFeel" ) ) //$NON-NLS-1$
- {
- UIManager.installLookAndFeel ( "TinyLaF", //$NON-NLS-1$
- "de.muntjak.tinylookandfeel.TinyLookAndFeel" ); //$NON-NLS-1$
- }
UIManager.setLookAndFeel ( PreferenceManager.getInstance ()
.getLookAndFeelItem ().getClassName () );
}
catch ( ClassNotFoundException exc )
{
logger.error ( "class not found exception", exc ); //$NON-NLS-1$
}
catch ( InstantiationException exc )
{
logger.error ( "instantiation exception", exc ); //$NON-NLS-1$
}
catch ( IllegalAccessException exc )
{
logger.error ( "illegal access exception", exc ); //$NON-NLS-1$
}
catch ( UnsupportedLookAndFeelException exc )
{
logger.error ( "unsupported look and feel exception", exc ); //$NON-NLS-1$
}
/*
* Set the last active language
*/
PreferenceManager.getInstance ().setSystemLocale ( Locale.getDefault () );
Locale.setDefault ( PreferenceManager.getInstance ().getLanguageItem ()
.getLocale () );
/*
* Start the GTI Tool
*/
SwingUtilities.invokeLater ( new Runnable ()
{
// allocate the main window
public void run ()
{
MainWindow window = new MainWindow ();
// check if any files are specified
if ( arguments.length > 0 )
{
// open any specified files
for ( String fileName : arguments )
{
File file = new File ( fileName );
window.openFile ( file, true );
}
}
else
{
// restore the files from the previous session
window.restoreOpenFiles ();
}
}
} );
}
}
| true | true | public final static void main ( final String [] arguments )
{
/*
* Install TinyLaF, if it is not the last active look and feel. Otherwise it
* will be installed while set it up.
*/
if ( !PreferenceManager.getInstance ().getLookAndFeelItem ()
.getClassName ().equals ( "de.muntjak.tinylookandfeel.TinyLookAndFeel" ) ) //$NON-NLS-1$
{
UIManager.installLookAndFeel ( "TinyLaF", //$NON-NLS-1$
"de.muntjak.tinylookandfeel.TinyLookAndFeel" ); //$NON-NLS-1$
}
/*
* Set the last active look and feel
*/
try
{
if ( !PreferenceManager.getInstance ().getLookAndFeelItem ()
.getClassName ().equals (
"de.muntjak.tinylookandfeel.TinyLookAndFeel" ) ) //$NON-NLS-1$
{
UIManager.installLookAndFeel ( "TinyLaF", //$NON-NLS-1$
"de.muntjak.tinylookandfeel.TinyLookAndFeel" ); //$NON-NLS-1$
}
UIManager.setLookAndFeel ( PreferenceManager.getInstance ()
.getLookAndFeelItem ().getClassName () );
}
catch ( ClassNotFoundException exc )
{
logger.error ( "class not found exception", exc ); //$NON-NLS-1$
}
catch ( InstantiationException exc )
{
logger.error ( "instantiation exception", exc ); //$NON-NLS-1$
}
catch ( IllegalAccessException exc )
{
logger.error ( "illegal access exception", exc ); //$NON-NLS-1$
}
catch ( UnsupportedLookAndFeelException exc )
{
logger.error ( "unsupported look and feel exception", exc ); //$NON-NLS-1$
}
/*
* Set the last active language
*/
PreferenceManager.getInstance ().setSystemLocale ( Locale.getDefault () );
Locale.setDefault ( PreferenceManager.getInstance ().getLanguageItem ()
.getLocale () );
/*
* Start the GTI Tool
*/
SwingUtilities.invokeLater ( new Runnable ()
{
// allocate the main window
public void run ()
{
MainWindow window = new MainWindow ();
// check if any files are specified
if ( arguments.length > 0 )
{
// open any specified files
for ( String fileName : arguments )
{
File file = new File ( fileName );
window.openFile ( file, true );
}
}
else
{
// restore the files from the previous session
window.restoreOpenFiles ();
}
}
} );
}
| public final static void main ( final String [] arguments )
{
/*
* Install TinyLaF, if it is not the last active look and feel. Otherwise it
* will be installed while set it up.
*/
if ( !PreferenceManager.getInstance ().getLookAndFeelItem ()
.getClassName ().equals ( "de.muntjak.tinylookandfeel.TinyLookAndFeel" ) ) //$NON-NLS-1$
{
UIManager.installLookAndFeel ( "TinyLaF", //$NON-NLS-1$
"de.muntjak.tinylookandfeel.TinyLookAndFeel" ); //$NON-NLS-1$
}
/*
* Set the last active look and feel
*/
try
{
UIManager.setLookAndFeel ( PreferenceManager.getInstance ()
.getLookAndFeelItem ().getClassName () );
}
catch ( ClassNotFoundException exc )
{
logger.error ( "class not found exception", exc ); //$NON-NLS-1$
}
catch ( InstantiationException exc )
{
logger.error ( "instantiation exception", exc ); //$NON-NLS-1$
}
catch ( IllegalAccessException exc )
{
logger.error ( "illegal access exception", exc ); //$NON-NLS-1$
}
catch ( UnsupportedLookAndFeelException exc )
{
logger.error ( "unsupported look and feel exception", exc ); //$NON-NLS-1$
}
/*
* Set the last active language
*/
PreferenceManager.getInstance ().setSystemLocale ( Locale.getDefault () );
Locale.setDefault ( PreferenceManager.getInstance ().getLanguageItem ()
.getLocale () );
/*
* Start the GTI Tool
*/
SwingUtilities.invokeLater ( new Runnable ()
{
// allocate the main window
public void run ()
{
MainWindow window = new MainWindow ();
// check if any files are specified
if ( arguments.length > 0 )
{
// open any specified files
for ( String fileName : arguments )
{
File file = new File ( fileName );
window.openFile ( file, true );
}
}
else
{
// restore the files from the previous session
window.restoreOpenFiles ();
}
}
} );
}
|
diff --git a/drools-pipeline/drools-camel/src/test/java/org/drools/camel/component/CamelEndpointWithJaxbXSDModelTest.java b/drools-pipeline/drools-camel/src/test/java/org/drools/camel/component/CamelEndpointWithJaxbXSDModelTest.java
index 6c5226495..2d896ec14 100644
--- a/drools-pipeline/drools-camel/src/test/java/org/drools/camel/component/CamelEndpointWithJaxbXSDModelTest.java
+++ b/drools-pipeline/drools-camel/src/test/java/org/drools/camel/component/CamelEndpointWithJaxbXSDModelTest.java
@@ -1,289 +1,289 @@
package org.drools.camel.component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.apache.camel.builder.RouteBuilder;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.ResourceType;
import org.drools.builder.help.KnowledgeBuilderHelper;
import org.drools.command.runtime.BatchExecutionCommand;
import org.drools.command.runtime.rule.FireAllRulesCommand;
import org.drools.command.runtime.rule.InsertObjectCommand;
import org.drools.common.InternalRuleBase;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.io.ResourceFactory;
import org.drools.rule.DroolsCompositeClassLoader;
import org.drools.runtime.ExecutionResults;
import org.drools.runtime.StatefulKnowledgeSession;
import com.sun.tools.xjc.Language;
import com.sun.tools.xjc.Options;
/**
*
* @author Lucas Amador
* @author Pablo Nussembaum
*
*/
public class CamelEndpointWithJaxbXSDModelTest extends DroolsCamelTestSupport {
private JAXBContext jaxbContext;
private DroolsCompositeClassLoader classLoader;
public void testSessionInsert() throws Exception {
Class<?> personClass = classLoader.loadClass("org.drools.model.Person");
assertNotNull(personClass.getPackage());
Class<?> addressClass = classLoader.loadClass("org.drools.model.AddressType");
assertNotNull(addressClass.getPackage());
Object baunax = personClass.newInstance();
Object lucaz = personClass.newInstance();
Method setName = personClass.getMethod("setName", String.class);
setName.invoke(baunax, "baunax");
setName.invoke(lucaz, "lucaz");
Method setAddress = personClass.getMethod("setAddress", addressClass);
Method setStreet = addressClass.getMethod("setStreet", String.class);
Method setPostalCode = addressClass.getMethod("setPostalCode", BigInteger.class);
Object lucazAddress = addressClass.newInstance();
setStreet.invoke(lucazAddress, "Unknow 342");
setPostalCode.invoke(lucazAddress, new BigInteger("1234"));
Object baunaxAddress = addressClass.newInstance();
setStreet.invoke(baunaxAddress, "New Street 123");
setPostalCode.invoke(baunaxAddress, new BigInteger("5678"));
setAddress.invoke(lucaz, lucazAddress);
setAddress.invoke(baunax, baunaxAddress);
BatchExecutionCommand cmd = new BatchExecutionCommand();
cmd.setLookup("ksession1");
cmd.getCommands().add(new InsertObjectCommand(lucaz, "lucaz"));
cmd.getCommands().add(new InsertObjectCommand(baunax, "baunax"));
cmd.getCommands().add(new FireAllRulesCommand());
StringWriter xmlReq = new StringWriter();
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
marshaller.marshal(cmd, xmlReq);
System.out.println(xmlReq.toString());
String xmlCmd = "";
xmlCmd += "<batch-execution lookup='ksession1'>\n";
xmlCmd += " <insert out-identifier='lucaz'>\n";
xmlCmd += " <object>\n";
xmlCmd += " <Person xmlns='http://drools.org/model' >\n";
xmlCmd += " <name>lucaz</name>\n";
xmlCmd += " <age>25</age>\n";
xmlCmd += " </Person>\n";
xmlCmd += " </object>\n";
xmlCmd += " </insert>\n";
xmlCmd += " <insert out-identifier='baunax'>\n";
xmlCmd += " <object>\n";
xmlCmd += " <Person xmlns='http://drools.org/model' >\n";
xmlCmd += " <name>baunax</name>\n";
xmlCmd += " <age>21</age>\n";
xmlCmd += " </Person>\n";
xmlCmd += " </object>\n";
xmlCmd += " </insert>\n";
xmlCmd += " <fire-all-rules />";
xmlCmd += "</batch-execution>\n";
byte[] xmlResp = (byte[]) template.requestBodyAndHeader("direct:test-with-session", xmlReq.toString(), "jaxb-context", jaxbContext);
assertNotNull(xmlResp);
System.out.println(new String(xmlResp));
ExecutionResults resp = (ExecutionResults) jaxbContext.createUnmarshaller().unmarshal(new ByteArrayInputStream(xmlResp));
assertNotNull(resp);
assertEquals(2, resp.getIdentifiers().size());
assertNotNull(resp.getValue("lucaz"));
assertNotNull(resp.getValue("baunax"));
assertNotNull(resp.getFactHandle("lucaz"));
assertNotNull(resp.getFactHandle("baunax"));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("direct:test-with-session").to("drools:sm/ksession1?dataFormat=drools-jaxb");
from("direct:test-no-session").to("drools:sm?dataFormat=drools-jaxb");
}
};
}
@Override
protected void configureDroolsContext() {
String rule = "";
rule += "package org.drools \n";
rule += "import org.drools.model.Person \n";
rule += "global java.util.List list \n";
rule += "query persons \n";
rule += " $p : Person(name != null) \n";
rule += "end \n";
rule += "query personWithName(String param)\n";
rule += " $p : Person(name == param) \n";
rule += "end \n";
rule += "rule rule1 \n";
rule += " when \n";
rule += " $p : Person() \n";
rule += " \n";
rule += " then \n";
rule += " System.out.println(\"executed\"); \n";
rule += "end\n";
registerKnowledgeRuntime("ksession1", rule);
}
@Override
protected StatefulKnowledgeSession registerKnowledgeRuntime(String identifier, String rule) {
KnowledgeBuilder kbuilder = serviceManager.getKnowledgeBuilderFactoryService().newKnowledgeBuilder();
Options xjcOpts = new Options();
xjcOpts.setSchemaLanguage( Language.XMLSCHEMA );
String classNames[] = null;
try {
- classNames = KnowledgeBuilderHelper.addXsdModel( ResourceFactory.newClassPathResource("personComplex.xsd", getClass()),
+ classNames = KnowledgeBuilderHelper.addXsdModel( ResourceFactory.newClassPathResource("person.xsd", getClass()),
kbuilder,
xjcOpts,
"xsd" );
} catch (IOException e) {
LOG.error("Errors while adding xsd model. ", kbuilder.getErrors());
}
assertFalse( kbuilder.hasErrors() );
if (rule != null && rule.length() > 0) {
kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding rule. ", kbuilder.getErrors());
}
}
String process1 = "";
process1 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process1 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process1 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process1 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process1 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
process1 += "\n";
process1 += " <header>\n";
process1 += " <imports>\n";
process1 += " <import name=\"org.drools.model.Person\" />\n";
process1 += " </imports>\n";
process1 += " <globals>\n";
process1 += " <global identifier=\"list\" type=\"java.util.List\" />\n";
process1 += " </globals>\n";
process1 += " <variables>\n";
process1 += " <variable name=\"person\" >\n";
process1 += " <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"Person\" />\n";
process1 += " </variable>\n";
process1 += " </variables>\n";
process1 += " </header>\n";
process1 += "\n";
process1 += " <nodes>\n";
process1 += " <start id=\"1\" name=\"Start\" />\n";
process1 += " <actionNode id=\"2\" name=\"MyActionNode\" >\n";
process1 += " <action type=\"expression\" dialect=\"mvel\" >System.out.println(\"Triggered\");\n";
process1 += "list.add(person.name);\n";
process1 += "</action>\n";
process1 += " </actionNode>\n";
process1 += " <end id=\"3\" name=\"End\" />\n";
process1 += " </nodes>\n";
process1 += "\n";
process1 += " <connections>\n";
process1 += " <connection from=\"1\" to=\"2\" />\n";
process1 += " <connection from=\"2\" to=\"3\" />\n";
process1 += " </connections>\n" + "\n";
process1 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process1.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
System.out.println("Errors while adding process rule 1. " + kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
String process2 = "";
process2 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process2 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process2 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process2 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process2 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.event\" package-name=\"org.drools\" version=\"1\" >\n";
process2 += "\n";
process2 += " <header>\n";
process2 += " <variables>\n";
process2 += " <variable name=\"MyVar\" >\n";
process2 += " <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
process2 += " <value>SomeText</value>\n";
process2 += " </variable>\n";
process2 += " </variables>\n";
process2 += " </header>\n";
process2 += "\n";
process2 += " <nodes>\n";
process2 += " <start id=\"1\" name=\"Start\" />\n";
process2 += " <eventNode id=\"2\" name=\"Event\" variableName=\"MyVar\" >\n";
process2 += " <eventFilters>\n";
process2 += " <eventFilter type=\"eventType\" eventType=\"MyEvent\" />\n";
process2 += " </eventFilters>\n";
process2 += " </eventNode>\n";
process2 += " <join id=\"3\" name=\"Join\" type=\"1\" />\n";
process2 += " <end id=\"4\" name=\"End\" />\n";
process2 += " </nodes>\n";
process2 += "\n";
process2 += " <connections>\n";
process2 += " <connection from=\"1\" to=\"3\" />\n";
process2 += " <connection from=\"2\" to=\"3\" />\n";
process2 += " <connection from=\"3\" to=\"4\" />\n";
process2 += " </connections>\n";
process2 += "\n";
process2 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process2.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding process rule 2. ", kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
KnowledgeBase kbase = serviceManager.getKnowledgeBaseFactoryService().newKnowledgeBase();
classLoader = ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).getRuleBase()).getRootClassLoader();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
// Add object model to classes array
List<String> allClasses = new ArrayList<String>(Arrays.asList(classNames));
try {
jaxbContext = KnowledgeBuilderHelper.newJAXBContext( allClasses.toArray(new String[allClasses.size()]), kbase );
} catch (Exception e) {
LOG.info("Errors while creating JAXB Context. ", e);
e.printStackTrace();
throw new RuntimeException(e);
}
StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
serviceManager.register(identifier, session);
return session;
}
}
| true | true | protected StatefulKnowledgeSession registerKnowledgeRuntime(String identifier, String rule) {
KnowledgeBuilder kbuilder = serviceManager.getKnowledgeBuilderFactoryService().newKnowledgeBuilder();
Options xjcOpts = new Options();
xjcOpts.setSchemaLanguage( Language.XMLSCHEMA );
String classNames[] = null;
try {
classNames = KnowledgeBuilderHelper.addXsdModel( ResourceFactory.newClassPathResource("personComplex.xsd", getClass()),
kbuilder,
xjcOpts,
"xsd" );
} catch (IOException e) {
LOG.error("Errors while adding xsd model. ", kbuilder.getErrors());
}
assertFalse( kbuilder.hasErrors() );
if (rule != null && rule.length() > 0) {
kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding rule. ", kbuilder.getErrors());
}
}
String process1 = "";
process1 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process1 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process1 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process1 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process1 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
process1 += "\n";
process1 += " <header>\n";
process1 += " <imports>\n";
process1 += " <import name=\"org.drools.model.Person\" />\n";
process1 += " </imports>\n";
process1 += " <globals>\n";
process1 += " <global identifier=\"list\" type=\"java.util.List\" />\n";
process1 += " </globals>\n";
process1 += " <variables>\n";
process1 += " <variable name=\"person\" >\n";
process1 += " <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"Person\" />\n";
process1 += " </variable>\n";
process1 += " </variables>\n";
process1 += " </header>\n";
process1 += "\n";
process1 += " <nodes>\n";
process1 += " <start id=\"1\" name=\"Start\" />\n";
process1 += " <actionNode id=\"2\" name=\"MyActionNode\" >\n";
process1 += " <action type=\"expression\" dialect=\"mvel\" >System.out.println(\"Triggered\");\n";
process1 += "list.add(person.name);\n";
process1 += "</action>\n";
process1 += " </actionNode>\n";
process1 += " <end id=\"3\" name=\"End\" />\n";
process1 += " </nodes>\n";
process1 += "\n";
process1 += " <connections>\n";
process1 += " <connection from=\"1\" to=\"2\" />\n";
process1 += " <connection from=\"2\" to=\"3\" />\n";
process1 += " </connections>\n" + "\n";
process1 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process1.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
System.out.println("Errors while adding process rule 1. " + kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
String process2 = "";
process2 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process2 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process2 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process2 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process2 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.event\" package-name=\"org.drools\" version=\"1\" >\n";
process2 += "\n";
process2 += " <header>\n";
process2 += " <variables>\n";
process2 += " <variable name=\"MyVar\" >\n";
process2 += " <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
process2 += " <value>SomeText</value>\n";
process2 += " </variable>\n";
process2 += " </variables>\n";
process2 += " </header>\n";
process2 += "\n";
process2 += " <nodes>\n";
process2 += " <start id=\"1\" name=\"Start\" />\n";
process2 += " <eventNode id=\"2\" name=\"Event\" variableName=\"MyVar\" >\n";
process2 += " <eventFilters>\n";
process2 += " <eventFilter type=\"eventType\" eventType=\"MyEvent\" />\n";
process2 += " </eventFilters>\n";
process2 += " </eventNode>\n";
process2 += " <join id=\"3\" name=\"Join\" type=\"1\" />\n";
process2 += " <end id=\"4\" name=\"End\" />\n";
process2 += " </nodes>\n";
process2 += "\n";
process2 += " <connections>\n";
process2 += " <connection from=\"1\" to=\"3\" />\n";
process2 += " <connection from=\"2\" to=\"3\" />\n";
process2 += " <connection from=\"3\" to=\"4\" />\n";
process2 += " </connections>\n";
process2 += "\n";
process2 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process2.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding process rule 2. ", kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
KnowledgeBase kbase = serviceManager.getKnowledgeBaseFactoryService().newKnowledgeBase();
classLoader = ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).getRuleBase()).getRootClassLoader();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
// Add object model to classes array
List<String> allClasses = new ArrayList<String>(Arrays.asList(classNames));
try {
jaxbContext = KnowledgeBuilderHelper.newJAXBContext( allClasses.toArray(new String[allClasses.size()]), kbase );
} catch (Exception e) {
LOG.info("Errors while creating JAXB Context. ", e);
e.printStackTrace();
throw new RuntimeException(e);
}
StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
serviceManager.register(identifier, session);
return session;
}
| protected StatefulKnowledgeSession registerKnowledgeRuntime(String identifier, String rule) {
KnowledgeBuilder kbuilder = serviceManager.getKnowledgeBuilderFactoryService().newKnowledgeBuilder();
Options xjcOpts = new Options();
xjcOpts.setSchemaLanguage( Language.XMLSCHEMA );
String classNames[] = null;
try {
classNames = KnowledgeBuilderHelper.addXsdModel( ResourceFactory.newClassPathResource("person.xsd", getClass()),
kbuilder,
xjcOpts,
"xsd" );
} catch (IOException e) {
LOG.error("Errors while adding xsd model. ", kbuilder.getErrors());
}
assertFalse( kbuilder.hasErrors() );
if (rule != null && rule.length() > 0) {
kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding rule. ", kbuilder.getErrors());
}
}
String process1 = "";
process1 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process1 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process1 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process1 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process1 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
process1 += "\n";
process1 += " <header>\n";
process1 += " <imports>\n";
process1 += " <import name=\"org.drools.model.Person\" />\n";
process1 += " </imports>\n";
process1 += " <globals>\n";
process1 += " <global identifier=\"list\" type=\"java.util.List\" />\n";
process1 += " </globals>\n";
process1 += " <variables>\n";
process1 += " <variable name=\"person\" >\n";
process1 += " <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"Person\" />\n";
process1 += " </variable>\n";
process1 += " </variables>\n";
process1 += " </header>\n";
process1 += "\n";
process1 += " <nodes>\n";
process1 += " <start id=\"1\" name=\"Start\" />\n";
process1 += " <actionNode id=\"2\" name=\"MyActionNode\" >\n";
process1 += " <action type=\"expression\" dialect=\"mvel\" >System.out.println(\"Triggered\");\n";
process1 += "list.add(person.name);\n";
process1 += "</action>\n";
process1 += " </actionNode>\n";
process1 += " <end id=\"3\" name=\"End\" />\n";
process1 += " </nodes>\n";
process1 += "\n";
process1 += " <connections>\n";
process1 += " <connection from=\"1\" to=\"2\" />\n";
process1 += " <connection from=\"2\" to=\"3\" />\n";
process1 += " </connections>\n" + "\n";
process1 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process1.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
System.out.println("Errors while adding process rule 1. " + kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
String process2 = "";
process2 += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
process2 += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
process2 += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
process2 += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
process2 += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.event\" package-name=\"org.drools\" version=\"1\" >\n";
process2 += "\n";
process2 += " <header>\n";
process2 += " <variables>\n";
process2 += " <variable name=\"MyVar\" >\n";
process2 += " <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
process2 += " <value>SomeText</value>\n";
process2 += " </variable>\n";
process2 += " </variables>\n";
process2 += " </header>\n";
process2 += "\n";
process2 += " <nodes>\n";
process2 += " <start id=\"1\" name=\"Start\" />\n";
process2 += " <eventNode id=\"2\" name=\"Event\" variableName=\"MyVar\" >\n";
process2 += " <eventFilters>\n";
process2 += " <eventFilter type=\"eventType\" eventType=\"MyEvent\" />\n";
process2 += " </eventFilters>\n";
process2 += " </eventNode>\n";
process2 += " <join id=\"3\" name=\"Join\" type=\"1\" />\n";
process2 += " <end id=\"4\" name=\"End\" />\n";
process2 += " </nodes>\n";
process2 += "\n";
process2 += " <connections>\n";
process2 += " <connection from=\"1\" to=\"3\" />\n";
process2 += " <connection from=\"2\" to=\"3\" />\n";
process2 += " <connection from=\"3\" to=\"4\" />\n";
process2 += " </connections>\n";
process2 += "\n";
process2 += "</process>";
kbuilder.add(ResourceFactory.newByteArrayResource(process2.getBytes()), ResourceType.DRF);
if (kbuilder.hasErrors()) {
LOG.info("Errors while adding process rule 2. ", kbuilder.getErrors());
}
assertFalse(kbuilder.hasErrors());
KnowledgeBase kbase = serviceManager.getKnowledgeBaseFactoryService().newKnowledgeBase();
classLoader = ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).getRuleBase()).getRootClassLoader();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
// Add object model to classes array
List<String> allClasses = new ArrayList<String>(Arrays.asList(classNames));
try {
jaxbContext = KnowledgeBuilderHelper.newJAXBContext( allClasses.toArray(new String[allClasses.size()]), kbase );
} catch (Exception e) {
LOG.info("Errors while creating JAXB Context. ", e);
e.printStackTrace();
throw new RuntimeException(e);
}
StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
serviceManager.register(identifier, session);
return session;
}
|
diff --git a/common/cpw/mods/fml/common/registry/GameRegistry.java b/common/cpw/mods/fml/common/registry/GameRegistry.java
index 06b05723..ea019b80 100644
--- a/common/cpw/mods/fml/common/registry/GameRegistry.java
+++ b/common/cpw/mods/fml/common/registry/GameRegistry.java
@@ -1,433 +1,433 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.registry;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import com.google.common.base.Function;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ICraftingHandler;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.IPickupNotifier;
import cpw.mods.fml.common.IPlayerTracker;
import cpw.mods.fml.common.IWorldGenerator;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.common.Mod.Block;
import cpw.mods.fml.common.ModContainer;
public class GameRegistry
{
private static Multimap<ModContainer, BlockProxy> blockRegistry = ArrayListMultimap.create();
private static Set<IWorldGenerator> worldGenerators = Sets.newHashSet();
private static List<IFuelHandler> fuelHandlers = Lists.newArrayList();
private static List<ICraftingHandler> craftingHandlers = Lists.newArrayList();
private static List<IPickupNotifier> pickupHandlers = Lists.newArrayList();
private static List<IPlayerTracker> playerTrackers = Lists.newArrayList();
/**
* Register a world generator - something that inserts new block types into the world
*
* @param generator
*/
public static void registerWorldGenerator(IWorldGenerator generator)
{
worldGenerators.add(generator);
}
/**
* Callback hook for world gen - if your mod wishes to add extra mod related generation to the world
* call this
*
* @param chunkX
* @param chunkZ
* @param world
* @param chunkGenerator
* @param chunkProvider
*/
public static void generateWorld(int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
long worldSeed = world.func_72905_C();
Random fmlRandom = new Random(worldSeed);
long xSeed = fmlRandom.nextLong() >> 2 + 1L;
long zSeed = fmlRandom.nextLong() >> 2 + 1L;
fmlRandom.setSeed((xSeed * chunkX + zSeed * chunkZ) ^ worldSeed);
for (IWorldGenerator generator : worldGenerators)
{
generator.generate(fmlRandom, chunkX, chunkZ, world, chunkGenerator, chunkProvider);
}
}
/**
* Internal method for creating an @Block instance
* @param container
* @param type
* @param annotation
* @throws Exception
*/
public static Object buildBlock(ModContainer container, Class<?> type, Block annotation) throws Exception
{
Object o = type.getConstructor(int.class).newInstance(findSpareBlockId());
registerBlock((net.minecraft.block.Block) o);
return o;
}
/**
* Private and not yet working properly
*
* @return a block id
*/
private static int findSpareBlockId()
{
return BlockTracker.nextBlockId();
}
/**
* Register an item with the item registry with a custom name : this allows for easier server->client resolution
*
* @param item The item to register
* @param name The mod-unique name of the item
*/
public static void registerItem(net.minecraft.item.Item item, String name)
{
registerItem(item, name, null);
}
/**
* Register the specified Item with a mod specific name : overrides the standard type based name
* @param item The item to register
* @param name The mod-unique name to register it as - null will remove a custom name
* @param modId An optional modId that will "own" this block - generally used by multi-mod systems
* where one mod should "own" all the blocks of all the mods, null defaults to the active mod
*/
public static void registerItem(net.minecraft.item.Item item, String name, String modId)
{
GameData.setName(item, name, modId);
}
/**
* Register a block with the world
*
*/
@Deprecated
public static void registerBlock(net.minecraft.block.Block block)
{
registerBlock(block, ItemBlock.class);
}
/**
* Register a block with the specified mod specific name : overrides the standard type based name
* @param block The block to register
* @param name The mod-unique name to register it as
*/
public static void registerBlock(net.minecraft.block.Block block, String name)
{
registerBlock(block, ItemBlock.class, name);
}
/**
* Register a block with the world, with the specified item class
*
* Deprecated in favour of named versions
*
* @param block The block to register
* @param itemclass The item type to register with it
*/
@Deprecated
public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass)
{
registerBlock(block, itemclass, null);
}
/**
* Register a block with the world, with the specified item class and block name
* @param block The block to register
* @param itemclass The item type to register with it
* @param name The mod-unique name to register it with
*/
public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name)
{
registerBlock(block, itemclass, name, null);
}
/**
* Register a block with the world, with the specified item class, block name and owning modId
* @param block The block to register
* @param itemclass The iterm type to register with it
* @param name The mod-unique name to register it with
* @param modId The modId that will own the block name. null defaults to the active modId
*/
public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId)
{
if (Loader.instance().isInState(LoaderState.CONSTRUCTING))
{
FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer());
}
try
{
assert block != null : "registerBlock: block cannot be null";
assert itemclass != null : "registerBlock: itemclass cannot be null";
int blockItemId = block.field_71990_ca - 256;
Constructor<? extends ItemBlock> itemCtor;
Item i;
try
{
itemCtor = itemclass.getConstructor(int.class);
i = itemCtor.newInstance(blockItemId);
}
catch (NoSuchMethodException e)
{
- itemCtor = itemclass.getConstructor(int.class, Block.class);
+ itemCtor = itemclass.getConstructor(int.class, net.minecraft.block.Block.class);
i = itemCtor.newInstance(blockItemId, block);
}
GameRegistry.registerItem(i,name, modId);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration");
throw new LoaderException(e);
}
blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block);
}
public static void addRecipe(ItemStack output, Object... params)
{
addShapedRecipe(output, params);
}
public static IRecipe addShapedRecipe(ItemStack output, Object... params)
{
return CraftingManager.func_77594_a().func_92103_a(output, params);
}
public static void addShapelessRecipe(ItemStack output, Object... params)
{
CraftingManager.func_77594_a().func_77596_b(output, params);
}
public static void addRecipe(IRecipe recipe)
{
CraftingManager.func_77594_a().func_77592_b().add(recipe);
}
public static void addSmelting(int input, ItemStack output, float xp)
{
FurnaceRecipes.func_77602_a().func_77600_a(input, output, xp);
}
public static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String id)
{
TileEntity.func_70306_a(tileEntityClass, id);
}
/**
* Register a tile entity, with alternative TileEntity identifiers. Use with caution!
* This method allows for you to "rename" the 'id' of the tile entity.
*
* @param tileEntityClass The tileEntity class to register
* @param id The primary ID, this will be the ID that the tileentity saves as
* @param alternatives A list of alternative IDs that will also map to this class. These will never save, but they will load
*/
public static void registerTileEntityWithAlternatives(Class<? extends TileEntity> tileEntityClass, String id, String... alternatives)
{
TileEntity.func_70306_a(tileEntityClass, id);
Map<String,Class> teMappings = ObfuscationReflectionHelper.getPrivateValue(TileEntity.class, null, "field_" + "70326_a", "field_70326_a", "a");
for (String s: alternatives)
{
if (!teMappings.containsKey(s))
{
teMappings.put(s, tileEntityClass);
}
}
}
public static void addBiome(BiomeGenBase biome)
{
WorldType.field_77137_b.addNewBiome(biome);
}
public static void removeBiome(BiomeGenBase biome)
{
WorldType.field_77137_b.removeBiome(biome);
}
public static void registerFuelHandler(IFuelHandler handler)
{
fuelHandlers.add(handler);
}
public static int getFuelValue(ItemStack itemStack)
{
int fuelValue = 0;
for (IFuelHandler handler : fuelHandlers)
{
fuelValue = Math.max(fuelValue, handler.getBurnTime(itemStack));
}
return fuelValue;
}
public static void registerCraftingHandler(ICraftingHandler handler)
{
craftingHandlers.add(handler);
}
public static void onItemCrafted(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
for (ICraftingHandler handler : craftingHandlers)
{
handler.onCrafting(player, item, craftMatrix);
}
}
public static void onItemSmelted(EntityPlayer player, ItemStack item)
{
for (ICraftingHandler handler : craftingHandlers)
{
handler.onSmelting(player, item);
}
}
public static void registerPickupHandler(IPickupNotifier handler)
{
pickupHandlers.add(handler);
}
public static void onPickupNotification(EntityPlayer player, EntityItem item)
{
for (IPickupNotifier notify : pickupHandlers)
{
notify.notifyPickup(item, player);
}
}
public static void registerPlayerTracker(IPlayerTracker tracker)
{
playerTrackers.add(tracker);
}
public static void onPlayerLogin(EntityPlayer player)
{
for(IPlayerTracker tracker : playerTrackers)
tracker.onPlayerLogin(player);
}
public static void onPlayerLogout(EntityPlayer player)
{
for(IPlayerTracker tracker : playerTrackers)
tracker.onPlayerLogout(player);
}
public static void onPlayerChangedDimension(EntityPlayer player)
{
for(IPlayerTracker tracker : playerTrackers)
tracker.onPlayerChangedDimension(player);
}
public static void onPlayerRespawn(EntityPlayer player)
{
for(IPlayerTracker tracker : playerTrackers)
tracker.onPlayerRespawn(player);
}
/**
* Look up a mod block in the global "named item list"
* @param modId The modid owning the block
* @param name The name of the block itself
* @return The block or null if not found
*/
public static net.minecraft.block.Block findBlock(String modId, String name)
{
return GameData.findBlock(modId, name);
}
/**
* Look up a mod item in the global "named item list"
* @param modId The modid owning the item
* @param name The name of the item itself
* @return The item or null if not found
*/
public static net.minecraft.item.Item findItem(String modId, String name)
{
return GameData.findItem(modId, name);
}
/**
* Manually register a custom item stack with FML for later tracking. It is automatically scoped with the active modid
*
* @param name The name to register it under
* @param itemStack The itemstack to register
*/
public static void registerCustomItemStack(String name, ItemStack itemStack)
{
GameData.registerCustomItemStack(name, itemStack);
}
/**
* Lookup an itemstack based on mod and name. It will create "default" itemstacks from blocks and items if no
* explicit itemstack is found.
*
* If it is built from a block, the metadata is by default the "wildcard" value.
*
* Custom itemstacks can be dumped from minecraft by setting the system property fml.dumpRegistry to true
* (-Dfml.dumpRegistry=true on the command line will work)
*
* @param modId The modid of the stack owner
* @param name The name of the stack
* @param stackSize The size of the stack returned
* @return The custom itemstack or null if no such itemstack was found
*/
public static ItemStack findItemStack(String modId, String name, int stackSize)
{
ItemStack foundStack = GameData.findItemStack(modId, name);
if (foundStack != null)
{
ItemStack is = foundStack.func_77946_l();
is.field_77994_a = Math.min(stackSize, is.func_77976_d());
return is;
}
return null;
}
}
| true | true | public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId)
{
if (Loader.instance().isInState(LoaderState.CONSTRUCTING))
{
FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer());
}
try
{
assert block != null : "registerBlock: block cannot be null";
assert itemclass != null : "registerBlock: itemclass cannot be null";
int blockItemId = block.field_71990_ca - 256;
Constructor<? extends ItemBlock> itemCtor;
Item i;
try
{
itemCtor = itemclass.getConstructor(int.class);
i = itemCtor.newInstance(blockItemId);
}
catch (NoSuchMethodException e)
{
itemCtor = itemclass.getConstructor(int.class, Block.class);
i = itemCtor.newInstance(blockItemId, block);
}
GameRegistry.registerItem(i,name, modId);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration");
throw new LoaderException(e);
}
blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block);
}
| public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId)
{
if (Loader.instance().isInState(LoaderState.CONSTRUCTING))
{
FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer());
}
try
{
assert block != null : "registerBlock: block cannot be null";
assert itemclass != null : "registerBlock: itemclass cannot be null";
int blockItemId = block.field_71990_ca - 256;
Constructor<? extends ItemBlock> itemCtor;
Item i;
try
{
itemCtor = itemclass.getConstructor(int.class);
i = itemCtor.newInstance(blockItemId);
}
catch (NoSuchMethodException e)
{
itemCtor = itemclass.getConstructor(int.class, net.minecraft.block.Block.class);
i = itemCtor.newInstance(blockItemId, block);
}
GameRegistry.registerItem(i,name, modId);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration");
throw new LoaderException(e);
}
blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block);
}
|
diff --git a/src/com/hourlyweather/web/HourlyWeatherByCityForward.java b/src/com/hourlyweather/web/HourlyWeatherByCityForward.java
index 3b26f07..f91b2f2 100644
--- a/src/com/hourlyweather/web/HourlyWeatherByCityForward.java
+++ b/src/com/hourlyweather/web/HourlyWeatherByCityForward.java
@@ -1,44 +1,48 @@
package com.hourlyweather.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
@SuppressWarnings("serial")
public class HourlyWeatherByCityForward extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
+ //not finished, regex for getting ending?
+ /*int start = request.getRequestURI().lastIndexOf('/');
+ int end = request.getRequestURI().indexOf('#');
+ String cityName = request.getRequestURI().substring(start, end);*/
Key cityKey = KeyFactory.createKey(City.ENTITY, request.getParameter("id"));
//query database for city geo data
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
City city;
try {
city = new City(ds.get(cityKey));
} catch (EntityNotFoundException e) {
throw new LocationException(cityKey + " wasn't found.");
}
request.setAttribute("city", city.getName());
request.setAttribute("lat", city.getLatitude());
request.setAttribute("lon", city.getLongitude());
request.setAttribute("timeOffset", city.getTimezone());
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/");
dispatcher.forward(request, response);
}
}
| true | true | protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Key cityKey = KeyFactory.createKey(City.ENTITY, request.getParameter("id"));
//query database for city geo data
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
City city;
try {
city = new City(ds.get(cityKey));
} catch (EntityNotFoundException e) {
throw new LocationException(cityKey + " wasn't found.");
}
request.setAttribute("city", city.getName());
request.setAttribute("lat", city.getLatitude());
request.setAttribute("lon", city.getLongitude());
request.setAttribute("timeOffset", city.getTimezone());
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/");
dispatcher.forward(request, response);
}
| protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//not finished, regex for getting ending?
/*int start = request.getRequestURI().lastIndexOf('/');
int end = request.getRequestURI().indexOf('#');
String cityName = request.getRequestURI().substring(start, end);*/
Key cityKey = KeyFactory.createKey(City.ENTITY, request.getParameter("id"));
//query database for city geo data
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
City city;
try {
city = new City(ds.get(cityKey));
} catch (EntityNotFoundException e) {
throw new LocationException(cityKey + " wasn't found.");
}
request.setAttribute("city", city.getName());
request.setAttribute("lat", city.getLatitude());
request.setAttribute("lon", city.getLongitude());
request.setAttribute("timeOffset", city.getTimezone());
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/");
dispatcher.forward(request, response);
}
|
diff --git a/SimSeqNBProject/src/simseq/SeqSampler.java b/SimSeqNBProject/src/simseq/SeqSampler.java
index 1b02e37..6aad5d8 100644
--- a/SimSeqNBProject/src/simseq/SeqSampler.java
+++ b/SimSeqNBProject/src/simseq/SeqSampler.java
@@ -1,258 +1,253 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package simseq;
import java.util.Random;
/**
*
* @author jstjohn
*/
public class SeqSampler{
private String seq;
private int len;
public SeqSampler(String sequence){
this.seq = sequence;
this.len = sequence.length();
}
public void PESample(SamRecord sr1,
SamRecord sr2, String qual1, String qual2,
int mean_ins, int stdev,
int read1_len, int read2_len, Random r){
int p,l;
if(mean_ins > this.len){
throw new RuntimeException("Fasta file has shorter sequence than the requested mean library length");
}
//increment the seq index
sr1.seqIndex++;
sr2.seqIndex++;
do{
p = r.nextInt(this.len);
l = ((int)(r.nextGaussian()*((double)stdev))) + mean_ins;
}while((p+l)>this.len || l < read1_len || l < read2_len);
sr1.qualLine.replace(0, qual1.length(), qual1);
sr2.qualLine.replace(0, qual2.length(), qual2);
if(r.nextBoolean()){ //sample from forward strand
sr1.seqLine.replace(seq.substring(p, p+read1_len));
sr2.seqLine.replace(seq.substring(p+l-read2_len,p+l));
//strand settings
sr1.mate_reverse_strand = true;
sr1.query_reverse_strand = false;
sr1.pos = p+1; //1 based
sr1.mpos = p+l-read2_len+1;
sr1.isize = l;
sr2.isize = -l;
}else{//sample from reverse strand
sr1.seqLine.replace(seq.substring(p+l-read1_len,p+l));
sr2.seqLine.replace(seq.substring(p,p+read2_len));
//strand settings
sr1.mate_reverse_strand = false;
sr1.query_reverse_strand = true;
sr1.pos = p+l-read1_len+1; //1 based
sr1.mpos = p+1;
sr1.isize = -l;
sr2.isize = l;
}
//things that can be inferred in 2 from 1
sr2.mate_reverse_strand = sr1.query_reverse_strand;
sr2.query_reverse_strand = sr1.mate_reverse_strand;
sr2.pos = sr1.mpos;
sr2.mpos = sr1.pos;
}
public void MPSample(SamRecord sr1,
SamRecord sr2, String qual1, String qual2,
int mate_ins, int mate_stdev, int read_ins, int read_stdev,
int read1_len, int read2_len, double p_bad_pulldown, Random r){
int i,b,l,p;
if(mate_ins > this.len){
throw new RuntimeException("Fasta file has shorter sequence than the requested mean library length");
}
//increment the seq index
sr1.seqIndex++;
sr2.seqIndex++;
boolean shortMate = false;
//grab our mate insert, our sheared mate loop, and position
do{
p = r.nextInt(this.len);
l = ((int)(r.nextGaussian()*((double)mate_stdev))) + mate_ins;
i = ((int)(r.nextGaussian()*((double)read_stdev))) + read_ins;
b = r.nextInt(i); //the location of biotin
if(b==0 || b == i-1 || p_bad_pulldown > r.nextDouble()){
shortMate = true;
if(i >= read1_len && i >= read2_len && p+i<=this.len && i <= l) break;
}else{
shortMate = false;
}
}while( i < read1_len ||
i < read2_len ||
(p+l)>this.len ||
l < read1_len ||
l < read2_len ||
i > l
);
//initialize sr1 and sr2
sr1.qualLine.replace(0, qual1.length(), qual1);
sr2.qualLine.replace(0, qual2.length(), qual2);
sr1.chimeric = sr2.chimeric = false;
sr1.mate_unmapped = sr2.mate_unmapped = false;
sr1.query_unmapped = sr2.query_unmapped = false;
sr1.proper_pair = sr2.proper_pair = true;
boolean rev = r.nextBoolean();
- if(rev){ //set up flags for mp library
- sr2.query_reverse_strand =
- sr1.query_reverse_strand =
- sr1.mate_reverse_strand =
- sr2.query_reverse_strand =
- sr2.mate_reverse_strand = true;
- }else{
- sr2.query_reverse_strand =
- sr1.query_reverse_strand =
- sr1.mate_reverse_strand =
- sr2.query_reverse_strand =
- sr2.mate_reverse_strand = false;
+ if(rev){ //set up flags for reverse mp library
+ // <=====2 1======>
+ sr2.query_reverse_strand = sr1.mate_reverse_strand = true;
+ sr1.query_reverse_strand = sr2.mate_reverse_strand = false;
+ }else{ // <=====1 2======>
+ sr2.query_reverse_strand = sr1.mate_reverse_strand = false;
+ sr1.query_reverse_strand = sr2.mate_reverse_strand = true;
}
if(shortMate){
//make surs CIGAR string is for all match (this could still be an SNP)
sr1.cigar = Integer.toString(read1_len)+"M";
sr2.cigar = Integer.toString(read2_len)+"M";
if(rev){//reverse strand sample
sr2.seqLine.replace(seq.substring(p, p+read2_len));
sr1.seqLine.replace(seq.substring(p+i-read1_len,p+i));
sr1.pos=p+i-read1_len+1; //1 based positions
sr1.mpos=p+ 1;
sr1.isize = -i;
}else{
sr1.seqLine.replace(seq.substring(p, p+read1_len));
sr2.seqLine.replace(seq.substring(p+i-read2_len,p+i));
sr1.mpos=p+i-read2_len+1; //1 based positions
sr1.pos=p+1;
sr1.isize = i;
}
//infer sr2 things from sr1
sr2.isize = -1*sr1.isize;
sr2.pos=sr1.mpos;
sr2.mpos=sr1.pos;
}else{
//two pieces, one of them starts at position
//p+l-b and goes to either p+l-b+read length
// if read length >= b, or goes to b and then
// takes read length - b starting from p.
// The other piece ends at p+i-b and starts at
// the lesser of (i-b) or read length before that
// if it (i-b) is less than read length, it takes
// the difference up until p+l. Those two cases where
// b happens within the read length lead to chimeric
// reads.
int rstart;
if(rev){ //sample from reverse
//both sequences are reversed, sr2 is taken from the p position
// and sr1 from the p+l position.
rstart = Math.abs(Math.min(0,i-b-read2_len));
sr2.seqLine.replace(rstart,read2_len,seq.substring(p+i-b-read2_len+rstart,p+i-b));
if(rstart != 0){
sr2.pos = p+l-rstart + 1;
sr2.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr2.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read2_len-rstart)+"S";
sr2.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read2_len-rstart)+"M";
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr2.pos = p+i-b-read2_len+rstart + 1; //1 based
sr2.cigar = Integer.toString(read2_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read1_len));
sr1.seqLine.replace(0,read1_len-rstart,seq.substring(p+l-b,p+l-b+read1_len-rstart));
sr1.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr1.cigar = Integer.toString(read1_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr1.c_cigar = Integer.toString(read1_len-rstart)+
"M-" +Integer.toString(l-b+read1_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr1.seqLine.replace(read1_len-rstart, read1_len, seq.substring(p,p+rstart));
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr1.cigar = Integer.toString(read1_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr2.isize=l-read1_len;
// sr1.isize = - sr2.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}else{//sample from forward
rstart = Math.abs(Math.min(0,i-b-read1_len));
sr1.seqLine.replace(rstart,read1_len,seq.substring(p+i-b-read1_len+rstart,p+i-b));
if(rstart != 0){
sr1.pos = p+l-rstart + 1;
sr1.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr1.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read1_len-rstart)+"S";
sr1.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read1_len-rstart)+"M";
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr1.pos = p+i-b-read1_len+rstart + 1; //1 based
sr1.cigar = Integer.toString(read1_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read2_len));
sr2.seqLine.replace(0,read2_len-rstart,seq.substring(p+l-b,p+l-b+read2_len-rstart));
sr2.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr2.cigar = Integer.toString(read2_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr2.c_cigar = Integer.toString(read2_len-rstart)+
"M-" +Integer.toString(l-b+read2_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr2.seqLine.replace(read2_len-rstart, read2_len, seq.substring(p,p+rstart));
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr2.cigar = Integer.toString(read2_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr1.isize=l-read2_len;
// sr2.isize = - sr1.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}
}
}
}
| true | true | public void MPSample(SamRecord sr1,
SamRecord sr2, String qual1, String qual2,
int mate_ins, int mate_stdev, int read_ins, int read_stdev,
int read1_len, int read2_len, double p_bad_pulldown, Random r){
int i,b,l,p;
if(mate_ins > this.len){
throw new RuntimeException("Fasta file has shorter sequence than the requested mean library length");
}
//increment the seq index
sr1.seqIndex++;
sr2.seqIndex++;
boolean shortMate = false;
//grab our mate insert, our sheared mate loop, and position
do{
p = r.nextInt(this.len);
l = ((int)(r.nextGaussian()*((double)mate_stdev))) + mate_ins;
i = ((int)(r.nextGaussian()*((double)read_stdev))) + read_ins;
b = r.nextInt(i); //the location of biotin
if(b==0 || b == i-1 || p_bad_pulldown > r.nextDouble()){
shortMate = true;
if(i >= read1_len && i >= read2_len && p+i<=this.len && i <= l) break;
}else{
shortMate = false;
}
}while( i < read1_len ||
i < read2_len ||
(p+l)>this.len ||
l < read1_len ||
l < read2_len ||
i > l
);
//initialize sr1 and sr2
sr1.qualLine.replace(0, qual1.length(), qual1);
sr2.qualLine.replace(0, qual2.length(), qual2);
sr1.chimeric = sr2.chimeric = false;
sr1.mate_unmapped = sr2.mate_unmapped = false;
sr1.query_unmapped = sr2.query_unmapped = false;
sr1.proper_pair = sr2.proper_pair = true;
boolean rev = r.nextBoolean();
if(rev){ //set up flags for mp library
sr2.query_reverse_strand =
sr1.query_reverse_strand =
sr1.mate_reverse_strand =
sr2.query_reverse_strand =
sr2.mate_reverse_strand = true;
}else{
sr2.query_reverse_strand =
sr1.query_reverse_strand =
sr1.mate_reverse_strand =
sr2.query_reverse_strand =
sr2.mate_reverse_strand = false;
}
if(shortMate){
//make surs CIGAR string is for all match (this could still be an SNP)
sr1.cigar = Integer.toString(read1_len)+"M";
sr2.cigar = Integer.toString(read2_len)+"M";
if(rev){//reverse strand sample
sr2.seqLine.replace(seq.substring(p, p+read2_len));
sr1.seqLine.replace(seq.substring(p+i-read1_len,p+i));
sr1.pos=p+i-read1_len+1; //1 based positions
sr1.mpos=p+ 1;
sr1.isize = -i;
}else{
sr1.seqLine.replace(seq.substring(p, p+read1_len));
sr2.seqLine.replace(seq.substring(p+i-read2_len,p+i));
sr1.mpos=p+i-read2_len+1; //1 based positions
sr1.pos=p+1;
sr1.isize = i;
}
//infer sr2 things from sr1
sr2.isize = -1*sr1.isize;
sr2.pos=sr1.mpos;
sr2.mpos=sr1.pos;
}else{
//two pieces, one of them starts at position
//p+l-b and goes to either p+l-b+read length
// if read length >= b, or goes to b and then
// takes read length - b starting from p.
// The other piece ends at p+i-b and starts at
// the lesser of (i-b) or read length before that
// if it (i-b) is less than read length, it takes
// the difference up until p+l. Those two cases where
// b happens within the read length lead to chimeric
// reads.
int rstart;
if(rev){ //sample from reverse
//both sequences are reversed, sr2 is taken from the p position
// and sr1 from the p+l position.
rstart = Math.abs(Math.min(0,i-b-read2_len));
sr2.seqLine.replace(rstart,read2_len,seq.substring(p+i-b-read2_len+rstart,p+i-b));
if(rstart != 0){
sr2.pos = p+l-rstart + 1;
sr2.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr2.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read2_len-rstart)+"S";
sr2.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read2_len-rstart)+"M";
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr2.pos = p+i-b-read2_len+rstart + 1; //1 based
sr2.cigar = Integer.toString(read2_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read1_len));
sr1.seqLine.replace(0,read1_len-rstart,seq.substring(p+l-b,p+l-b+read1_len-rstart));
sr1.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr1.cigar = Integer.toString(read1_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr1.c_cigar = Integer.toString(read1_len-rstart)+
"M-" +Integer.toString(l-b+read1_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr1.seqLine.replace(read1_len-rstart, read1_len, seq.substring(p,p+rstart));
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr1.cigar = Integer.toString(read1_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr2.isize=l-read1_len;
// sr1.isize = - sr2.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}else{//sample from forward
rstart = Math.abs(Math.min(0,i-b-read1_len));
sr1.seqLine.replace(rstart,read1_len,seq.substring(p+i-b-read1_len+rstart,p+i-b));
if(rstart != 0){
sr1.pos = p+l-rstart + 1;
sr1.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr1.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read1_len-rstart)+"S";
sr1.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read1_len-rstart)+"M";
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr1.pos = p+i-b-read1_len+rstart + 1; //1 based
sr1.cigar = Integer.toString(read1_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read2_len));
sr2.seqLine.replace(0,read2_len-rstart,seq.substring(p+l-b,p+l-b+read2_len-rstart));
sr2.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr2.cigar = Integer.toString(read2_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr2.c_cigar = Integer.toString(read2_len-rstart)+
"M-" +Integer.toString(l-b+read2_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr2.seqLine.replace(read2_len-rstart, read2_len, seq.substring(p,p+rstart));
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr2.cigar = Integer.toString(read2_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr1.isize=l-read2_len;
// sr2.isize = - sr1.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}
}
}
| public void MPSample(SamRecord sr1,
SamRecord sr2, String qual1, String qual2,
int mate_ins, int mate_stdev, int read_ins, int read_stdev,
int read1_len, int read2_len, double p_bad_pulldown, Random r){
int i,b,l,p;
if(mate_ins > this.len){
throw new RuntimeException("Fasta file has shorter sequence than the requested mean library length");
}
//increment the seq index
sr1.seqIndex++;
sr2.seqIndex++;
boolean shortMate = false;
//grab our mate insert, our sheared mate loop, and position
do{
p = r.nextInt(this.len);
l = ((int)(r.nextGaussian()*((double)mate_stdev))) + mate_ins;
i = ((int)(r.nextGaussian()*((double)read_stdev))) + read_ins;
b = r.nextInt(i); //the location of biotin
if(b==0 || b == i-1 || p_bad_pulldown > r.nextDouble()){
shortMate = true;
if(i >= read1_len && i >= read2_len && p+i<=this.len && i <= l) break;
}else{
shortMate = false;
}
}while( i < read1_len ||
i < read2_len ||
(p+l)>this.len ||
l < read1_len ||
l < read2_len ||
i > l
);
//initialize sr1 and sr2
sr1.qualLine.replace(0, qual1.length(), qual1);
sr2.qualLine.replace(0, qual2.length(), qual2);
sr1.chimeric = sr2.chimeric = false;
sr1.mate_unmapped = sr2.mate_unmapped = false;
sr1.query_unmapped = sr2.query_unmapped = false;
sr1.proper_pair = sr2.proper_pair = true;
boolean rev = r.nextBoolean();
if(rev){ //set up flags for reverse mp library
// <=====2 1======>
sr2.query_reverse_strand = sr1.mate_reverse_strand = true;
sr1.query_reverse_strand = sr2.mate_reverse_strand = false;
}else{ // <=====1 2======>
sr2.query_reverse_strand = sr1.mate_reverse_strand = false;
sr1.query_reverse_strand = sr2.mate_reverse_strand = true;
}
if(shortMate){
//make surs CIGAR string is for all match (this could still be an SNP)
sr1.cigar = Integer.toString(read1_len)+"M";
sr2.cigar = Integer.toString(read2_len)+"M";
if(rev){//reverse strand sample
sr2.seqLine.replace(seq.substring(p, p+read2_len));
sr1.seqLine.replace(seq.substring(p+i-read1_len,p+i));
sr1.pos=p+i-read1_len+1; //1 based positions
sr1.mpos=p+ 1;
sr1.isize = -i;
}else{
sr1.seqLine.replace(seq.substring(p, p+read1_len));
sr2.seqLine.replace(seq.substring(p+i-read2_len,p+i));
sr1.mpos=p+i-read2_len+1; //1 based positions
sr1.pos=p+1;
sr1.isize = i;
}
//infer sr2 things from sr1
sr2.isize = -1*sr1.isize;
sr2.pos=sr1.mpos;
sr2.mpos=sr1.pos;
}else{
//two pieces, one of them starts at position
//p+l-b and goes to either p+l-b+read length
// if read length >= b, or goes to b and then
// takes read length - b starting from p.
// The other piece ends at p+i-b and starts at
// the lesser of (i-b) or read length before that
// if it (i-b) is less than read length, it takes
// the difference up until p+l. Those two cases where
// b happens within the read length lead to chimeric
// reads.
int rstart;
if(rev){ //sample from reverse
//both sequences are reversed, sr2 is taken from the p position
// and sr1 from the p+l position.
rstart = Math.abs(Math.min(0,i-b-read2_len));
sr2.seqLine.replace(rstart,read2_len,seq.substring(p+i-b-read2_len+rstart,p+i-b));
if(rstart != 0){
sr2.pos = p+l-rstart + 1;
sr2.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr2.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read2_len-rstart)+"S";
sr2.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read2_len-rstart)+"M";
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr2.pos = p+i-b-read2_len+rstart + 1; //1 based
sr2.cigar = Integer.toString(read2_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read1_len));
sr1.seqLine.replace(0,read1_len-rstart,seq.substring(p+l-b,p+l-b+read1_len-rstart));
sr1.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr1.cigar = Integer.toString(read1_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr1.c_cigar = Integer.toString(read1_len-rstart)+
"M-" +Integer.toString(l-b+read1_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr1.seqLine.replace(read1_len-rstart, read1_len, seq.substring(p,p+rstart));
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr2.proper_pair=sr1.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr1.cigar = Integer.toString(read1_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr2.isize=l-read1_len;
// sr1.isize = - sr2.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}else{//sample from forward
rstart = Math.abs(Math.min(0,i-b-read1_len));
sr1.seqLine.replace(rstart,read1_len,seq.substring(p+i-b-read1_len+rstart,p+i-b));
if(rstart != 0){
sr1.pos = p+l-rstart + 1;
sr1.seqLine.replace(0,rstart,seq.substring(p+l-rstart,p+l));
sr1.cigar = Integer.toString(rstart)+
"M"+Integer.toString(read1_len-rstart)+"S";
sr1.c_cigar =Integer.toString(rstart)+
"M-"+Integer.toString(l-rstart-(i-b))+
"N"+Integer.toString(read1_len-rstart)+"M";
sr1.chimeric = true;
// sr1.query_unmapped = true;
// sr2.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr1.isize=sr2.isize=0;
}else{ //not a chimeric read, so cigar is all match
sr1.pos = p+i-b-read1_len+rstart + 1; //1 based
sr1.cigar = Integer.toString(read1_len)+"M";
}
rstart = Math.abs(Math.min(0,b-read2_len));
sr2.seqLine.replace(0,read2_len-rstart,seq.substring(p+l-b,p+l-b+read2_len-rstart));
sr2.pos = p+l-b + 1; //1 based
if(rstart != 0){
sr2.cigar = Integer.toString(read2_len-rstart)+
"M"+Integer.toString(rstart)+
"S";
sr2.c_cigar = Integer.toString(read2_len-rstart)+
"M-" +Integer.toString(l-b+read2_len-rstart)+
"N"+Integer.toString(rstart)+"M";
sr2.seqLine.replace(read2_len-rstart, read2_len, seq.substring(p,p+rstart));
sr2.chimeric = true;
// sr2.query_unmapped = true;
// sr1.mate_unmapped = true;
// sr1.proper_pair=sr2.proper_pair=false;
// sr2.isize=sr1.isize=0;
}else{ //not a chimeric read so CIGAR is all match
sr2.cigar = Integer.toString(read2_len)+"M";
}
// if(!sr1.chimeric && !sr2.chimeric){
// sr1.isize=l-read2_len;
// sr2.isize = - sr1.isize;
// }
sr1.mpos = sr2.pos;
sr2.mpos = sr1.pos;
sr1.isize = sr1.pos - sr2.pos;
sr2.isize = sr2.pos - sr1.pos;
}
}
}
|
diff --git a/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java b/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java
index 95505009..1b68db46 100644
--- a/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java
+++ b/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java
@@ -1,377 +1,379 @@
package org.bukkit.plugin;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
* Provides access to a Plugins description file, plugin.yaml
*/
public final class PluginDescriptionFile {
private static final Yaml yaml = new Yaml(new SafeConstructor());
private String name = null;
private String main = null;
private String classLoaderOf = null;
private List<String> depend = null;
private List<String> softDepend = null;
private String version = null;
private Map<String, Map<String, Object>> commands = null;
private String description = null;
private List<String> authors = null;
private String website = null;
private String prefix = null;
private boolean database = false;
private PluginLoadOrder order = PluginLoadOrder.POSTWORLD;
private List<Permission> permissions = null;
private PermissionDefault defaultPerm = PermissionDefault.OP;
public PluginDescriptionFile(final InputStream stream) throws InvalidDescriptionException {
loadMap((Map<?, ?>) yaml.load(stream));
}
/**
* Loads a PluginDescriptionFile from the specified reader
*
* @param reader The reader
* @throws InvalidDescriptionException If the PluginDescriptionFile is invalid
*/
public PluginDescriptionFile(final Reader reader) throws InvalidDescriptionException {
loadMap((Map<?, ?>) yaml.load(reader));
}
/**
* Creates a new PluginDescriptionFile with the given detailed
*
* @param pluginName Name of this plugin
* @param pluginVersion Version of this plugin
* @param mainClass Full location of the main class of this plugin
*/
public PluginDescriptionFile(final String pluginName, final String pluginVersion, final String mainClass) {
name = pluginName;
version = pluginVersion;
main = mainClass;
}
/**
* Saves this PluginDescriptionFile to the given writer
*
* @param writer Writer to output this file to
*/
public void save(Writer writer) {
yaml.dump(saveMap(), writer);
}
/**
* Returns the name of a plugin
*
* @return String name
*/
public String getName() {
return name;
}
/**
* Returns the version of a plugin
*
* @return String name
*/
public String getVersion() {
return version;
}
/**
* Returns the name of a plugin including the version
*
* @return String name
*/
public String getFullName() {
return name + " v" + version;
}
/**
* Returns the main class for a plugin
*
* @return Java classpath
*/
public String getMain() {
return main;
}
public Map<String, Map<String, Object>> getCommands() {
return commands;
}
public List<String> getDepend() {
return depend;
}
public List<String> getSoftDepend() {
return softDepend;
}
public PluginLoadOrder getLoad() {
return order;
}
/**
* Gets the description of this plugin
*
* @return Description of this plugin
*/
public String getDescription() {
return description;
}
public List<String> getAuthors() {
return authors;
}
public String getWebsite() {
return website;
}
public boolean isDatabaseEnabled() {
return database;
}
public void setDatabaseEnabled(boolean database) {
this.database = database;
}
public List<Permission> getPermissions() {
return permissions;
}
public PermissionDefault getPermissionDefault() {
return defaultPerm;
}
public String getClassLoaderOf() {
return classLoaderOf;
}
public String getPrefix() {
return prefix;
}
private void loadMap(Map<?, ?> map) throws InvalidDescriptionException {
try {
name = map.get("name").toString();
if (!name.matches("^[A-Za-z0-9 _.-]+$")) {
throw new InvalidDescriptionException("name '" + name + "' contains invalid characters.");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "name is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "name is of wrong type");
}
try {
version = map.get("version").toString();
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "version is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "version is of wrong type");
}
try {
main = map.get("main").toString();
if (main.startsWith("org.bukkit.")) {
throw new InvalidDescriptionException("main may not be within the org.bukkit namespace");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "main is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "main is of wrong type");
}
if (map.get("commands") != null) {
ImmutableMap.Builder<String, Map<String, Object>> commandsBuilder = ImmutableMap.<String, Map<String, Object>>builder();
try {
for (Map.Entry<?, ?> command : ((Map<?, ?>) map.get("commands")).entrySet()) {
ImmutableMap.Builder<String, Object> commandBuilder = ImmutableMap.<String, Object>builder();
- for (Map.Entry<?, ?> commandEntry : ((Map<?, ?>) command.getValue()).entrySet()) {
- if (commandEntry.getValue() instanceof Iterable) {
- // This prevents internal alias list changes
- ImmutableList.Builder<Object> commandSubList = ImmutableList.<Object>builder();
- for (Object commandSubListItem : (Iterable<?>) commandEntry.getValue()) {
- commandSubList.add(commandSubListItem);
+ if (command.getValue() != null) {
+ for (Map.Entry<?, ?> commandEntry : ((Map<?, ?>) command.getValue()).entrySet()) {
+ if (commandEntry.getValue() instanceof Iterable) {
+ // This prevents internal alias list changes
+ ImmutableList.Builder<Object> commandSubList = ImmutableList.<Object>builder();
+ for (Object commandSubListItem : (Iterable<?>) commandEntry.getValue()) {
+ if (commandSubListItem != null) {
+ commandSubList.add(commandSubListItem);
+ }
+ }
+ commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build());
+ } else if (commandEntry.getValue() != null) {
+ commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue());
}
- commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build());
- } else if (commandEntry.getValue() != null) {
- commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue());
}
}
commandsBuilder.put(command.getKey().toString(), commandBuilder.build());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "commands are of wrong type");
- } catch (NullPointerException ex) {
- throw new InvalidDescriptionException(ex, "commands are not properly defined");
}
commands = commandsBuilder.build();
}
if (map.get("class-loader-of") != null) {
classLoaderOf = map.get("class-loader-of").toString();
}
if (map.get("depend") != null) {
ImmutableList.Builder<String> dependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("depend")) {
dependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "depend is of wrong type");
} catch (NullPointerException e) {
throw new InvalidDescriptionException(e, "invalid dependency format");
}
depend = dependBuilder.build();
}
if (map.get("softdepend") != null) {
ImmutableList.Builder<String> softDependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("softdepend")) {
softDependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "softdepend is of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "invalid soft-dependency format");
}
softDepend = softDependBuilder.build();
}
if (map.get("database") != null) {
try {
database = (Boolean) map.get("database");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "database is of wrong type");
}
}
if (map.get("website") != null) {
website = map.get("website").toString();
}
if (map.get("description") != null) {
description = map.get("description").toString();
}
if (map.get("load") != null) {
try {
order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", ""));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "load is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "load is not a valid choice");
}
}
if (map.get("authors") != null) {
ImmutableList.Builder<String> authorsBuilder = ImmutableList.<String>builder();
if (map.get("author") != null) {
authorsBuilder.add(map.get("author").toString());
}
try {
for (Object o : (Iterable<?>) map.get("authors")) {
authorsBuilder.add(o.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "authors are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "authors are improperly defined");
}
authors = authorsBuilder.build();
} else if (map.get("author") != null) {
authors = ImmutableList.of(map.get("author").toString());
} else {
authors = ImmutableList.<String>of();
}
if (map.get("default-permission") != null) {
try {
defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString());
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "default-permission is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "default-permission is not a valid choice");
}
}
if (map.get("permissions") != null) {
try {
Map<?, ?> perms = (Map<?, ?>) map.get("permissions");
permissions = ImmutableList.copyOf(Permission.loadPermissions(perms, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "permissions are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "permissions are not properly defined");
}
} else {
permissions = ImmutableList.<Permission>of();
}
if (map.get("prefix") != null) {
prefix = map.get("prefix").toString();
}
}
private Map<String, Object> saveMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("main", main);
map.put("version", version);
map.put("database", database);
map.put("order", order.toString());
map.put("default-permission", defaultPerm.toString());
if (commands != null) {
map.put("command", commands);
}
if (depend != null) {
map.put("depend", depend);
}
if (softDepend != null) {
map.put("softdepend", softDepend);
}
if (website != null) {
map.put("website", website);
}
if (description != null) {
map.put("description", description);
}
if (authors.size() == 1) {
map.put("author", authors.get(0));
} else if (authors.size() > 1) {
map.put("authors", authors);
}
if (classLoaderOf != null) {
map.put("class-loader-of", classLoaderOf);
}
if (prefix != null) {
map.put("prefix", prefix);
}
return map;
}
}
| false | true | private void loadMap(Map<?, ?> map) throws InvalidDescriptionException {
try {
name = map.get("name").toString();
if (!name.matches("^[A-Za-z0-9 _.-]+$")) {
throw new InvalidDescriptionException("name '" + name + "' contains invalid characters.");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "name is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "name is of wrong type");
}
try {
version = map.get("version").toString();
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "version is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "version is of wrong type");
}
try {
main = map.get("main").toString();
if (main.startsWith("org.bukkit.")) {
throw new InvalidDescriptionException("main may not be within the org.bukkit namespace");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "main is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "main is of wrong type");
}
if (map.get("commands") != null) {
ImmutableMap.Builder<String, Map<String, Object>> commandsBuilder = ImmutableMap.<String, Map<String, Object>>builder();
try {
for (Map.Entry<?, ?> command : ((Map<?, ?>) map.get("commands")).entrySet()) {
ImmutableMap.Builder<String, Object> commandBuilder = ImmutableMap.<String, Object>builder();
for (Map.Entry<?, ?> commandEntry : ((Map<?, ?>) command.getValue()).entrySet()) {
if (commandEntry.getValue() instanceof Iterable) {
// This prevents internal alias list changes
ImmutableList.Builder<Object> commandSubList = ImmutableList.<Object>builder();
for (Object commandSubListItem : (Iterable<?>) commandEntry.getValue()) {
commandSubList.add(commandSubListItem);
}
commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build());
} else if (commandEntry.getValue() != null) {
commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue());
}
}
commandsBuilder.put(command.getKey().toString(), commandBuilder.build());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "commands are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "commands are not properly defined");
}
commands = commandsBuilder.build();
}
if (map.get("class-loader-of") != null) {
classLoaderOf = map.get("class-loader-of").toString();
}
if (map.get("depend") != null) {
ImmutableList.Builder<String> dependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("depend")) {
dependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "depend is of wrong type");
} catch (NullPointerException e) {
throw new InvalidDescriptionException(e, "invalid dependency format");
}
depend = dependBuilder.build();
}
if (map.get("softdepend") != null) {
ImmutableList.Builder<String> softDependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("softdepend")) {
softDependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "softdepend is of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "invalid soft-dependency format");
}
softDepend = softDependBuilder.build();
}
if (map.get("database") != null) {
try {
database = (Boolean) map.get("database");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "database is of wrong type");
}
}
if (map.get("website") != null) {
website = map.get("website").toString();
}
if (map.get("description") != null) {
description = map.get("description").toString();
}
if (map.get("load") != null) {
try {
order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", ""));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "load is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "load is not a valid choice");
}
}
if (map.get("authors") != null) {
ImmutableList.Builder<String> authorsBuilder = ImmutableList.<String>builder();
if (map.get("author") != null) {
authorsBuilder.add(map.get("author").toString());
}
try {
for (Object o : (Iterable<?>) map.get("authors")) {
authorsBuilder.add(o.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "authors are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "authors are improperly defined");
}
authors = authorsBuilder.build();
} else if (map.get("author") != null) {
authors = ImmutableList.of(map.get("author").toString());
} else {
authors = ImmutableList.<String>of();
}
if (map.get("default-permission") != null) {
try {
defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString());
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "default-permission is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "default-permission is not a valid choice");
}
}
if (map.get("permissions") != null) {
try {
Map<?, ?> perms = (Map<?, ?>) map.get("permissions");
permissions = ImmutableList.copyOf(Permission.loadPermissions(perms, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "permissions are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "permissions are not properly defined");
}
} else {
permissions = ImmutableList.<Permission>of();
}
if (map.get("prefix") != null) {
prefix = map.get("prefix").toString();
}
}
| private void loadMap(Map<?, ?> map) throws InvalidDescriptionException {
try {
name = map.get("name").toString();
if (!name.matches("^[A-Za-z0-9 _.-]+$")) {
throw new InvalidDescriptionException("name '" + name + "' contains invalid characters.");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "name is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "name is of wrong type");
}
try {
version = map.get("version").toString();
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "version is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "version is of wrong type");
}
try {
main = map.get("main").toString();
if (main.startsWith("org.bukkit.")) {
throw new InvalidDescriptionException("main may not be within the org.bukkit namespace");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "main is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "main is of wrong type");
}
if (map.get("commands") != null) {
ImmutableMap.Builder<String, Map<String, Object>> commandsBuilder = ImmutableMap.<String, Map<String, Object>>builder();
try {
for (Map.Entry<?, ?> command : ((Map<?, ?>) map.get("commands")).entrySet()) {
ImmutableMap.Builder<String, Object> commandBuilder = ImmutableMap.<String, Object>builder();
if (command.getValue() != null) {
for (Map.Entry<?, ?> commandEntry : ((Map<?, ?>) command.getValue()).entrySet()) {
if (commandEntry.getValue() instanceof Iterable) {
// This prevents internal alias list changes
ImmutableList.Builder<Object> commandSubList = ImmutableList.<Object>builder();
for (Object commandSubListItem : (Iterable<?>) commandEntry.getValue()) {
if (commandSubListItem != null) {
commandSubList.add(commandSubListItem);
}
}
commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build());
} else if (commandEntry.getValue() != null) {
commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue());
}
}
}
commandsBuilder.put(command.getKey().toString(), commandBuilder.build());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "commands are of wrong type");
}
commands = commandsBuilder.build();
}
if (map.get("class-loader-of") != null) {
classLoaderOf = map.get("class-loader-of").toString();
}
if (map.get("depend") != null) {
ImmutableList.Builder<String> dependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("depend")) {
dependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "depend is of wrong type");
} catch (NullPointerException e) {
throw new InvalidDescriptionException(e, "invalid dependency format");
}
depend = dependBuilder.build();
}
if (map.get("softdepend") != null) {
ImmutableList.Builder<String> softDependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("softdepend")) {
softDependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "softdepend is of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "invalid soft-dependency format");
}
softDepend = softDependBuilder.build();
}
if (map.get("database") != null) {
try {
database = (Boolean) map.get("database");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "database is of wrong type");
}
}
if (map.get("website") != null) {
website = map.get("website").toString();
}
if (map.get("description") != null) {
description = map.get("description").toString();
}
if (map.get("load") != null) {
try {
order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", ""));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "load is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "load is not a valid choice");
}
}
if (map.get("authors") != null) {
ImmutableList.Builder<String> authorsBuilder = ImmutableList.<String>builder();
if (map.get("author") != null) {
authorsBuilder.add(map.get("author").toString());
}
try {
for (Object o : (Iterable<?>) map.get("authors")) {
authorsBuilder.add(o.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "authors are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "authors are improperly defined");
}
authors = authorsBuilder.build();
} else if (map.get("author") != null) {
authors = ImmutableList.of(map.get("author").toString());
} else {
authors = ImmutableList.<String>of();
}
if (map.get("default-permission") != null) {
try {
defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString());
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "default-permission is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "default-permission is not a valid choice");
}
}
if (map.get("permissions") != null) {
try {
Map<?, ?> perms = (Map<?, ?>) map.get("permissions");
permissions = ImmutableList.copyOf(Permission.loadPermissions(perms, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "permissions are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "permissions are not properly defined");
}
} else {
permissions = ImmutableList.<Permission>of();
}
if (map.get("prefix") != null) {
prefix = map.get("prefix").toString();
}
}
|
diff --git a/src/org/meta_environment/uptr/SymbolAdapter.java b/src/org/meta_environment/uptr/SymbolAdapter.java
index ded30af199..6ac683704d 100644
--- a/src/org/meta_environment/uptr/SymbolAdapter.java
+++ b/src/org/meta_environment/uptr/SymbolAdapter.java
@@ -1,120 +1,121 @@
package org.meta_environment.uptr;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IString;
import org.meta_environment.rascal.interpreter.asserts.ImplementationError;
public class SymbolAdapter {
private SymbolAdapter() {
super();
}
public static boolean isCf(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Cf;
}
public static boolean isLex(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Lex;
}
public static boolean isSort(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Sort;
}
public static IConstructor getSymbol(IConstructor tree) {
if (isCf(tree) || isLex(tree) || isOpt(tree) || isIterPlus(tree) || isIterPlusSep(tree) || isIterStar(tree) || isIterStarSep(tree)) {
return ((IConstructor) tree.get("symbol"));
}
throw new ImplementationError("Symbol does not have a child named symbol: " + tree);
}
public static IConstructor getSeparator(IConstructor tree) {
if (isIterPlusSep(tree) || isIterStarSep(tree)) {
return (IConstructor) tree.get("separator");
}
throw new ImplementationError("Symbol does not have a child named separator: " + tree);
}
public static String getName(IConstructor tree) {
if (isSort(tree)) {
return ((IString) tree.get("string")).getValue();
}
else if (isParameterizedSort(tree)) {
return ((IString) tree.get("sort")).getValue();
}
else {
throw new ImplementationError("Symbol does not have a child named \"name\": " + tree);
}
}
public static boolean isParameterizedSort(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_ParameterizedSort;
}
public static boolean isLiteral(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Lit;
}
public static boolean isCILiteral(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_CiLit;
}
public static boolean isIterPlusSep(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_IterPlusSep;
}
public static boolean isIterStar(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_IterStar;
}
public static boolean isIterPlus(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_IterPlus;
}
public static boolean isLayout(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Layout;
}
public static boolean isStarList(IConstructor tree) {
if (isCf(tree) || SymbolAdapter.isLex(tree)) {
tree = SymbolAdapter.getSymbol(tree);
}
return isIterStar(tree) || isIterStarSep(tree);
}
public static boolean isPlusList(IConstructor tree) {
if (isCf(tree) || SymbolAdapter.isLex(tree)) {
tree = getSymbol(tree);
}
return isIterPlus(tree) || isIterPlusSep(tree);
}
public static boolean isAnyList(IConstructor tree) {
return isStarList(tree) || isPlusList(tree);
}
public static boolean isCfOptLayout(IConstructor tree) {
if (isCf(tree)) {
+ tree = getSymbol(tree);
if (isOpt(tree)) {
tree = getSymbol(tree);
if (isLayout(tree)) {
return true;
}
}
}
return false;
}
private static boolean isOpt(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_Opt;
}
public static boolean isIterStarSep(IConstructor tree) {
return tree.getConstructorType() == Factory.Symbol_IterStarSep;
}
}
| true | true | public static boolean isCfOptLayout(IConstructor tree) {
if (isCf(tree)) {
if (isOpt(tree)) {
tree = getSymbol(tree);
if (isLayout(tree)) {
return true;
}
}
}
return false;
}
| public static boolean isCfOptLayout(IConstructor tree) {
if (isCf(tree)) {
tree = getSymbol(tree);
if (isOpt(tree)) {
tree = getSymbol(tree);
if (isLayout(tree)) {
return true;
}
}
}
return false;
}
|
diff --git a/src/savant/controller/PluginController.java b/src/savant/controller/PluginController.java
index be17a4d0..c31e2690 100644
--- a/src/savant/controller/PluginController.java
+++ b/src/savant/controller/PluginController.java
@@ -1,411 +1,414 @@
/*
* Copyright 2010-2011 University of Toronto
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package savant.controller;
import java.awt.BorderLayout;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JPanel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import savant.api.util.DialogUtils;
import savant.controller.event.PluginEvent;
import savant.experimental.PluginTool;
import savant.plugin.PluginDescriptor;
import savant.plugin.PluginIndex;
import savant.plugin.PluginVersionException;
import savant.plugin.SavantDataSourcePlugin;
import savant.plugin.SavantPanelPlugin;
import savant.plugin.SavantPlugin;
import savant.settings.BrowserSettings;
import savant.settings.DirectorySettings;
import savant.util.Controller;
import savant.util.IOUtils;
import savant.util.MiscUtils;
import savant.util.NetworkUtils;
import savant.view.tools.ToolsModule;
/**
*
* @author mfiume, tarkvara
*/
public class PluginController extends Controller {
private static final Log LOG = LogFactory.getLog(PluginController.class);
private static final String UNINSTALL_FILENAME = ".uninstall_plugins";
private static PluginController instance;
private File uninstallFile;
private List<String> pluginsToRemove = new ArrayList<String>();
private Map<String, PluginDescriptor> knownPlugins = new HashMap<String, PluginDescriptor>();
private Map<String, SavantPlugin> loadedPlugins = new HashMap<String, SavantPlugin>();
private Map<String, String> pluginErrors = new LinkedHashMap<String, String>();
private PluginLoader pluginLoader;
private PluginIndex repositoryIndex = null;
/** SINGLETON **/
public static synchronized PluginController getInstance() {
if (instance == null) {
instance = new PluginController();
}
return instance;
}
/**
* Private constructor. Should only be called by getInstance().
*/
private PluginController() {
try {
uninstallFile = new File(DirectorySettings.getSavantDirectory(), UNINSTALL_FILENAME);
LOG.info("Uninstall list " + UNINSTALL_FILENAME);
if (uninstallFile.exists()) {
deleteFileList(uninstallFile);
}
copyBuiltInPlugins();
} catch (Exception ex) {
LOG.error("Error loading plugins.", ex);
}
}
/**
* Try to load all JAR files in the given directory.
*/
public void loadPlugins(File pluginsDir) {
File[] files = pluginsDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jar");
}
});
for (File f: files) {
try {
addPlugin(f);
} catch (PluginVersionException x) {
LOG.warn("No compatible plugins found in " + f);
}
}
// Check to see if we have any outdated plugins.
if (pluginErrors.size() > 0) {
List<String> updated = new ArrayList<String>();
for (String s: pluginErrors.keySet()) {
// Plugin is invalid, and we don't have a newer version.
if (checkForPluginUpdate(s)) {
updated.add(s);
}
}
if (updated.size() > 0) {
DialogUtils.displayMessage("Plugins Updated", String.format("<html>The following plugins were updated to be compatible with Savant %s:<br><br><i>%s</i></html>", BrowserSettings.VERSION, MiscUtils.join(updated, ", ")));
for (String s: updated) {
pluginErrors.remove(s);
}
}
if (pluginErrors.size() > 0) {
StringBuilder errorStr = null;
for (String s: pluginErrors.keySet()) {
if (errorStr == null) {
errorStr = new StringBuilder();
} else {
errorStr.append("\n");
}
errorStr.append(s);
errorStr.append(" – ");
errorStr.append(pluginErrors.get(s));
}
if (errorStr != null) {
+ // The following dialog will only report plugins which we can tell are faulty before calling loadPlugin(), typically
+ // by checking the version in plugin.xml.
DialogUtils.displayMessage("Plugins Not Loaded", String.format("<html>The following plugins could not be loaded:<br><br><i>%s</i><br><br>They will not be available to Savant.</html>", errorStr));
}
}
}
Set<URL> jarURLs = new HashSet<URL>();
for (PluginDescriptor desc: knownPlugins.values()) {
try {
if (!pluginErrors.containsKey(desc.getID())) {
jarURLs.add(desc.getFile().toURI().toURL());
}
} catch (MalformedURLException ignored) {
}
}
if (jarURLs.size() > 0) {
pluginLoader = new PluginLoader(jarURLs.toArray(new URL[0]), getClass().getClassLoader());
for (final PluginDescriptor desc: knownPlugins.values()) {
if (!pluginErrors.containsKey(desc.getID())) {
new Thread("PluginLoader-" + desc) {
@Override
public void run() {
try {
loadPlugin(desc);
} catch (Throwable x) {
LOG.error("Unable to load " + desc.getName(), x);
- pluginErrors.put(desc.getID(), "Error");
+ pluginErrors.put(desc.getID(), x.getClass().getName());
+ DialogUtils.displayMessage("Plugin Not Loaded", String.format("<html>The following plugin could not be loaded:<br><br><i>%s – %s</i><br><br>It will not be available to Savant.</html>", desc.getID(), x));
}
}
}.start();
}
}
}
}
public List<PluginDescriptor> getDescriptors() {
List<PluginDescriptor> result = new ArrayList<PluginDescriptor>();
result.addAll(knownPlugins.values());
Collections.sort(result);
return result;
}
public SavantPlugin getPlugin(String id) {
return loadedPlugins.get(id);
}
public void queuePluginForRemoval(String id) {
FileWriter fstream = null;
try {
PluginDescriptor info = knownPlugins.get(id);
LOG.info("Adding plugin " + info.getFile().getAbsolutePath() + " to uninstall list " + uninstallFile.getPath());
if (!uninstallFile.exists()) {
uninstallFile.createNewFile();
}
fstream = new FileWriter(uninstallFile, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(info.getFile().getAbsolutePath() + "\n");
out.close();
DialogUtils.displayMessage("Uninstallation Complete", "Please restart Savant for changes to take effect.");
pluginsToRemove.add(id);
fireEvent(new PluginEvent(PluginEvent.Type.QUEUED_FOR_REMOVAL, id, null));
} catch (IOException ex) {
LOG.error("Error uninstalling plugin: " + uninstallFile, ex);
} finally {
try {
fstream.close();
} catch (IOException ignored) {
}
}
}
public boolean isPluginQueuedForRemoval(String id) {
return pluginsToRemove.contains(id);
}
public String getPluginStatus(String id) {
if (pluginsToRemove.contains(id)) {
return "Queued for removal";
}
if (loadedPlugins.get(id) != null) {
return "Loaded";
}
String err = pluginErrors.get(id);
if (err != null) {
return err;
}
if (knownPlugins.get(id) != null) {
// Plugin is valid, but hasn't shown up in the loadedPlugins map.
return "Loading";
}
return "Unknown";
}
/**
* Give plugin tool an opportunity to initialise itself.
*
* @param plugin
*/
private void initPluginTool(PluginTool plugin) {
plugin.init();
ToolsModule.addTool(plugin);
}
/**
* Give a panel plugin an opportunity to initialise itself.
*
* @param plugin
*/
private JPanel initGUIPlugin(SavantPanelPlugin plugin) {
JPanel canvas = new JPanel();
canvas.setLayout(new BorderLayout());
plugin.init(canvas);
return canvas;
}
/**
* Give a DataSource plugin a chance to initalise itself.
* @param plugin
*/
private void initSavantDataSourcePlugin(SavantDataSourcePlugin plugin) {
DataSourcePluginController.getInstance().addDataSourcePlugin(plugin);
plugin.init();
}
private void deleteFileList(File fileListFile) {
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(fileListFile));
while ((line = br.readLine()) != null) {
LOG.info("Uninstalling " + line);
if (!new File(line).delete()) {
throw new IOException("Delete of " + line + " failed");
}
}
} catch (IOException ex) {
LOG.error("Problem uninstalling " + line, ex);
} finally {
try {
br.close();
} catch (IOException ex) {
}
}
fileListFile.delete();
}
private void copyBuiltInPlugins() {
File destDir = DirectorySettings.getPluginsDirectory();
File srcDir = null;
if (MiscUtils.MAC) {
srcDir = new File(com.apple.eio.FileManager.getPathToApplicationBundle() + "/Contents/Plugins");
if (srcDir.exists()) {
try {
IOUtils.copyDir(srcDir, destDir);
return;
} catch (Exception ignored) {
// We should expect to see this when running in the debugger.
}
}
}
try {
srcDir = new File("plugins");
IOUtils.copyDir(srcDir, destDir);
} catch (Exception x) {
LOG.error("Unable to copy builtin plugins from " + srcDir.getAbsolutePath() + " to " + destDir, x);
}
}
private void loadPlugin(PluginDescriptor desc) throws Throwable {
Class pluginClass = pluginLoader.loadClass(desc.getClassName());
SavantPlugin plugin = (SavantPlugin)pluginClass.newInstance();
plugin.setDescriptor(desc);
// Init the plugin based on its type
JPanel canvas = null;
if (plugin instanceof SavantPanelPlugin) {
canvas = initGUIPlugin((SavantPanelPlugin)plugin);
} else if (plugin instanceof PluginTool) {
initPluginTool((PluginTool)plugin);
} else if (plugin instanceof SavantDataSourcePlugin) {
initSavantDataSourcePlugin((SavantDataSourcePlugin)plugin);
}
loadedPlugins.put(desc.getID(), plugin);
fireEvent(new PluginEvent(PluginEvent.Type.LOADED, desc.getID(), canvas));
}
/**
* Try to add a plugin from the given file. It is inserted into our internal
* data structures, but not yet loaded.
*/
public PluginDescriptor addPlugin(File f) throws PluginVersionException {
PluginDescriptor desc = PluginDescriptor.fromFile(f);
if (desc != null) {
LOG.info("Found possible " + desc + " in " + f.getName());
PluginDescriptor existingDesc = knownPlugins.get(desc.getID());
if (existingDesc != null && existingDesc.getVersion().compareTo(desc.getVersion()) >= 0) {
LOG.info(" Ignored " + desc + " due to presence of existing " + existingDesc);
return null;
}
knownPlugins.put(desc.getID(), desc);
if (desc.isCompatible()) {
if (existingDesc != null) {
LOG.info(" Replaced " + existingDesc);
pluginErrors.remove(desc.getID());
}
} else {
LOG.info("Found incompatible " + desc + " (SDK version " + desc.getSDKVersion() + ") in " + f.getName());
pluginErrors.put(desc.getID(), "Invalid SDK version (" + desc.getSDKVersion() + ")");
throw new PluginVersionException("Invalid SDK version (" + desc.getSDKVersion() + ")");
}
}
return desc;
}
/**
* Copy the given file to the plugins directory, add it, and load it.
* @param selectedFile
*/
public void installPlugin(File selectedFile) throws Throwable {
File pluginFile = new File(DirectorySettings.getPluginsDirectory(), selectedFile.getName());
IOUtils.copyFile(selectedFile, pluginFile);
PluginDescriptor desc = addPlugin(pluginFile);
pluginLoader.addJar(pluginFile);
loadPlugin(desc);
}
private boolean checkForPluginUpdate(String id) {
try {
if (repositoryIndex == null) {
repositoryIndex = new PluginIndex(BrowserSettings.PLUGIN_URL);
}
URL updateURL = repositoryIndex.getPluginURL(id);
if (updateURL != null) {
LOG.info("Downloading updated version of " + id + " from " + updateURL);
addPlugin(NetworkUtils.downloadFile(updateURL, DirectorySettings.getPluginsDirectory(), null));
return true;
}
} catch (IOException x) {
LOG.error("Unable to install update for " + id, x);
} catch (PluginVersionException x) {
LOG.error("Update for " + id + " not loaded.");
}
return false;
}
class PluginLoader extends URLClassLoader {
PluginLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
void addJar(File f) {
try {
addURL(f.toURI().toURL());
} catch (MalformedURLException ignored) {
}
}
}
}
| false | true | public void loadPlugins(File pluginsDir) {
File[] files = pluginsDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jar");
}
});
for (File f: files) {
try {
addPlugin(f);
} catch (PluginVersionException x) {
LOG.warn("No compatible plugins found in " + f);
}
}
// Check to see if we have any outdated plugins.
if (pluginErrors.size() > 0) {
List<String> updated = new ArrayList<String>();
for (String s: pluginErrors.keySet()) {
// Plugin is invalid, and we don't have a newer version.
if (checkForPluginUpdate(s)) {
updated.add(s);
}
}
if (updated.size() > 0) {
DialogUtils.displayMessage("Plugins Updated", String.format("<html>The following plugins were updated to be compatible with Savant %s:<br><br><i>%s</i></html>", BrowserSettings.VERSION, MiscUtils.join(updated, ", ")));
for (String s: updated) {
pluginErrors.remove(s);
}
}
if (pluginErrors.size() > 0) {
StringBuilder errorStr = null;
for (String s: pluginErrors.keySet()) {
if (errorStr == null) {
errorStr = new StringBuilder();
} else {
errorStr.append("\n");
}
errorStr.append(s);
errorStr.append(" – ");
errorStr.append(pluginErrors.get(s));
}
if (errorStr != null) {
DialogUtils.displayMessage("Plugins Not Loaded", String.format("<html>The following plugins could not be loaded:<br><br><i>%s</i><br><br>They will not be available to Savant.</html>", errorStr));
}
}
}
Set<URL> jarURLs = new HashSet<URL>();
for (PluginDescriptor desc: knownPlugins.values()) {
try {
if (!pluginErrors.containsKey(desc.getID())) {
jarURLs.add(desc.getFile().toURI().toURL());
}
} catch (MalformedURLException ignored) {
}
}
if (jarURLs.size() > 0) {
pluginLoader = new PluginLoader(jarURLs.toArray(new URL[0]), getClass().getClassLoader());
for (final PluginDescriptor desc: knownPlugins.values()) {
if (!pluginErrors.containsKey(desc.getID())) {
new Thread("PluginLoader-" + desc) {
@Override
public void run() {
try {
loadPlugin(desc);
} catch (Throwable x) {
LOG.error("Unable to load " + desc.getName(), x);
pluginErrors.put(desc.getID(), "Error");
}
}
}.start();
}
}
}
}
| public void loadPlugins(File pluginsDir) {
File[] files = pluginsDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jar");
}
});
for (File f: files) {
try {
addPlugin(f);
} catch (PluginVersionException x) {
LOG.warn("No compatible plugins found in " + f);
}
}
// Check to see if we have any outdated plugins.
if (pluginErrors.size() > 0) {
List<String> updated = new ArrayList<String>();
for (String s: pluginErrors.keySet()) {
// Plugin is invalid, and we don't have a newer version.
if (checkForPluginUpdate(s)) {
updated.add(s);
}
}
if (updated.size() > 0) {
DialogUtils.displayMessage("Plugins Updated", String.format("<html>The following plugins were updated to be compatible with Savant %s:<br><br><i>%s</i></html>", BrowserSettings.VERSION, MiscUtils.join(updated, ", ")));
for (String s: updated) {
pluginErrors.remove(s);
}
}
if (pluginErrors.size() > 0) {
StringBuilder errorStr = null;
for (String s: pluginErrors.keySet()) {
if (errorStr == null) {
errorStr = new StringBuilder();
} else {
errorStr.append("\n");
}
errorStr.append(s);
errorStr.append(" – ");
errorStr.append(pluginErrors.get(s));
}
if (errorStr != null) {
// The following dialog will only report plugins which we can tell are faulty before calling loadPlugin(), typically
// by checking the version in plugin.xml.
DialogUtils.displayMessage("Plugins Not Loaded", String.format("<html>The following plugins could not be loaded:<br><br><i>%s</i><br><br>They will not be available to Savant.</html>", errorStr));
}
}
}
Set<URL> jarURLs = new HashSet<URL>();
for (PluginDescriptor desc: knownPlugins.values()) {
try {
if (!pluginErrors.containsKey(desc.getID())) {
jarURLs.add(desc.getFile().toURI().toURL());
}
} catch (MalformedURLException ignored) {
}
}
if (jarURLs.size() > 0) {
pluginLoader = new PluginLoader(jarURLs.toArray(new URL[0]), getClass().getClassLoader());
for (final PluginDescriptor desc: knownPlugins.values()) {
if (!pluginErrors.containsKey(desc.getID())) {
new Thread("PluginLoader-" + desc) {
@Override
public void run() {
try {
loadPlugin(desc);
} catch (Throwable x) {
LOG.error("Unable to load " + desc.getName(), x);
pluginErrors.put(desc.getID(), x.getClass().getName());
DialogUtils.displayMessage("Plugin Not Loaded", String.format("<html>The following plugin could not be loaded:<br><br><i>%s – %s</i><br><br>It will not be available to Savant.</html>", desc.getID(), x));
}
}
}.start();
}
}
}
}
|
diff --git a/src/java/org/apache/commons/beanutils/MethodUtils.java b/src/java/org/apache/commons/beanutils/MethodUtils.java
index 70bf511..c072c72 100644
--- a/src/java/org/apache/commons/beanutils/MethodUtils.java
+++ b/src/java/org/apache/commons/beanutils/MethodUtils.java
@@ -1,851 +1,851 @@
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p> Utility reflection methods focussed on methods in general rather than properties in particular. </p>
*
* <h3>Known Limitations</h3>
* <h4>Accessing Public Methods In A Default Access Superclass</h4>
* <p>There is an issue when invoking public methods contained in a default access superclass.
* Reflection locates these methods fine and correctly assigns them as public.
* However, an <code>IllegalAccessException</code> is thrown if the method is invoked.</p>
*
* <p><code>MethodUtils</code> contains a workaround for this situation.
* It will attempt to call <code>setAccessible</code> on this method.
* If this call succeeds, then the method can be invoked as normal.
* This call will only succeed when the application has sufficient security privilages.
* If this call fails then a warning will be logged and the method may fail.</p>
*
* @author Craig R. McClanahan
* @author Ralph Schaer
* @author Chris Audley
* @author Rey Fran�ois
* @author Gregor Ra�man
* @author Jan Sorensen
* @author Robert Burrell Donkin
*/
public class MethodUtils {
// --------------------------------------------------------- Private Methods
/**
* All logging goes through this logger
*/
private static Log log = LogFactory.getLog(MethodUtils.class);
/** Only log warning about accessibility work around once */
private static boolean loggedAccessibleWarning = false;
/** An empty class array */
private static final Class[] emptyClassArray = new Class[0];
/** An empty object array */
private static final Object[] emptyObjectArray = new Object[0];
/**
* Stores a cache of Methods against MethodDescriptors, in a WeakHashMap.
*/
private static WeakHashMap cache = new WeakHashMap();
// --------------------------------------------------------- Public Methods
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>The behaviour of this method is less deterministic
* than {@link #invokeExactMethod}.
* It loops through all methods with names that match
* and then executes the first it finds with compatable parameters.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
* <p> This is a convenient wrapper for
* {@link #invokeMethod(Object object,String methodName,Object [] args)}.
* </p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param arg use this argument
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeMethod(
Object object,
String methodName,
Object arg)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
Object[] args = {arg};
return invokeMethod(object, methodName, args);
}
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>The behaviour of this method is less deterministic
* than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
* It loops through all methods with names that match
* and then executes the first it finds with compatable parameters.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
* <p> This is a convenient wrapper for
* {@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
* </p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeMethod(
Object object,
String methodName,
Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = emptyObjectArray;
}
int arguments = args.length;
Class parameterTypes [] = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeMethod(object, methodName, args, parameterTypes);
}
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>The behaviour of this method is less deterministic
* than {@link
* #invokeExactMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
* It loops through all methods with names that match
* and then executes the first it finds with compatable parameters.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeMethod(
Object object,
String methodName,
Object[] args,
Class[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (parameterTypes == null) {
parameterTypes = emptyClassArray;
}
if (args == null) {
args = emptyObjectArray;
}
Method method = getMatchingAccessibleMethod(
object.getClass(),
methodName,
parameterTypes);
if (method == null)
throw new NoSuchMethodException("No such accessible method: " +
methodName + "() on object: " + object.getClass().getName());
return method.invoke(object, args);
}
/**
* <p>Invoke a method whose parameter type matches exactly the object
* type.</p>
*
* <p> This is a convenient wrapper for
* {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
* </p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param arg use this argument
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactMethod(
Object object,
String methodName,
Object arg)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
Object[] args = {arg};
return invokeExactMethod(object, methodName, args);
}
/**
* <p>Invoke a method whose parameter types match exactly the object
* types.</p>
*
* <p> This uses reflection to invoke the method obtained from a call to
* {@link #getAccessibleMethod}.</p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactMethod(
Object object,
String methodName,
Object[] args)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = emptyObjectArray;
}
int arguments = args.length;
Class parameterTypes [] = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
/**
* <p>Invoke a method whose parameter types match exactly the parameter
* types given.</p>
*
* <p>This uses reflection to invoke the method obtained from a call to
* {@link #getAccessibleMethod}.</p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactMethod(
Object object,
String methodName,
Object[] args,
Class[] parameterTypes)
throws
NoSuchMethodException,
IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = emptyObjectArray;
}
if (parameterTypes == null) {
parameterTypes = emptyClassArray;
}
Method method = getAccessibleMethod(
object.getClass(),
methodName,
parameterTypes);
if (method == null)
throw new NoSuchMethodException("No such accessible method: " +
methodName + "() on object: " + object.getClass().getName());
return method.invoke(object, args);
}
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) with given name and a single parameter. If no such method
* can be found, return <code>null</code>.
* Basically, a convenience wrapper that constructs a <code>Class</code>
* array for you.</p>
*
* @param clazz get method from this class
* @param methodName get method with this name
* @param parameterType taking this type of parameter
*/
public static Method getAccessibleMethod(
Class clazz,
String methodName,
Class parameterType) {
Class[] parameterTypes = {parameterType};
return getAccessibleMethod(clazz, methodName, parameterTypes);
}
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) with given name and parameters. If no such method
* can be found, return <code>null</code>.
* This is just a convenient wrapper for
* {@link #getAccessibleMethod(Method method)}.</p>
*
* @param clazz get method from this class
* @param methodName get method with this name
* @param parameterTypes with these parameters types
*/
public static Method getAccessibleMethod(
Class clazz,
String methodName,
Class[] parameterTypes) {
try {
MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, true);
// Check the cache first
Method method = (Method)cache.get(md);
if (method != null) {
return method;
}
method = getAccessibleMethod
(clazz.getMethod(methodName, parameterTypes));
cache.put(md, method);
return method;
} catch (NoSuchMethodException e) {
return (null);
}
}
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) that implements the specified Method. If no such method
* can be found, return <code>null</code>.</p>
*
* @param method The method that we wish to call
*/
public static Method getAccessibleMethod(Method method) {
// Make sure we have a method to check
if (method == null) {
return (null);
}
// If the requested method is not public we cannot call it
if (!Modifier.isPublic(method.getModifiers())) {
return (null);
}
// If the declaring class is public, we are done
Class clazz = method.getDeclaringClass();
if (Modifier.isPublic(clazz.getModifiers())) {
return (method);
}
// Check the implemented interfaces and subinterfaces
method =
getAccessibleMethodFromInterfaceNest(clazz,
method.getName(),
method.getParameterTypes());
return (method);
}
// -------------------------------------------------------- Private Methods
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) that implements the specified method, by scanning through
* all implemented interfaces and subinterfaces. If no such method
* can be found, return <code>null</code>.</p>
*
* <p> There isn't any good reason why this method must be private.
* It is because there doesn't seem any reason why other classes should
* call this rather than the higher level methods.</p>
*
* @param clazz Parent class for the interfaces to be checked
* @param methodName Method name of the method we wish to call
* @param parameterTypes The parameter type signatures
*/
private static Method getAccessibleMethodFromInterfaceNest
(Class clazz, String methodName, Class parameterTypes[]) {
Method method = null;
// Search up the superclass chain
for (; clazz != null; clazz = clazz.getSuperclass()) {
// Check the implemented interfaces of the parent class
Class interfaces[] = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
// Is this interface public?
if (!Modifier.isPublic(interfaces[i].getModifiers()))
continue;
// Does the method exist on this interface?
try {
method = interfaces[i].getDeclaredMethod(methodName,
parameterTypes);
} catch (NoSuchMethodException e) {
;
}
if (method != null)
break;
// Recursively check our parent interfaces
method =
getAccessibleMethodFromInterfaceNest(interfaces[i],
methodName,
parameterTypes);
if (method != null)
break;
}
}
// If we found a method return it
if (method != null)
return (method);
// We did not find anything
return (null);
}
/**
* <p>Find an accessible method that matches the given name and has compatible parameters.
* Compatible parameters mean that every method parameter is assignable from
* the given parameters.
* In other words, it finds a method with the given name
* that will take the parameters given.<p>
*
* <p>This method is slightly undeterminstic since it loops
* through methods names and return the first matching method.</p>
*
* <p>This method is used by
* {@link
* #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
*
* <p>This method can match primitive parameter by passing in wrapper classes.
* For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
* parameter.
*
* @param clazz find method in this class
* @param methodName find method with this name
* @param parameterTypes find method with compatible parameters
*/
public static Method getMatchingAccessibleMethod(
Class clazz,
String methodName,
Class[] parameterTypes) {
// trace logging
if (log.isTraceEnabled()) {
log.trace("Matching name=" + methodName + " on " + clazz);
}
MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);
// see if we can find the method directly
// most of the time this works and it's much faster
try {
// Check the cache first
Method method = (Method)cache.get(md);
if (method != null) {
return method;
}
method = clazz.getMethod(methodName, parameterTypes);
if (log.isTraceEnabled()) {
log.trace("Found straight match: " + method);
log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
}
try {
//
// XXX Default access superclass workaround
//
// When a public class has a default access superclass
// with public methods, these methods are accessible.
// Calling them from compiled code works fine.
//
// Unfortunately, using reflection to invoke these methods
// seems to (wrongly) to prevent access even when the method
// modifer is public.
//
// The following workaround solves the problem but will only
// work from sufficiently privilages code.
//
// Better workarounds would be greatfully accepted.
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
boolean vunerableJVM = false;
try {
String specVersion = System.getProperty("java.specification.version");
if (specVersion.charAt(0) == '1' &&
(specVersion.charAt(0) == '0' ||
specVersion.charAt(0) == '1' ||
specVersion.charAt(0) == '2' ||
specVersion.charAt(0) == '3')) {
vunerableJVM = true;
}
} catch (SecurityException e) {
// don't know - so display warning
vunerableJVM = true;
}
if (vunerableJVM) {
log.warn(
"Current Security Manager restricts use of workarounds for reflection bugs "
+ " in pre-1.4 JVMs.");
}
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
} catch (NoSuchMethodException e) { /* SWALLOW */ }
// search through all methods
int paramSize = parameterTypes.length;
Method[] methods = clazz.getMethods();
for (int i = 0, size = methods.length; i < size ; i++) {
if (methods[i].getName().equals(methodName)) {
// log some trace information
if (log.isTraceEnabled()) {
log.trace("Found matching name:");
log.trace(methods[i]);
}
// compare parameters
Class[] methodsParams = methods[i].getParameterTypes();
int methodParamSize = methodsParams.length;
if (methodParamSize == paramSize) {
boolean match = true;
for (int n = 0 ; n < methodParamSize; n++) {
if (log.isTraceEnabled()) {
log.trace("Param=" + parameterTypes[n].getName());
log.trace("Method=" + methodsParams[n].getName());
}
if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
if (log.isTraceEnabled()) {
log.trace(methodsParams[n] + " is not assignable from "
+ parameterTypes[n]);
}
match = false;
break;
}
}
if (match) {
// get accessible version of method
Method method = getAccessibleMethod(methods[i]);
if (method != null) {
if (log.isTraceEnabled()) {
log.trace(method + " accessible version of "
+ methods[i]);
}
try {
//
// XXX Default access superclass workaround
// (See above for more details.)
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
log.warn(
- "Cannot use JVM pre-1.4 access bug workaround die to restrictive security manager.");
+ "Cannot use JVM pre-1.4 access bug workaround due to restrictive security manager.");
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
}
log.trace("Couldn't find accessible method.");
}
}
}
}
// didn't find a match
log.trace("No match found.");
return null;
}
/**
* <p>Determine whether a type can be used as a parameter in a method invocation.
* This method handles primitive conversions correctly.</p>
*
* <p>In order words, it will match a <code>Boolean</code> to a <code>boolean</code>,
* a <code>Long</code> to a <code>long</code>,
* a <code>Float</code> to a <code>float</code>,
* a <code>Integer</code> to a <code>int</code>,
* and a <code>Double</code> to a <code>double</code>.
* Now logic widening matches are allowed.
* For example, a <code>Long</code> will not match a <code>int</code>.
*
* @param parameterType the type of parameter accepted by the method
* @param parameterization the type of parameter being tested
*
* @return true if the assignement is compatible.
*/
public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
// try plain assignment
if (parameterType.isAssignableFrom(parameterization)) {
return true;
}
if (parameterType.isPrimitive()) {
// this method does *not* do widening - you must specify exactly
// is this the right behaviour?
Class parameterWrapperClazz = getPrimitiveWrapper(parameterType);
if (parameterWrapperClazz != null) {
return parameterWrapperClazz.equals(parameterization);
}
}
return false;
}
/**
* Gets the wrapper object class for the given primitive type class.
* For example, passing <code>boolean.class</code> returns <code>Boolean.class</code>
* @param primitiveType the primitive type class for which a match is to be found
* @return the wrapper type associated with the given primitive
* or null if no match is found
*/
public static Class getPrimitiveWrapper(Class primitiveType) {
// does anyone know a better strategy than comparing names?
if (boolean.class.equals(primitiveType)) {
return Boolean.class;
} else if (float.class.equals(primitiveType)) {
return Float.class;
} else if (long.class.equals(primitiveType)) {
return Long.class;
} else if (int.class.equals(primitiveType)) {
return Integer.class;
} else if (short.class.equals(primitiveType)) {
return Short.class;
} else if (byte.class.equals(primitiveType)) {
return Byte.class;
} else if (double.class.equals(primitiveType)) {
return Double.class;
} else if (char.class.equals(primitiveType)) {
return Character.class;
} else {
return null;
}
}
/**
* Gets the class for the primitive type corresponding to the primitive wrapper class given.
* For example, an instance of <code>Boolean.class</code> returns a <code>boolean.class</code>.
* @param wrapperType the
* @return the primitive type class corresponding to the given wrapper class,
* null if no match is found
*/
public static Class getPrimitiveType(Class wrapperType) {
// does anyone know a better strategy than comparing names?
if (Boolean.class.equals(wrapperType)) {
return boolean.class;
} else if (Float.class.equals(wrapperType)) {
return float.class;
} else if (Long.class.equals(wrapperType)) {
return long.class;
} else if (Integer.class.equals(wrapperType)) {
return int.class;
} else if (Short.class.equals(wrapperType)) {
return short.class;
} else if (Byte.class.equals(wrapperType)) {
return byte.class;
} else if (Double.class.equals(wrapperType)) {
return double.class;
} else if (Character.class.equals(wrapperType)) {
return char.class;
} else {
if (log.isDebugEnabled()) {
log.debug("Not a known primitive wrapper class: " + wrapperType);
}
return null;
}
}
/**
* Find a non primitive representation for given primitive class.
*
* @param Class the class to find a representation for, not null
* @return the original class if it not a primitive. Otherwise the wrapper class. Not null
*/
public static Class toNonPrimitiveClass(Class clazz) {
if (clazz.isPrimitive()) {
Class primitiveClazz = MethodUtils.getPrimitiveWrapper(clazz);
// the above method returns
if (primitiveClazz != null) {
return primitiveClazz;
} else {
return clazz;
}
} else {
return clazz;
}
}
/**
* Represents the key to looking up a Method by reflection.
*/
private static class MethodDescriptor {
private Class cls;
private String methodName;
private Class[] paramTypes;
private boolean exact;
private int hashCode;
/**
* The sole constructor.
*
* @param cls the class to reflect, must not be null
* @param methodName the method name to obtain
* @param paramTypes the array of classes representing the paramater types
* @param exact whether the match has to be exact.
*/
public MethodDescriptor(Class cls, String methodName, Class[] paramTypes, boolean exact) {
if (cls == null) {
throw new IllegalArgumentException("Class cannot be null");
}
if (methodName == null) {
throw new IllegalArgumentException("Method Name cannot be null");
}
if (paramTypes == null) {
paramTypes = emptyClassArray;
}
this.cls = cls;
this.methodName = methodName;
this.paramTypes = paramTypes;
this.exact= exact;
this.hashCode = methodName.length();
}
/**
* Checks for equality.
* @param obj object to be tested for equality
* @return true, if the object describes the same Method.
*/
public boolean equals(Object obj) {
if (!(obj instanceof MethodDescriptor)) {
return false;
}
MethodDescriptor md = (MethodDescriptor)obj;
return (
exact == md.exact &&
methodName.equals(md.methodName) &&
cls.equals(md.cls) &&
java.util.Arrays.equals(paramTypes, md.paramTypes)
);
}
/**
* Returns the string length of method name. I.e. if the
* hashcodes are different, the objects are different. If the
* hashcodes are the same, need to use the equals method to
* determine equality.
* @return the string length of method name.
*/
public int hashCode() {
return hashCode;
}
}
}
| true | true | public static Method getMatchingAccessibleMethod(
Class clazz,
String methodName,
Class[] parameterTypes) {
// trace logging
if (log.isTraceEnabled()) {
log.trace("Matching name=" + methodName + " on " + clazz);
}
MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);
// see if we can find the method directly
// most of the time this works and it's much faster
try {
// Check the cache first
Method method = (Method)cache.get(md);
if (method != null) {
return method;
}
method = clazz.getMethod(methodName, parameterTypes);
if (log.isTraceEnabled()) {
log.trace("Found straight match: " + method);
log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
}
try {
//
// XXX Default access superclass workaround
//
// When a public class has a default access superclass
// with public methods, these methods are accessible.
// Calling them from compiled code works fine.
//
// Unfortunately, using reflection to invoke these methods
// seems to (wrongly) to prevent access even when the method
// modifer is public.
//
// The following workaround solves the problem but will only
// work from sufficiently privilages code.
//
// Better workarounds would be greatfully accepted.
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
boolean vunerableJVM = false;
try {
String specVersion = System.getProperty("java.specification.version");
if (specVersion.charAt(0) == '1' &&
(specVersion.charAt(0) == '0' ||
specVersion.charAt(0) == '1' ||
specVersion.charAt(0) == '2' ||
specVersion.charAt(0) == '3')) {
vunerableJVM = true;
}
} catch (SecurityException e) {
// don't know - so display warning
vunerableJVM = true;
}
if (vunerableJVM) {
log.warn(
"Current Security Manager restricts use of workarounds for reflection bugs "
+ " in pre-1.4 JVMs.");
}
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
} catch (NoSuchMethodException e) { /* SWALLOW */ }
// search through all methods
int paramSize = parameterTypes.length;
Method[] methods = clazz.getMethods();
for (int i = 0, size = methods.length; i < size ; i++) {
if (methods[i].getName().equals(methodName)) {
// log some trace information
if (log.isTraceEnabled()) {
log.trace("Found matching name:");
log.trace(methods[i]);
}
// compare parameters
Class[] methodsParams = methods[i].getParameterTypes();
int methodParamSize = methodsParams.length;
if (methodParamSize == paramSize) {
boolean match = true;
for (int n = 0 ; n < methodParamSize; n++) {
if (log.isTraceEnabled()) {
log.trace("Param=" + parameterTypes[n].getName());
log.trace("Method=" + methodsParams[n].getName());
}
if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
if (log.isTraceEnabled()) {
log.trace(methodsParams[n] + " is not assignable from "
+ parameterTypes[n]);
}
match = false;
break;
}
}
if (match) {
// get accessible version of method
Method method = getAccessibleMethod(methods[i]);
if (method != null) {
if (log.isTraceEnabled()) {
log.trace(method + " accessible version of "
+ methods[i]);
}
try {
//
// XXX Default access superclass workaround
// (See above for more details.)
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
log.warn(
"Cannot use JVM pre-1.4 access bug workaround die to restrictive security manager.");
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
}
log.trace("Couldn't find accessible method.");
}
}
}
}
// didn't find a match
log.trace("No match found.");
return null;
}
| public static Method getMatchingAccessibleMethod(
Class clazz,
String methodName,
Class[] parameterTypes) {
// trace logging
if (log.isTraceEnabled()) {
log.trace("Matching name=" + methodName + " on " + clazz);
}
MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);
// see if we can find the method directly
// most of the time this works and it's much faster
try {
// Check the cache first
Method method = (Method)cache.get(md);
if (method != null) {
return method;
}
method = clazz.getMethod(methodName, parameterTypes);
if (log.isTraceEnabled()) {
log.trace("Found straight match: " + method);
log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
}
try {
//
// XXX Default access superclass workaround
//
// When a public class has a default access superclass
// with public methods, these methods are accessible.
// Calling them from compiled code works fine.
//
// Unfortunately, using reflection to invoke these methods
// seems to (wrongly) to prevent access even when the method
// modifer is public.
//
// The following workaround solves the problem but will only
// work from sufficiently privilages code.
//
// Better workarounds would be greatfully accepted.
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
boolean vunerableJVM = false;
try {
String specVersion = System.getProperty("java.specification.version");
if (specVersion.charAt(0) == '1' &&
(specVersion.charAt(0) == '0' ||
specVersion.charAt(0) == '1' ||
specVersion.charAt(0) == '2' ||
specVersion.charAt(0) == '3')) {
vunerableJVM = true;
}
} catch (SecurityException e) {
// don't know - so display warning
vunerableJVM = true;
}
if (vunerableJVM) {
log.warn(
"Current Security Manager restricts use of workarounds for reflection bugs "
+ " in pre-1.4 JVMs.");
}
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
} catch (NoSuchMethodException e) { /* SWALLOW */ }
// search through all methods
int paramSize = parameterTypes.length;
Method[] methods = clazz.getMethods();
for (int i = 0, size = methods.length; i < size ; i++) {
if (methods[i].getName().equals(methodName)) {
// log some trace information
if (log.isTraceEnabled()) {
log.trace("Found matching name:");
log.trace(methods[i]);
}
// compare parameters
Class[] methodsParams = methods[i].getParameterTypes();
int methodParamSize = methodsParams.length;
if (methodParamSize == paramSize) {
boolean match = true;
for (int n = 0 ; n < methodParamSize; n++) {
if (log.isTraceEnabled()) {
log.trace("Param=" + parameterTypes[n].getName());
log.trace("Method=" + methodsParams[n].getName());
}
if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
if (log.isTraceEnabled()) {
log.trace(methodsParams[n] + " is not assignable from "
+ parameterTypes[n]);
}
match = false;
break;
}
}
if (match) {
// get accessible version of method
Method method = getAccessibleMethod(methods[i]);
if (method != null) {
if (log.isTraceEnabled()) {
log.trace(method + " accessible version of "
+ methods[i]);
}
try {
//
// XXX Default access superclass workaround
// (See above for more details.)
//
method.setAccessible(true);
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
if (!loggedAccessibleWarning) {
log.warn(
"Cannot use JVM pre-1.4 access bug workaround due to restrictive security manager.");
loggedAccessibleWarning = true;
}
log.debug(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
cache.put(md, method);
return method;
}
log.trace("Couldn't find accessible method.");
}
}
}
}
// didn't find a match
log.trace("No match found.");
return null;
}
|
diff --git a/src/edu/sc/seis/sod/status/MapPool.java b/src/edu/sc/seis/sod/status/MapPool.java
index a8641b17c..f80466d02 100755
--- a/src/edu/sc/seis/sod/status/MapPool.java
+++ b/src/edu/sc/seis/sod/status/MapPool.java
@@ -1,51 +1,51 @@
package edu.sc.seis.sod.status;
import edu.sc.seis.fissuresUtil.map.OpenMap;
import edu.sc.seis.fissuresUtil.map.colorizer.event.EventColorizer;
import edu.sc.seis.fissuresUtil.map.layers.EventLayer;
import edu.sc.seis.fissuresUtil.map.layers.StationLayer;
public class MapPool{
public MapPool(int mapCount, EventColorizer colorizer){
maps = new OpenMap[mapCount];
free = new boolean[mapCount];
for (int i = 0; i < maps.length; i++) {
maps[i] =
new OpenMap("edu/sc/seis/fissuresUtil/data/maps/dcwpo-browse");
maps[i].setEtopoLayer("edu/sc/seis/mapData");
- maps[i].setEventLayer(new EventLayer(maps[i].getMapBean(), colorizer));
+ maps[i].setEventLayer(new EventLayer(maps[i], colorizer));
maps[i].setStationLayer(new StationLayer());
maps[i].overrideProjChangedInOMLayers(true);
free[i] = true;
}
}
public OpenMap getMap(){
while(true){
for (int i = 0; i < maps.length; i++) {
synchronized(free){
if(free[i]) {
free[i] = false;
return maps[i];
}
}
}
try { Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
public void returnMap(OpenMap map){
clear(map);
for (int i = 0; i < maps.length; i++)
if(maps[i] == map) synchronized(free){free[i] = true;}
}
private void clear(OpenMap map){
map.getEventLayer().eventDataCleared();
map.getStationLayer().stationDataCleared();
}
private boolean[] free;
private OpenMap[] maps;
}
| true | true | public MapPool(int mapCount, EventColorizer colorizer){
maps = new OpenMap[mapCount];
free = new boolean[mapCount];
for (int i = 0; i < maps.length; i++) {
maps[i] =
new OpenMap("edu/sc/seis/fissuresUtil/data/maps/dcwpo-browse");
maps[i].setEtopoLayer("edu/sc/seis/mapData");
maps[i].setEventLayer(new EventLayer(maps[i].getMapBean(), colorizer));
maps[i].setStationLayer(new StationLayer());
maps[i].overrideProjChangedInOMLayers(true);
free[i] = true;
}
}
| public MapPool(int mapCount, EventColorizer colorizer){
maps = new OpenMap[mapCount];
free = new boolean[mapCount];
for (int i = 0; i < maps.length; i++) {
maps[i] =
new OpenMap("edu/sc/seis/fissuresUtil/data/maps/dcwpo-browse");
maps[i].setEtopoLayer("edu/sc/seis/mapData");
maps[i].setEventLayer(new EventLayer(maps[i], colorizer));
maps[i].setStationLayer(new StationLayer());
maps[i].overrideProjChangedInOMLayers(true);
free[i] = true;
}
}
|
diff --git a/intro/assignment_4/ArrayAssignments.java b/intro/assignment_4/ArrayAssignments.java
index 83e1cfc..430d481 100644
--- a/intro/assignment_4/ArrayAssignments.java
+++ b/intro/assignment_4/ArrayAssignments.java
@@ -1,102 +1,102 @@
/**
* @author Ory Band
* @version 1.0
*/
public class ArrayAssignments implements Assignments {
private Assignment[] assignments;
/** @return new ArrayAssignment object with no assignments. */
public ArrayAssignments() {
this.assignments = new Assignment[0];
}
/**
* @param assignments Assignment array.
*
* @return new ArrayAssignment object with initial assignments given as argument.
*/
public ArrayAssignments(Assignment[] s) {
// Basic validity tests.
if (s == null) {
throw new RuntimeException("Assignment[] argument is null.");
} else if (s.length == 0) {
throw new RuntimeException("Assignment[] argument is of length 0!");
}
// Test for valid assignments.
for (int i=0; i<s.length; i++) {
if (s[i] == null) {
throw new RuntimeException("Assignment[" + i + "] is null.");
}
// Test for duplicate variable names inside assignments.
for (int j=i+1; j<s.length; j++) {
if (s[j] == null) {
- throw new RuntimeException("Assignment[" + i + "] is null.");
+ throw new RuntimeException("Assignment[" + j + "] is null.");
} else if (s[j].getVar().getName() == s[i].getVar().getName()) {
throw new RuntimeException("Assigment[" + i + "] and Assignment[" + j + "] " +
"are using the same variable '" +
s[i].getVar().getName() + " = " + s[i].getValue());
}
}
}
this.assignments = s; // Shallow copy according to FAQ page.
// Deep copy assignments.
/*this.assignments = new Assignment[s.length];
for (i=0; i < s.length; i++) {
for (j=i+1; j<s.length;
this.assignments[i] = s[i];
}*/
}
public double valueOf(Variable v) {
// Validate argument.
if (v == null) {
throw new RuntimeException("Variable argument is null.");
}
// Search for v in the assignments list.
for (int i=0; i < this.assignments.length; i++) {
if (this.assignments[i].getVar().equals(v)) {
return this.assignments[i].getValue();
}
}
// If v wasn't found, throw exception.
throw new RuntimeException("Variable " + v.getName() + " has no valid assignment!");
}
public void addAssignment(Assignment a) {
if (a == null) {
throw new RuntimeException("Assignment argument is null.");
}
// Update assignment if it's already in the assignments' list.
int i;
for (i=0; i < this.assignments.length; i++) {
if (this.assignments[i].getVar().getName() == (a.getVar().getName())) {
this.assignments[i].setValue(a.getValue());
return; // No need to extend the assignments list if we only needed to update one of its variables.
}
}
// Creates a new list, and add a single new assignment to it.
Assignment[] copy = new Assignment[assignments.length +1];
// Copies the old assignments.
for (i=0; i < this.assignments.length; i++) {
copy[i] = this.assignments[i];
}
// Add the new assignment to the end of the list.
copy[copy.length -1] = a;
// Replace the old assignments list with new one.
this.assignments = copy;
}
}
| true | true | public ArrayAssignments(Assignment[] s) {
// Basic validity tests.
if (s == null) {
throw new RuntimeException("Assignment[] argument is null.");
} else if (s.length == 0) {
throw new RuntimeException("Assignment[] argument is of length 0!");
}
// Test for valid assignments.
for (int i=0; i<s.length; i++) {
if (s[i] == null) {
throw new RuntimeException("Assignment[" + i + "] is null.");
}
// Test for duplicate variable names inside assignments.
for (int j=i+1; j<s.length; j++) {
if (s[j] == null) {
throw new RuntimeException("Assignment[" + i + "] is null.");
} else if (s[j].getVar().getName() == s[i].getVar().getName()) {
throw new RuntimeException("Assigment[" + i + "] and Assignment[" + j + "] " +
"are using the same variable '" +
s[i].getVar().getName() + " = " + s[i].getValue());
}
}
}
this.assignments = s; // Shallow copy according to FAQ page.
// Deep copy assignments.
/*this.assignments = new Assignment[s.length];
for (i=0; i < s.length; i++) {
for (j=i+1; j<s.length;
this.assignments[i] = s[i];
}*/
}
| public ArrayAssignments(Assignment[] s) {
// Basic validity tests.
if (s == null) {
throw new RuntimeException("Assignment[] argument is null.");
} else if (s.length == 0) {
throw new RuntimeException("Assignment[] argument is of length 0!");
}
// Test for valid assignments.
for (int i=0; i<s.length; i++) {
if (s[i] == null) {
throw new RuntimeException("Assignment[" + i + "] is null.");
}
// Test for duplicate variable names inside assignments.
for (int j=i+1; j<s.length; j++) {
if (s[j] == null) {
throw new RuntimeException("Assignment[" + j + "] is null.");
} else if (s[j].getVar().getName() == s[i].getVar().getName()) {
throw new RuntimeException("Assigment[" + i + "] and Assignment[" + j + "] " +
"are using the same variable '" +
s[i].getVar().getName() + " = " + s[i].getValue());
}
}
}
this.assignments = s; // Shallow copy according to FAQ page.
// Deep copy assignments.
/*this.assignments = new Assignment[s.length];
for (i=0; i < s.length; i++) {
for (j=i+1; j<s.length;
this.assignments[i] = s[i];
}*/
}
|
diff --git a/org.eclipse.riena.ui.ridgets/src/org/eclipse/riena/ui/ridgets/AbstractMarkerSupport.java b/org.eclipse.riena.ui.ridgets/src/org/eclipse/riena/ui/ridgets/AbstractMarkerSupport.java
index 6544f444b..478e5dc70 100644
--- a/org.eclipse.riena.ui.ridgets/src/org/eclipse/riena/ui/ridgets/AbstractMarkerSupport.java
+++ b/org.eclipse.riena.ui.ridgets/src/org/eclipse/riena/ui/ridgets/AbstractMarkerSupport.java
@@ -1,171 +1,170 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 compeople AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.ui.ridgets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.riena.core.marker.IMarker;
import org.eclipse.riena.core.marker.IMarkerAttributeChangeListener;
import org.eclipse.riena.ui.core.marker.IMarkerPropertyChangeEvent;
/**
* Helper class for Ridgets to delegate their marker issues to.
*/
public abstract class AbstractMarkerSupport {
private Set<IMarker> markers;
protected IMarkableRidget ridget;
private PropertyChangeSupport propertyChangeSupport;
private IMarkerAttributeChangeListener markerAttributeChangeListener;
public AbstractMarkerSupport(IMarkableRidget ridget, PropertyChangeSupport propertyChangeSupport) {
this.ridget = ridget;
this.propertyChangeSupport = propertyChangeSupport;
markerAttributeChangeListener = new MarkerAttributeChangeListener();
}
/**
* Updates the UI-control to display the current markers.
*
* @see #getUIControl()
* @see #getMarkers()
*/
public abstract void updateMarkers();
/**
* @see org.eclipse.riena.ui.ridgets.IMarkableRidget#addMarker(org.eclipse.riena.core.marker.IMarker)
*/
public void addMarker(IMarker marker) {
if (marker == null) {
return;
}
Collection<IMarker> oldValue = getMarkers();
if (markers == null) {
markers = new HashSet<IMarker>(1, 1.0f);
}
if (markers.add(marker)) {
- // TODO scp updateMandatoryMarkers();
updateMarkers();
fireMarkerPropertyChangeEvent(oldValue);
marker.addAttributeChangeListener(markerAttributeChangeListener);
}
}
/**
* @see org.eclipse.riena.ui.ridgets.IMarkableRidget#getMarkers()
*/
public Collection<IMarker> getMarkers() {
if (markers != null) {
return new HashSet<IMarker>(markers);
} else {
return Collections.emptySet();
}
}
/**
* @see org.eclipse.riena.ui.ridgets.IMarkableRidget#getMarkersOfType(java.lang.Class)
*/
public <T extends IMarker> Collection<T> getMarkersOfType(Class<T> type) {
if (type == null) {
return Collections.emptyList();
}
List<T> typedMarkerList = new ArrayList<T>();
for (IMarker marker : getMarkers()) {
if (type.isAssignableFrom(marker.getClass())) {
typedMarkerList.add((T) marker);
}
}
return typedMarkerList;
}
/**
* @see org.eclipse.riena.ui.ridgets.IMarkableRidget#removeAllMarkers()
*/
public void removeAllMarkers() {
if (markers != null) {
Collection<IMarker> oldValue = getMarkers();
for (IMarker marker : markers) {
marker.removeAttributeChangeListener(markerAttributeChangeListener);
}
markers.clear();
if (oldValue.size() > 0) {
updateMarkers();
fireMarkerPropertyChangeEvent(oldValue);
}
}
}
/**
* @see org.eclipse.riena.ui.ridgets.IMarkableRidget#removeMarker(org.eclipse.riena.core.marker.IMarker)
*/
public void removeMarker(IMarker marker) {
if (markers != null) {
Collection<IMarker> oldValue = getMarkers();
if (markers.remove(marker)) {
updateMarkers();
fireMarkerPropertyChangeEvent(oldValue);
marker.removeAttributeChangeListener(markerAttributeChangeListener);
}
}
}
protected Object getUIControl() {
return ridget.getUIControl();
}
private void fireMarkerPropertyChangeEvent(Collection<IMarker> oldValue) {
propertyChangeSupport.firePropertyChange(new MarkerPropertyChangeEvent(oldValue, ridget, getMarkers()));
}
protected void handleMarkerAttributesChanged() {
propertyChangeSupport.firePropertyChange(new MarkerPropertyChangeEvent(true, ridget, getMarkers()));
}
private static final class MarkerPropertyChangeEvent extends PropertyChangeEvent implements
IMarkerPropertyChangeEvent {
private static final long serialVersionUID = 1L;
private boolean attributeRelated = false;
private MarkerPropertyChangeEvent(Object oldValue, IMarkableRidget source, Object newValue) {
super(source, IMarkableRidget.PROPERTY_MARKER, oldValue, newValue);
}
private MarkerPropertyChangeEvent(boolean attributeRelated, IMarkableRidget source, Object newValue) {
this(null, source, newValue);
this.attributeRelated = attributeRelated;
}
public boolean isAttributeRelated() {
return attributeRelated;
}
}
private class MarkerAttributeChangeListener implements IMarkerAttributeChangeListener {
/**
* @see de.compeople.spirit.core.client.uibinding.IMarkerAttributeChangeListener#attributesChanged()
*/
public void attributesChanged() {
handleMarkerAttributesChanged();
}
}
}
| true | true | public void addMarker(IMarker marker) {
if (marker == null) {
return;
}
Collection<IMarker> oldValue = getMarkers();
if (markers == null) {
markers = new HashSet<IMarker>(1, 1.0f);
}
if (markers.add(marker)) {
// TODO scp updateMandatoryMarkers();
updateMarkers();
fireMarkerPropertyChangeEvent(oldValue);
marker.addAttributeChangeListener(markerAttributeChangeListener);
}
}
| public void addMarker(IMarker marker) {
if (marker == null) {
return;
}
Collection<IMarker> oldValue = getMarkers();
if (markers == null) {
markers = new HashSet<IMarker>(1, 1.0f);
}
if (markers.add(marker)) {
updateMarkers();
fireMarkerPropertyChangeEvent(oldValue);
marker.addAttributeChangeListener(markerAttributeChangeListener);
}
}
|
diff --git a/src/main/java/org/efreak/bukkitmanager/addon/ftpbackup/FTPStorage.java b/src/main/java/org/efreak/bukkitmanager/addon/ftpbackup/FTPStorage.java
index 449d288..68bcd70 100644
--- a/src/main/java/org/efreak/bukkitmanager/addon/ftpbackup/FTPStorage.java
+++ b/src/main/java/org/efreak/bukkitmanager/addon/ftpbackup/FTPStorage.java
@@ -1,112 +1,112 @@
package org.efreak.bukkitmanager.addon.ftpbackup;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.commons.net.util.TrustManagerUtils;
import org.efreak.bukkitmanager.util.BackupStorage;
import org.efreak.bukkitmanager.util.FileHelper;
import org.efreak.bukkitmanager.util.NotificationsHandler;
public class FTPStorage extends BackupStorage {
private static String host, username, password, path, hostString, trustmgr, protocol;
private static int port;
private static boolean logging, ftps, implicit;
public FTPStorage() {
enabled = config.getBoolean("Autobackup.FTP.Enabled");
tempDir = new File(FileHelper.getBackupDir(), "ftptemp");
if (!tempDir.exists()) tempDir.mkdir();
}
static {
host = config.getString("Autobackup.FTP.Host");
port = config.getInt("Autobackup.FTP.Port");
username = config.getString("Autobackup.FTP.Username");
password = config.getString("Autobackup.FTP.Password");
path = config.getString("Autobackup.FTP.Path");
logging = config.getBoolean("Autobackup.FTP.Logging");
ftps = config.getBoolean("Autobackup.FTP.FTPS");
trustmgr = config.getString("Autobackup.FTP.TrustManager");
protocol = config.getString("Autobackup.FTP.Protocol");
implicit = config.getBoolean("Autobackup.FTP.isImplicit");
if (ftps) hostString = "ftps://" + host + ":" + port;
else hostString = "ftp://" + host + ":" + port;
}
@Override
public boolean storeFile() {
io.sendConsole(io.translate("FTPBackup.Start").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Started")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploading Backup to " + hostString);
boolean returnValue = true;
FTPClient ftp;
if (!ftps) ftp = new FTPClient();
else {
FTPSClient ftps;
if (protocol == "") ftps = new FTPSClient(implicit);
else ftps = new FTPSClient(protocol, implicit);
if ("all".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
} else if ("valid".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
} else if ("none".equals(trustmgr)) {
ftps.setTrustManager(null);
}
ftp = ftps;
}
try {
ftp.connect(host, port);
if (logging) io.sendConsole(io.translate("FTPBackup.Connected").replaceAll("%host%", hostString));
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
io.sendConsoleError(io.translate("FTPBackup.Refused"));
return false;
}
if (!ftp.login(username, password)) {
ftp.logout();
io.sendConsoleError(io.translate("FTPBackup.LoginError"));
return false;
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(path);
InputStream input = new FileInputStream(backupFile);
if (logging) {
- if (path != "") io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%path%", path + "/" + backupFile.getName()));
- else io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%path%", backupFile.getName()));
+ if (path != "") io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%location%", path + "/" + backupFile.getName()));
+ else io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%location%", backupFile.getName()));
}
ftp.storeFile(backupFile.getName(), input);
input.close();
ftp.logout();
}catch (Exception e) {
io.sendConsoleError(io.translate("FTPBackup.CantConnect").replaceAll("%host%", hostString));
if (config.getDebug()) e.printStackTrace();
returnValue = false;
}finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
}catch (Exception e) {
if (config.getDebug()) e.printStackTrace();
}
}
}
if (returnValue) {
io.sendConsole(io.translate("FTPBackup.Uploaded").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploaded Backup to " + hostString);
}else {
io.sendConsoleWarning(io.translate("FTPBackup.Error").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Error uploading Backup to " + hostString);
}
return returnValue;
}
}
| true | true | public boolean storeFile() {
io.sendConsole(io.translate("FTPBackup.Start").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Started")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploading Backup to " + hostString);
boolean returnValue = true;
FTPClient ftp;
if (!ftps) ftp = new FTPClient();
else {
FTPSClient ftps;
if (protocol == "") ftps = new FTPSClient(implicit);
else ftps = new FTPSClient(protocol, implicit);
if ("all".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
} else if ("valid".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
} else if ("none".equals(trustmgr)) {
ftps.setTrustManager(null);
}
ftp = ftps;
}
try {
ftp.connect(host, port);
if (logging) io.sendConsole(io.translate("FTPBackup.Connected").replaceAll("%host%", hostString));
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
io.sendConsoleError(io.translate("FTPBackup.Refused"));
return false;
}
if (!ftp.login(username, password)) {
ftp.logout();
io.sendConsoleError(io.translate("FTPBackup.LoginError"));
return false;
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(path);
InputStream input = new FileInputStream(backupFile);
if (logging) {
if (path != "") io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%path%", path + "/" + backupFile.getName()));
else io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%path%", backupFile.getName()));
}
ftp.storeFile(backupFile.getName(), input);
input.close();
ftp.logout();
}catch (Exception e) {
io.sendConsoleError(io.translate("FTPBackup.CantConnect").replaceAll("%host%", hostString));
if (config.getDebug()) e.printStackTrace();
returnValue = false;
}finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
}catch (Exception e) {
if (config.getDebug()) e.printStackTrace();
}
}
}
if (returnValue) {
io.sendConsole(io.translate("FTPBackup.Uploaded").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploaded Backup to " + hostString);
}else {
io.sendConsoleWarning(io.translate("FTPBackup.Error").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Error uploading Backup to " + hostString);
}
return returnValue;
}
| public boolean storeFile() {
io.sendConsole(io.translate("FTPBackup.Start").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Started")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploading Backup to " + hostString);
boolean returnValue = true;
FTPClient ftp;
if (!ftps) ftp = new FTPClient();
else {
FTPSClient ftps;
if (protocol == "") ftps = new FTPSClient(implicit);
else ftps = new FTPSClient(protocol, implicit);
if ("all".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
} else if ("valid".equals(trustmgr)) {
ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
} else if ("none".equals(trustmgr)) {
ftps.setTrustManager(null);
}
ftp = ftps;
}
try {
ftp.connect(host, port);
if (logging) io.sendConsole(io.translate("FTPBackup.Connected").replaceAll("%host%", hostString));
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
io.sendConsoleError(io.translate("FTPBackup.Refused"));
return false;
}
if (!ftp.login(username, password)) {
ftp.logout();
io.sendConsoleError(io.translate("FTPBackup.LoginError"));
return false;
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(path);
InputStream input = new FileInputStream(backupFile);
if (logging) {
if (path != "") io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%location%", path + "/" + backupFile.getName()));
else io.sendConsole(io.translate("FTPBackup.Uploading").replaceAll("%location%", backupFile.getName()));
}
ftp.storeFile(backupFile.getName(), input);
input.close();
ftp.logout();
}catch (Exception e) {
io.sendConsoleError(io.translate("FTPBackup.CantConnect").replaceAll("%host%", hostString));
if (config.getDebug()) e.printStackTrace();
returnValue = false;
}finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
}catch (Exception e) {
if (config.getDebug()) e.printStackTrace();
}
}
}
if (returnValue) {
io.sendConsole(io.translate("FTPBackup.Uploaded").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Uploaded Backup to " + hostString);
}else {
io.sendConsoleWarning(io.translate("FTPBackup.Error").replaceAll("%host%", hostString));
if (config.getBoolean("Notifications.Autobackup.FTP.Finished")) NotificationsHandler.notify("Bukkitmanager", "FTPBackup Addon", "Error uploading Backup to " + hostString);
}
return returnValue;
}
|
diff --git a/EDUkid/src/bu/edu/cs673/edukid/settings/AddCategoryView.java b/EDUkid/src/bu/edu/cs673/edukid/settings/AddCategoryView.java
index 959b38c..7b14ff4 100644
--- a/EDUkid/src/bu/edu/cs673/edukid/settings/AddCategoryView.java
+++ b/EDUkid/src/bu/edu/cs673/edukid/settings/AddCategoryView.java
@@ -1,17 +1,17 @@
package bu.edu.cs673.edukid.settings;
import bu.edu.cs673.edukid.R;
import android.app.Activity;
import android.os.Bundle;
public class AddCategoryView extends Activity {
/**
* {@inheritDoc}
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.add_category);
+ //setContentView(R.layout.add_category);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_category);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.add_category);
}
|
diff --git a/src/java/fedora/client/batch/BatchXforms.java b/src/java/fedora/client/batch/BatchXforms.java
index 94df0f8f2..81eb2505d 100755
--- a/src/java/fedora/client/batch/BatchXforms.java
+++ b/src/java/fedora/client/batch/BatchXforms.java
@@ -1,259 +1,259 @@
package fedora.client.batch;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.File;
//import java.util.Hashtable;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
//import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactory; // RunXSLT works with this
//import javax.xml.transform.sax.SAXTransformerFactory; // was with error
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.BufferedReader;
import java.util.Vector;
/**
*
* <p><b>Title:</b> BatchXforms.java</p>
* <p><b>Description:</b> </p>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>The contents of this file are subject to the
* Mozilla Public License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.</p>
*
* <p>The entire file consists of original code. Copyright © 2002, 2003 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @author [email protected]
* @version 1.0
*/
class BatchXforms {
/** Constants used for JAXP 1.2 */
private static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
private static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
private String additionsPath = null;
private String objectsPath = null;
private String xformPath = null;
private String modelPath = null;
private Transformer transformer = null;
BatchXforms(Properties optValues) throws Exception {
xformPath = System.getProperty("fedora.home") + "/client/lib/merge.xsl";
additionsPath = optValues.getProperty(BatchTool.ADDITIONSPATH);
objectsPath = optValues.getProperty(BatchTool.OBJECTSPATH);
modelPath = optValues.getProperty(BatchTool.CMODEL);
if (! BatchTool.argOK(additionsPath)) {
System.err.println("additionsPath required");
throw new Exception();
}
if (! BatchTool.argOK(objectsPath)) {
System.err.println("objectsPath required");
throw new Exception();
}
if (! BatchTool.argOK(xformPath)) {
System.err.println("xformPath required");
throw new Exception();
}
}
private static final String[] padding = {"", "0", "00", "000"};
private static final String leftPadded (int i, int n) throws Exception {
if ((n > 3) || (n < 0) || (i < 0) || (i > 999)) {
throw new Exception();
}
int m = (i > 99) ? 3 : (i > 9) ? 2 : 1;
int p = n - m;
return padding[p] + Integer.toString(i);
}
private boolean good2go = false;
final void prep() throws Exception {
good2go = true;
}
private Vector keys = null;
/* package */ Vector getKeys() {
return keys;
}
final void process() throws TransformerConfigurationException, Exception {
//System.err.println("before TransformerFactory.newInstance()"); //<<==
//System.err.println("xformPath=[" + xformPath + "]"); //<<==
//SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT
//System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<==
keys = new Vector();
if (good2go) {
int count = 0;
File file4catch = null;
int files4catch = 0;
int badFileCount = 0;
int succeededBuildCount = 0;
int failedBuildCount = 0;
try {
File[] files = null; {
// System.err.println("additions path " + additionsPath);
File additionsDirectory = new File(additionsPath);
files = additionsDirectory.listFiles();
}
//int badFileCount = 0;
files4catch = files.length;
for (int i = 0; i < files.length; i++) {
//System.err.println("another it");
file4catch = files[i];
if (! files[i].isFile()) {
badFileCount++;
System.err.println("additions directory contains unexpected directory or file: " + files[i].getName());
} else {
//System.err.println("before tfactory.newTransformer()"); //<<==
File f = new File(xformPath);
//System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]");
StreamSource ss = new StreamSource(f);
//System.err.println("ss null=[" + (ss == null) + "]");
/*
Reader r = ss.getReader();
System.err.println("r null=[" + (r == null) + "]");
BufferedReader br = new BufferedReader(r);
System.err.println("br null=[" + (br == null) + "]");
String st = br.readLine();
System.err.println("st null=[" + (st == null) + "]");
System.err.println("first line[" + st + "]");
System.err.println("after dummy SS"); //<<==
System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<==
*/
transformer = tfactory.newTransformer(ss); //xformPath
//System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null));
GregorianCalendar calendar = new GregorianCalendar();
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = leftPadded(1+ calendar.get(Calendar.MONTH),2);
String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2);
String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2);
String minute = leftPadded(calendar.get(Calendar.MINUTE),2);
String second = leftPadded(calendar.get(Calendar.SECOND),2);
transformer.setParameter("date",
year + "-" + month + "-" + dayOfMonth +
"T" + hourOfDay + ":" + minute + ":" + second);
//"2002-05-20T06:32:00"
//System.err.println("about to xform " + count++);
//System.err.println(">>>>>>>>>>>>" + files[i].getPath());
//System.err.println("objectsPath [" + objectsPath + "]");
/*
for (int bb=0; bb<objectsPath.length(); bb++) {
char c = objectsPath.charAt(bb);
int n = Character.getNumericValue(c);
boolean t = Character.isISOControl(c);
System.err.print("["+c+"("+n+")"+t+"]");
}
*/
//System.err.println("File.separator " + File.separator);
//System.err.println("files[i].getName() " + files[i].getName());
//System.err.println("before calling xform");
- String temp = "file:///" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:");
+ String temp = "file://" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:");
//System.err.println("path is [" + temp); //files[i].getPath());
transformer.setParameter("subfilepath",temp); //files[i].getPath());
//System.out.println("fis");
FileInputStream fis = new FileInputStream(modelPath);
//System.out.println("fos");
FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName());
//System.out.println("fos");
try {
//transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName()));
transform(fis, fos);
//System.out.println("Fedora METS XML created at " + files[i].getName());
succeededBuildCount++;
//System.out.println("before keys.add()");
keys.add(files[i].getName());
//System.out.println("after keys.add()");
} catch (Exception e) {
//for now, follow processing as-is and throw out rest of batch
throw e;
} finally { // so that files are available to outside editor during batchtool client use
//System.out.println("before fis.close");
fis.close();
//System.out.println("before fos.close");
fos.close();
//System.out.println("after fos.close()");
}
}
}
} catch (Exception e) {
System.err.println("Fedora METS XML failed for " + file4catch.getName());
System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass());
failedBuildCount++;
} finally {
}
System.err.println("\n" + "Batch Build Summary");
System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch");
System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created");
System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed");
System.err.println("\t" + badFileCount + " unexpected files in directory");
System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error");
}
}
public static final void main(String[] args) {
try {
Properties miscProperties = new Properties();
miscProperties.load(new FileInputStream("c:\\batchdemo\\batchtool.properties"));
BatchXforms batchXforms = new BatchXforms(miscProperties);
batchXforms.prep();
batchXforms.process();
} catch (Exception e) {
}
}
public void transform(InputStream sourceStream, OutputStream destStream) throws TransformerException, TransformerConfigurationException {
//System.err.println("before transformer.transform()");
transformer.transform(new StreamSource(sourceStream), new StreamResult(destStream));
//System.err.println("after transformer.transform()");
}
}
| true | true | final void process() throws TransformerConfigurationException, Exception {
//System.err.println("before TransformerFactory.newInstance()"); //<<==
//System.err.println("xformPath=[" + xformPath + "]"); //<<==
//SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT
//System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<==
keys = new Vector();
if (good2go) {
int count = 0;
File file4catch = null;
int files4catch = 0;
int badFileCount = 0;
int succeededBuildCount = 0;
int failedBuildCount = 0;
try {
File[] files = null; {
// System.err.println("additions path " + additionsPath);
File additionsDirectory = new File(additionsPath);
files = additionsDirectory.listFiles();
}
//int badFileCount = 0;
files4catch = files.length;
for (int i = 0; i < files.length; i++) {
//System.err.println("another it");
file4catch = files[i];
if (! files[i].isFile()) {
badFileCount++;
System.err.println("additions directory contains unexpected directory or file: " + files[i].getName());
} else {
//System.err.println("before tfactory.newTransformer()"); //<<==
File f = new File(xformPath);
//System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]");
StreamSource ss = new StreamSource(f);
//System.err.println("ss null=[" + (ss == null) + "]");
/*
Reader r = ss.getReader();
System.err.println("r null=[" + (r == null) + "]");
BufferedReader br = new BufferedReader(r);
System.err.println("br null=[" + (br == null) + "]");
String st = br.readLine();
System.err.println("st null=[" + (st == null) + "]");
System.err.println("first line[" + st + "]");
System.err.println("after dummy SS"); //<<==
System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<==
*/
transformer = tfactory.newTransformer(ss); //xformPath
//System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null));
GregorianCalendar calendar = new GregorianCalendar();
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = leftPadded(1+ calendar.get(Calendar.MONTH),2);
String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2);
String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2);
String minute = leftPadded(calendar.get(Calendar.MINUTE),2);
String second = leftPadded(calendar.get(Calendar.SECOND),2);
transformer.setParameter("date",
year + "-" + month + "-" + dayOfMonth +
"T" + hourOfDay + ":" + minute + ":" + second);
//"2002-05-20T06:32:00"
//System.err.println("about to xform " + count++);
//System.err.println(">>>>>>>>>>>>" + files[i].getPath());
//System.err.println("objectsPath [" + objectsPath + "]");
/*
for (int bb=0; bb<objectsPath.length(); bb++) {
char c = objectsPath.charAt(bb);
int n = Character.getNumericValue(c);
boolean t = Character.isISOControl(c);
System.err.print("["+c+"("+n+")"+t+"]");
}
*/
//System.err.println("File.separator " + File.separator);
//System.err.println("files[i].getName() " + files[i].getName());
//System.err.println("before calling xform");
String temp = "file:///" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:");
//System.err.println("path is [" + temp); //files[i].getPath());
transformer.setParameter("subfilepath",temp); //files[i].getPath());
//System.out.println("fis");
FileInputStream fis = new FileInputStream(modelPath);
//System.out.println("fos");
FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName());
//System.out.println("fos");
try {
//transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName()));
transform(fis, fos);
//System.out.println("Fedora METS XML created at " + files[i].getName());
succeededBuildCount++;
//System.out.println("before keys.add()");
keys.add(files[i].getName());
//System.out.println("after keys.add()");
} catch (Exception e) {
//for now, follow processing as-is and throw out rest of batch
throw e;
} finally { // so that files are available to outside editor during batchtool client use
//System.out.println("before fis.close");
fis.close();
//System.out.println("before fos.close");
fos.close();
//System.out.println("after fos.close()");
}
}
}
} catch (Exception e) {
System.err.println("Fedora METS XML failed for " + file4catch.getName());
System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass());
failedBuildCount++;
} finally {
}
System.err.println("\n" + "Batch Build Summary");
System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch");
System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created");
System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed");
System.err.println("\t" + badFileCount + " unexpected files in directory");
System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error");
}
}
| final void process() throws TransformerConfigurationException, Exception {
//System.err.println("before TransformerFactory.newInstance()"); //<<==
//System.err.println("xformPath=[" + xformPath + "]"); //<<==
//SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT
//System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<==
keys = new Vector();
if (good2go) {
int count = 0;
File file4catch = null;
int files4catch = 0;
int badFileCount = 0;
int succeededBuildCount = 0;
int failedBuildCount = 0;
try {
File[] files = null; {
// System.err.println("additions path " + additionsPath);
File additionsDirectory = new File(additionsPath);
files = additionsDirectory.listFiles();
}
//int badFileCount = 0;
files4catch = files.length;
for (int i = 0; i < files.length; i++) {
//System.err.println("another it");
file4catch = files[i];
if (! files[i].isFile()) {
badFileCount++;
System.err.println("additions directory contains unexpected directory or file: " + files[i].getName());
} else {
//System.err.println("before tfactory.newTransformer()"); //<<==
File f = new File(xformPath);
//System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]");
StreamSource ss = new StreamSource(f);
//System.err.println("ss null=[" + (ss == null) + "]");
/*
Reader r = ss.getReader();
System.err.println("r null=[" + (r == null) + "]");
BufferedReader br = new BufferedReader(r);
System.err.println("br null=[" + (br == null) + "]");
String st = br.readLine();
System.err.println("st null=[" + (st == null) + "]");
System.err.println("first line[" + st + "]");
System.err.println("after dummy SS"); //<<==
System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<==
*/
transformer = tfactory.newTransformer(ss); //xformPath
//System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null));
GregorianCalendar calendar = new GregorianCalendar();
String year = Integer.toString(calendar.get(Calendar.YEAR));
String month = leftPadded(1+ calendar.get(Calendar.MONTH),2);
String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2);
String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2);
String minute = leftPadded(calendar.get(Calendar.MINUTE),2);
String second = leftPadded(calendar.get(Calendar.SECOND),2);
transformer.setParameter("date",
year + "-" + month + "-" + dayOfMonth +
"T" + hourOfDay + ":" + minute + ":" + second);
//"2002-05-20T06:32:00"
//System.err.println("about to xform " + count++);
//System.err.println(">>>>>>>>>>>>" + files[i].getPath());
//System.err.println("objectsPath [" + objectsPath + "]");
/*
for (int bb=0; bb<objectsPath.length(); bb++) {
char c = objectsPath.charAt(bb);
int n = Character.getNumericValue(c);
boolean t = Character.isISOControl(c);
System.err.print("["+c+"("+n+")"+t+"]");
}
*/
//System.err.println("File.separator " + File.separator);
//System.err.println("files[i].getName() " + files[i].getName());
//System.err.println("before calling xform");
String temp = "file://" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:");
//System.err.println("path is [" + temp); //files[i].getPath());
transformer.setParameter("subfilepath",temp); //files[i].getPath());
//System.out.println("fis");
FileInputStream fis = new FileInputStream(modelPath);
//System.out.println("fos");
FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName());
//System.out.println("fos");
try {
//transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName()));
transform(fis, fos);
//System.out.println("Fedora METS XML created at " + files[i].getName());
succeededBuildCount++;
//System.out.println("before keys.add()");
keys.add(files[i].getName());
//System.out.println("after keys.add()");
} catch (Exception e) {
//for now, follow processing as-is and throw out rest of batch
throw e;
} finally { // so that files are available to outside editor during batchtool client use
//System.out.println("before fis.close");
fis.close();
//System.out.println("before fos.close");
fos.close();
//System.out.println("after fos.close()");
}
}
}
} catch (Exception e) {
System.err.println("Fedora METS XML failed for " + file4catch.getName());
System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass());
failedBuildCount++;
} finally {
}
System.err.println("\n" + "Batch Build Summary");
System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch");
System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created");
System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed");
System.err.println("\t" + badFileCount + " unexpected files in directory");
System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error");
}
}
|
diff --git a/src/jcube/manager/filter/InitialDataInsert.java b/src/jcube/manager/filter/InitialDataInsert.java
index d3bd602..af7afa2 100644
--- a/src/jcube/manager/filter/InitialDataInsert.java
+++ b/src/jcube/manager/filter/InitialDataInsert.java
@@ -1,78 +1,78 @@
package jcube.manager.filter;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import manager.model.News;
import manager.model.NewsStatus;
import jcube.activerecord.fieldtypes.DateTime;
import jcube.core.filter.JcubeChainFilterElement;
import jcube.core.server.Environ;
// TODO: Auto-generated Javadoc
/**
* The Class InitialDataInsert.
*/
public class InitialDataInsert extends JcubeChainFilterElement
{
/**
* Instantiates a new initial data insert.
*
* @param env
* the env
* @param properties
* the properties
* @throws Exception
* the exception
*/
public InitialDataInsert(Environ env, Properties properties) throws Exception
{
File file = new File("../.inited");
System.out.println("inside filer");
- if (file.exists())
+ if (!file.exists())
{
// Generate statuses
NewsStatus open_status = new NewsStatus();
open_status.title = "Open";
open_status.save();
NewsStatus closed_status = new NewsStatus();
closed_status.title = "Closed";
closed_status.save();
NewsStatus moderate_status = new NewsStatus();
moderate_status.title = "Verifying";
moderate_status.save();
NewsStatus archived_status = new NewsStatus();
archived_status.title = "Archived";
archived_status.save();
ArrayList<NewsStatus> statuses = new ArrayList<NewsStatus>();
statuses.add(open_status);
statuses.add(closed_status);
statuses.add(moderate_status);
statuses.add(archived_status);
for (int i = 0; i <= 200; i++)
{
News news = new News();
news.title = "Item " + i;
news.status = statuses.get((int) (Math.random() * statuses.size()));
DateTime date = new DateTime();
date.shift(Calendar.DATE, (int) (Math.random() * 30));
news.added_on = date;
news.published = ((int) (Math.random() * 2) == 0) ? false : true;
news.desc = "Item description " + i;
news.save();
}
- file.delete();
+ file.createNewFile();
}
}
}
| false | true | public InitialDataInsert(Environ env, Properties properties) throws Exception
{
File file = new File("../.inited");
System.out.println("inside filer");
if (file.exists())
{
// Generate statuses
NewsStatus open_status = new NewsStatus();
open_status.title = "Open";
open_status.save();
NewsStatus closed_status = new NewsStatus();
closed_status.title = "Closed";
closed_status.save();
NewsStatus moderate_status = new NewsStatus();
moderate_status.title = "Verifying";
moderate_status.save();
NewsStatus archived_status = new NewsStatus();
archived_status.title = "Archived";
archived_status.save();
ArrayList<NewsStatus> statuses = new ArrayList<NewsStatus>();
statuses.add(open_status);
statuses.add(closed_status);
statuses.add(moderate_status);
statuses.add(archived_status);
for (int i = 0; i <= 200; i++)
{
News news = new News();
news.title = "Item " + i;
news.status = statuses.get((int) (Math.random() * statuses.size()));
DateTime date = new DateTime();
date.shift(Calendar.DATE, (int) (Math.random() * 30));
news.added_on = date;
news.published = ((int) (Math.random() * 2) == 0) ? false : true;
news.desc = "Item description " + i;
news.save();
}
file.delete();
}
}
| public InitialDataInsert(Environ env, Properties properties) throws Exception
{
File file = new File("../.inited");
System.out.println("inside filer");
if (!file.exists())
{
// Generate statuses
NewsStatus open_status = new NewsStatus();
open_status.title = "Open";
open_status.save();
NewsStatus closed_status = new NewsStatus();
closed_status.title = "Closed";
closed_status.save();
NewsStatus moderate_status = new NewsStatus();
moderate_status.title = "Verifying";
moderate_status.save();
NewsStatus archived_status = new NewsStatus();
archived_status.title = "Archived";
archived_status.save();
ArrayList<NewsStatus> statuses = new ArrayList<NewsStatus>();
statuses.add(open_status);
statuses.add(closed_status);
statuses.add(moderate_status);
statuses.add(archived_status);
for (int i = 0; i <= 200; i++)
{
News news = new News();
news.title = "Item " + i;
news.status = statuses.get((int) (Math.random() * statuses.size()));
DateTime date = new DateTime();
date.shift(Calendar.DATE, (int) (Math.random() * 30));
news.added_on = date;
news.published = ((int) (Math.random() * 2) == 0) ? false : true;
news.desc = "Item description " + i;
news.save();
}
file.createNewFile();
}
}
|
diff --git a/src/main/java/net/pms/network/RequestV2.java b/src/main/java/net/pms/network/RequestV2.java
index 815c6a318..7c640278b 100644
--- a/src/main/java/net/pms/network/RequestV2.java
+++ b/src/main/java/net/pms/network/RequestV2.java
@@ -1,916 +1,916 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import net.pms.PMS;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.DLNAMediaInfo;
import net.pms.dlna.DLNAMediaSubtitle;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.Range;
import net.pms.external.StartStopListenerDelegate;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.stream.ChunkedStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class handles all forms of incoming HTTP requests by constructing a proper HTTP response.
*/
public class RequestV2 extends HTTPResource {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestV2.class);
private final static String CRLF = "\r\n";
private static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
private static int BUFFER_SIZE = 8 * 1024;
private static final int[] MULTIPLIER = new int[] { 1, 60, 3600, 24*3600};
private final String method;
/**
* A {@link String} that contains the argument with which this {@link RequestV2} was
* created. It contains a command, a unique resource id and a resource name, all
* separated by slashes. For example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or
* "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv"
*/
private String argument;
private String soapaction;
private String content;
private String objectID;
private int startingIndex;
private int requestCount;
private String browseFlag;
/**
* When sending an input stream, the lowRange indicates which byte to start from.
*/
private long lowRange;
private InputStream inputStream;
private RendererConfiguration mediaRenderer;
private String transferMode;
private String contentFeatures;
private final Range.Time range = new Range.Time();
/**
* When sending an input stream, the highRange indicates which byte to stop at.
*/
private long highRange;
private boolean http10;
public RendererConfiguration getMediaRenderer() {
return mediaRenderer;
}
public void setMediaRenderer(RendererConfiguration mediaRenderer) {
this.mediaRenderer = mediaRenderer;
}
public InputStream getInputStream() {
return inputStream;
}
/**
* When sending an input stream, the lowRange indicates which byte to start from.
* @return The byte to start from
*/
public long getLowRange() {
return lowRange;
}
/**
* Set the byte from which to start when sending an input stream. This value will
* be used to send a CONTENT_RANGE header with the response.
* @param lowRange The byte to start from.
*/
public void setLowRange(long lowRange) {
this.lowRange = lowRange;
}
public String getTransferMode() {
return transferMode;
}
public void setTransferMode(String transferMode) {
this.transferMode = transferMode;
}
public String getContentFeatures() {
return contentFeatures;
}
public void setContentFeatures(String contentFeatures) {
this.contentFeatures = contentFeatures;
}
public void setTimeRangeStart(Double timeseek) {
this.range.setStart(timeseek);
}
public void setTimeRangeStartString(String str) {
setTimeRangeStart(convertTime(str));
}
public void setTimeRangeEnd(Double rangeEnd) {
this.range.setEnd(rangeEnd);
}
public void setTimeRangeEndString(String str) {
setTimeRangeEnd(convertTime(str));
}
/**
* When sending an input stream, the highRange indicates which byte to stop at.
* @return The byte to stop at.
*/
public long getHighRange() {
return highRange;
}
/**
* Set the byte at which to stop when sending an input stream. This value will
* be used to send a CONTENT_RANGE header with the response.
* @param highRange The byte to stop at.
*/
public void setHighRange(long highRange) {
this.highRange = highRange;
}
public boolean isHttp10() {
return http10;
}
public void setHttp10(boolean http10) {
this.http10 = http10;
}
/**
* This class will construct and transmit a proper HTTP response to a given HTTP request.
* Rewritten version of the {@link Request} class.
* @param method The {@link String} that defines the HTTP method to be used.
* @param argument The {@link String} containing instructions for PMS. It contains a command,
* a unique resource id and a resource name, all separated by slashes.
*/
public RequestV2(String method, String argument) {
this.method = method;
this.argument = argument;
}
public String getSoapaction() {
return soapaction;
}
public void setSoapaction(String soapaction) {
this.soapaction = soapaction;
}
public String getTextContent() {
return content;
}
public void setTextContent(String content) {
this.content = content;
}
/**
* Retrieves the HTTP method with which this {@link RequestV2} was created.
* @return The (@link String} containing the HTTP method.
*/
public String getMethod() {
return method;
}
/**
* Retrieves the argument with which this {@link RequestV2} was created. It contains
* a command, a unique resource id and a resource name, all separated by slashes. For
* example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv"
* @return The {@link String} containing the argument.
*/
public String getArgument() {
return argument;
}
/**
* Construct a proper HTTP response to a received request. After the response has been
* created, it is sent and the resulting {@link ChannelFuture} object is returned.
* See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC-2616</a>
* for HTTP header field definitions.
* @param output The {@link HttpResponse} object that will be used to construct the response.
* @param e The {@link MessageEvent} object used to communicate with the client that sent
* the request.
* @param close Set to true to close the channel after sending the response. By default the
* channel is not closed after sending.
* @param startStopListenerDelegate The {@link StartStopListenerDelegate} object that is used
* to notify plugins that the {@link DLNAResource} is about to start playing.
* @return The {@link ChannelFuture} object via which the response was sent.
* @throws IOException
*/
public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTLM console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// Extract the resource id from the argument string.
String id = argument.substring(argument.indexOf("get/") + 4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request, unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
- // DNLAresource was found.
+ // DLNAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
inputStream = new java.io.FileInputStream(sub.getFile());
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
int type = sub.getType();
if (type < DLNAMediaSubtitle.subExtensions.length) {
String strType = DLNAMediaSubtitle.subExtensions[type - 1];
String subtitleUrl = "http://" + PMS.get().getServer().getHost()
+ ':' + PMS.get().getServer().getPort() + "/get/"
+ id + "/subtitle0000." + strType;
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
final DLNAMediaInfo media = dlna.getMedia();
if (media != null) {
if (StringUtils.isNotBlank(media.getContainer())) {
name += " [container: " + media.getContainer() + "]";
}
if (StringUtils.isNotBlank(media.getCodecV())) {
name += " [video: " + media.getCodecV() + "]";
}
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-"
+ (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn());//.substring(0, PMS.get().usn().length()-2));
String profileName = PMS.getConfiguration().getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF
+ "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF
+ "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF
+ "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF
+ "<controlURL>/upnp/mrr/control</controlURL>" + CRLF
+ "</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-256.png", "/images/thumbnail-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>" + DLNAResource.getSystemUpdateId() + "</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search")) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0) && xbox) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
if (!containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && PMS.getConfiguration().getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer);
if (searchCriteria != null && files != null) {
for (int i = files.size() - 1; i >= 0; i--) {
if (!files.get(i).getName().equals(searchCriteria)) {
files.remove(i);
}
}
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
String cb = soapaction.replace("<", "").replace(">", "");
String faddr = cb.replace("http://", "").replace("/", "");
String addr = faddr.split(":")[0];
int port = Integer.parseInt(faddr.split(":")[1]);
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + faddr).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
/**
* Returns a date somewhere in the far future.
* @return The {@link String} containing the date
*/
private String getFUTUREDATE() {
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(new Date(10000000000L + System.currentTimeMillis()));
}
/**
* Returns the string value that is enclosed by the left and right tag in a content string.
* Only the first match of each tag is used to determine positions. If either of the tags
* cannot be found, null is returned.
* @param content The entire {@link String} that needs to be searched for the left and right tag.
* @param leftTag The {@link String} determining the match for the left tag.
* @param rightTag The {@link String} determining the match for the right tag.
* @return The {@link String} that was enclosed by the left and right tag.
*/
private String getEnclosingValue(String content, String leftTag, String rightTag) {
String result = null;
int leftTagPos = content.indexOf(leftTag);
int rightTagPos = content.indexOf(rightTag, leftTagPos + 1);
if (leftTagPos > -1 && rightTagPos > leftTagPos) {
result = content.substring(leftTagPos + leftTag.length(), rightTagPos);
}
return result;
}
/**
* Parse as double, or if it's not just one number, handles {hour}:{minute}:{seconds}
* @param time
* @return
*/
private double convertTime(String time) {
try {
return Double.parseDouble(time);
} catch (NumberFormatException e) {
String[] arrs = time.split(":");
double value, sum = 0;
for (int i = 0; i < arrs.length; i++) {
value = Double.parseDouble(arrs[arrs.length - i - 1]);
sum += value * MULTIPLIER[i];
}
return sum;
}
}
}
| true | true | public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTLM console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// Extract the resource id from the argument string.
String id = argument.substring(argument.indexOf("get/") + 4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request, unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
// DNLAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
inputStream = new java.io.FileInputStream(sub.getFile());
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
int type = sub.getType();
if (type < DLNAMediaSubtitle.subExtensions.length) {
String strType = DLNAMediaSubtitle.subExtensions[type - 1];
String subtitleUrl = "http://" + PMS.get().getServer().getHost()
+ ':' + PMS.get().getServer().getPort() + "/get/"
+ id + "/subtitle0000." + strType;
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
final DLNAMediaInfo media = dlna.getMedia();
if (media != null) {
if (StringUtils.isNotBlank(media.getContainer())) {
name += " [container: " + media.getContainer() + "]";
}
if (StringUtils.isNotBlank(media.getCodecV())) {
name += " [video: " + media.getCodecV() + "]";
}
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-"
+ (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn());//.substring(0, PMS.get().usn().length()-2));
String profileName = PMS.getConfiguration().getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF
+ "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF
+ "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF
+ "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF
+ "<controlURL>/upnp/mrr/control</controlURL>" + CRLF
+ "</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-256.png", "/images/thumbnail-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>" + DLNAResource.getSystemUpdateId() + "</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search")) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0) && xbox) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
if (!containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && PMS.getConfiguration().getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer);
if (searchCriteria != null && files != null) {
for (int i = files.size() - 1; i >= 0; i--) {
if (!files.get(i).getName().equals(searchCriteria)) {
files.remove(i);
}
}
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
String cb = soapaction.replace("<", "").replace(">", "");
String faddr = cb.replace("http://", "").replace("/", "");
String addr = faddr.split(":")[0];
int port = Integer.parseInt(faddr.split(":")[1]);
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + faddr).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
| public ChannelFuture answer(
HttpResponse output,
MessageEvent e,
final boolean close,
final StartStopListenerDelegate startStopListenerDelegate) throws IOException {
ChannelFuture future = null;
long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
StringBuilder response = new StringBuilder();
DLNAResource dlna = null;
boolean xbox = mediaRenderer.isXBOX();
// Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
if (argument.startsWith("/")) {
LOGGER.trace("Stripping preceding slash from: " + argument);
argument = argument.substring(1);
}
if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
// Request to output a page to the HTLM console.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
response.append(HTMLConsole.servePage(argument.substring(8)));
} else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
// Request to retrieve a file
// Extract the resource id from the argument string.
String id = argument.substring(argument.indexOf("get/") + 4, argument.lastIndexOf("/"));
// Some clients escape the separators in their request, unescape them.
id = id.replace("%24", "$");
// Retrieve the DLNAresource itself.
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer);
if (transferMode != null) {
output.setHeader("TransferMode.DLNA.ORG", transferMode);
}
if (files.size() == 1) {
// DLNAresource was found.
dlna = files.get(0);
String fileName = argument.substring(argument.lastIndexOf("/") + 1);
if (fileName.startsWith("thumbnail0000")) {
// This is a request for a thumbnail file.
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
if (mediaRenderer.isMediaParserV2()) {
dlna.checkThumbnail();
}
inputStream = dlna.getThumbnailInputStream();
} else if (fileName.indexOf("subtitle0000") > -1) {
// This is a request for a subtitle file
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
// TODO: maybe loop subs to get the requested subtitle type instead of using the first one
DLNAMediaSubtitle sub = subs.get(0);
inputStream = new java.io.FileInputStream(sub.getFile());
}
} else {
// This is a request for a regular file.
// If range has not been initialized yet and the DLNAResource has its
// own start and end defined, initialize range with those values before
// requesting the input stream.
Range.Time splitRange = dlna.getSplitRange();
if (range.getStart() == null && splitRange.getStart() != null) {
range.setStart(splitRange.getStart());
}
if (range.getEnd() == null && splitRange.getEnd() != null) {
range.setEnd(splitRange.getEnd());
}
inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);
// Some renderers (like Samsung devices) allow a custom header for a subtitle URL
String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();
if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
// Device allows a custom subtitle HTTP header; construct it
List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitlesCodes();
if (subs != null && !subs.isEmpty()) {
DLNAMediaSubtitle sub = subs.get(0);
int type = sub.getType();
if (type < DLNAMediaSubtitle.subExtensions.length) {
String strType = DLNAMediaSubtitle.subExtensions[type - 1];
String subtitleUrl = "http://" + PMS.get().getServer().getHost()
+ ':' + PMS.get().getServer().getPort() + "/get/"
+ id + "/subtitle0000." + strType;
output.setHeader(subtitleHttpHeader, subtitleUrl);
}
}
}
String name = dlna.getDisplayName(mediaRenderer);
if (inputStream == null) {
// No inputStream indicates that transcoding / remuxing probably crashed.
LOGGER.error("There is no inputstream to return for " + name);
} else {
// Notify plugins that the DLNAresource is about to start playing
startStopListenerDelegate.start(dlna);
// Try to determine the content type of the file
String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);
if (rendererMimeType != null && !"".equals(rendererMimeType)) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
}
final DLNAMediaInfo media = dlna.getMedia();
if (media != null) {
if (StringUtils.isNotBlank(media.getContainer())) {
name += " [container: " + media.getContainer() + "]";
}
if (StringUtils.isNotBlank(media.getCodecV())) {
name += " [video: " + media.getCodecV() + "]";
}
}
PMS.get().getFrame().setStatusLine("Serving " + name);
// Response generation:
// We use -1 for arithmetic convenience but don't send it as a value.
// If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.
boolean chunked = mediaRenderer.isChunkedTransfer();
// Determine the total size. Note: when transcoding the length is
// not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.
long totalsize = dlna.length(mediaRenderer);
if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
// In chunked mode we try to avoid arbitrary values.
totalsize = -1;
}
long remaining = totalsize - lowRange;
long requested = highRange - lowRange;
if (requested != 0) {
// Determine the range (i.e. smaller of known or requested bytes)
long bytes = remaining > -1 ? remaining : inputStream.available();
if (requested > 0 && bytes > requested) {
bytes = requested + 1;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);
LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");
output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-"
+ (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*"));
// Content-Length refers to the current chunk size here, though in chunked
// mode if the request is open-ended and totalsize is unknown we omit it.
if (chunked && requested < 0 && totalsize < 0) {
CLoverride = -1;
} else {
CLoverride = bytes;
}
} else {
// Content-Length refers to the total remaining size of the stream here.
CLoverride = remaining;
}
// Calculate the corresponding highRange (this is usually redundant).
highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);
if (contentFeatures != null) {
output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
}
}
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
if (argument.toLowerCase().endsWith(".png")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
} else {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
}
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
inputStream = getResourceInputStream(argument);
} else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
output.setHeader(HttpHeaders.Names.EXPIRES, "0");
output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));
if (argument.equals("description/fetch")) {
byte b[] = new byte[inputStream.available()];
inputStream.read(b);
String s = new String(b);
s = s.replace("[uuid]", PMS.get().usn());//.substring(0, PMS.get().usn().length()-2));
String profileName = PMS.getConfiguration().getProfileName();
if (PMS.get().getServer().getHost() != null) {
s = s.replace("[host]", PMS.get().getServer().getHost());
s = s.replace("[port]", "" + PMS.get().getServer().getPort());
}
if (xbox) {
LOGGER.debug("DLNA changes for Xbox 360");
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect");
s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>");
s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF
+ "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF
+ "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF
+ "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF
+ "<controlURL>/upnp/mrr/control</controlURL>" + CRLF
+ "</service>" + CRLF);
} else {
s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]");
}
if (!mediaRenderer.isPS3()) {
// hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
// really need a proper format compatibility list by renderer
s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
s = s.replace("/images/thumbnail-256.png", "/images/thumbnail-120.jpg");
s = s.replace(">256<", ">120<");
}
response.append(s);
inputStream = null;
}
} else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction != null && soapaction.contains("IsAuthorized")) {
response.append(HTTPXMLHelper.XBOX_2);
response.append(CRLF);
} else if (soapaction != null && soapaction.contains("IsValidated")) {
response.append(HTTPXMLHelper.XBOX_1);
response.append(CRLF);
}
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
}
} else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
if (soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
response.append(CRLF);
response.append("<Id>" + DLNAResource.getSystemUpdateId() + "</Id>");
response.append(CRLF);
response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
} else if (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search")) {
objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
String containerID = null;
if ((objectID == null || objectID.length() == 0) && xbox) {
containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
if (!containerID.contains("$")) {
objectID = "0";
} else {
objectID = containerID;
containerID = null;
}
}
Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");
if (sI != null) {
startingIndex = Integer.parseInt(sI.toString());
}
if (rC != null) {
requestCount = Integer.parseInt(rC.toString());
}
response.append(HTTPXMLHelper.XML_HEADER);
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.RESULT_HEADER);
response.append(HTTPXMLHelper.DIDL_HEADER);
if (soapaction.contains("ContentDirectory:1#Search")) {
browseFlag = "BrowseDirectChildren";
}
// XBOX virtual containers ... d'oh!
String searchCriteria = null;
if (xbox && PMS.getConfiguration().getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
} else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
} else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
} else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
} else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
} else if (containerID.equals("1")) {
String artist = getEnclosingValue(content, "upnp:artist = "", "")");
if (artist != null) {
objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
searchCriteria = artist;
}
}
}
List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer);
if (searchCriteria != null && files != null) {
for (int i = files.size() - 1; i >= 0; i--) {
if (!files.get(i).getName().equals(searchCriteria)) {
files.remove(i);
}
}
if (files.size() > 0) {
files = files.get(0).getChildren();
}
}
int minus = 0;
if (files != null) {
for (DLNAResource uf : files) {
if (xbox && containerID != null) {
uf.setFakeParentId(containerID);
}
if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
response.append(uf.toString(mediaRenderer));
} else {
minus++;
}
}
}
response.append(HTTPXMLHelper.DIDL_FOOTER);
response.append(HTTPXMLHelper.RESULT_FOOTER);
response.append(CRLF);
int filessize = 0;
if (files != null) {
filessize = files.size();
}
response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
response.append(CRLF);
DLNAResource parentFolder = null;
if (files != null && filessize > 0) {
parentFolder = files.get(0).getParent();
}
if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
// with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
// every 10 items (the ps3 asks 10 by 10),
// so we do not know exactly the total number of items in the DLNA folder to send
// (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
// invalidated and hidden if format is broken or encrypted, etc.).
// let's send a fake total size to force the renderer to ask following items
int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
if (filessize - minus <= 0) // if no more elements, send the startingIndex
{
totalCount = startingIndex;
}
response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
} else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>");
} else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
response.append("<TotalMatches>1</TotalMatches>");
}
response.append(CRLF);
response.append("<UpdateID>");
if (parentFolder != null) {
response.append(parentFolder.getUpdateId());
} else {
response.append("1");
}
response.append("</UpdateID>");
response.append(CRLF);
if (soapaction.contains("ContentDirectory:1#Search")) {
response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
} else {
response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
}
response.append(CRLF);
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
response.append(CRLF);
// LOGGER.trace(response.toString());
}
} else if (method.equals("SUBSCRIBE")) {
output.setHeader("SID", PMS.get().usn());
output.setHeader("TIMEOUT", "Second-1800");
String cb = soapaction.replace("<", "").replace(">", "");
String faddr = cb.replace("http://", "").replace("/", "");
String addr = faddr.split(":")[0];
int port = Integer.parseInt(faddr.split(":")[1]);
Socket sock = new Socket(addr,port);
OutputStream out = sock.getOutputStream();
out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
out.write(CRLF.getBytes());
out.write(("SID: " + PMS.get().usn()).getBytes());
out.write(CRLF.getBytes());
out.write(("SEQ: " + 0).getBytes());
out.write(CRLF.getBytes());
out.write(("NT: upnp:event").getBytes());
out.write(CRLF.getBytes());
out.write(("NTS: upnp:propchange").getBytes());
out.write(CRLF.getBytes());
out.write(("HOST: " + faddr).getBytes());
out.write(CRLF.getBytes());
out.flush();
out.close();
if (argument.contains("connection_manager")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
response.append(HTTPXMLHelper.EVENT_FOOTER);
} else if (argument.contains("content_directory")) {
response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
response.append(HTTPXMLHelper.eventProp("TransferIDs"));
response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
response.append(HTTPXMLHelper.EVENT_FOOTER);
}
} else if (method.equals("NOTIFY")) {
output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
output.setHeader("NT", "upnp:event");
output.setHeader("NTS", "upnp:propchange");
output.setHeader("SID", PMS.get().usn());
output.setHeader("SEQ", "0");
response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
response.append("<e:property>");
response.append("<TransferIDs></TransferIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
response.append("</e:property>");
response.append("<e:property>");
response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>");
response.append("</e:property>");
response.append("</e:propertyset>");
}
output.setHeader("Server", PMS.get().getServerName());
if (response.length() > 0) {
// A response message was constructed; convert it to data ready to be sent.
byte responseData[] = response.toString().getBytes("UTF-8");
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);
// HEAD requests only require headers to be set, no need to set contents.
if (!method.equals("HEAD")) {
// Not a HEAD request, so set the contents of the response.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
output.setContent(buf);
}
// Send the response to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
} else if (inputStream != null) {
// There is an input stream to send as a response.
if (CLoverride > -2) {
// Content-Length override has been set, send or omit as appropriate
if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
// Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
// as the PS3 will display a network error and request the last seconds of the
// transcoded video. Better to send no Content-Length at all.
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
}
} else {
int cl = inputStream.available();
LOGGER.trace("Available Content-Length: " + cl);
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
}
if (range.isStartOffsetAvailable() && dlna != null) {
// Add timeseek information headers.
String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
String timetotalValue = dlna.getMedia().getDurationString();
String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue;
output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
// Send the response body to the client in chunks.
ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));
// Add a listener to clean up after sending the entire response body.
chunkWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
// Always close the channel after the response is sent because of
// a freeze at the end of video when the channel is not closed.
future.getChannel().close();
startStopListenerDelegate.stop();
}
});
} else {
// HEAD method is being used, so simply clean up after the response was sent.
try {
PMS.get().getRegistry().reenableGoToSleep();
inputStream.close();
} catch (IOException ioe) {
LOGGER.debug("Caught exception", ioe);
}
if (close) {
// Close the channel after the response is sent
future.addListener(ChannelFutureListener.CLOSE);
}
startStopListenerDelegate.stop();
}
} else {
// No response data and no input stream. Seems we are merely serving up headers.
if (lowRange > 0 && highRange > 0) {
// FIXME: There is no content, so why set a length?
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
} else {
output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
}
// Send the response headers to the client.
future = e.getChannel().write(output);
if (close) {
// Close the channel after the response is sent.
future.addListener(ChannelFutureListener.CLOSE);
}
}
// Log trace information
Iterator<String> it = output.getHeaderNames().iterator();
while (it.hasNext()) {
String headerName = it.next();
LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
}
return future;
}
|
diff --git a/codegen/src/main/java/org/exolab/castor/builder/TypeConversion.java b/codegen/src/main/java/org/exolab/castor/builder/TypeConversion.java
index ade3c6d1..3f60cfc9 100644
--- a/codegen/src/main/java/org/exolab/castor/builder/TypeConversion.java
+++ b/codegen/src/main/java/org/exolab/castor/builder/TypeConversion.java
@@ -1,670 +1,671 @@
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2002 (C) Intalio Inc. All Rights Reserved.
*
* $Id$
*/
package org.exolab.castor.builder;
import java.util.Enumeration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.builder.types.XSAnyURI;
import org.exolab.castor.builder.types.XSBase64Binary;
import org.exolab.castor.builder.types.XSBoolean;
import org.exolab.castor.builder.types.XSByte;
import org.exolab.castor.builder.types.XSClass;
import org.exolab.castor.builder.types.XSDate;
import org.exolab.castor.builder.types.XSDateTime;
import org.exolab.castor.builder.types.XSDecimal;
import org.exolab.castor.builder.types.XSDouble;
import org.exolab.castor.builder.types.XSDuration;
import org.exolab.castor.builder.types.XSFloat;
import org.exolab.castor.builder.types.XSGDay;
import org.exolab.castor.builder.types.XSGMonth;
import org.exolab.castor.builder.types.XSGMonthDay;
import org.exolab.castor.builder.types.XSGYear;
import org.exolab.castor.builder.types.XSGYearMonth;
import org.exolab.castor.builder.types.XSHexBinary;
import org.exolab.castor.builder.types.XSId;
import org.exolab.castor.builder.types.XSIdRef;
import org.exolab.castor.builder.types.XSIdRefs;
import org.exolab.castor.builder.types.XSInt;
import org.exolab.castor.builder.types.XSInteger;
import org.exolab.castor.builder.types.XSLong;
import org.exolab.castor.builder.types.XSNCName;
import org.exolab.castor.builder.types.XSNMToken;
import org.exolab.castor.builder.types.XSNMTokens;
import org.exolab.castor.builder.types.XSNegativeInteger;
import org.exolab.castor.builder.types.XSNonNegativeInteger;
import org.exolab.castor.builder.types.XSNonPositiveInteger;
import org.exolab.castor.builder.types.XSNormalizedString;
import org.exolab.castor.builder.types.XSPositiveInteger;
import org.exolab.castor.builder.types.XSQName;
import org.exolab.castor.builder.types.XSShort;
import org.exolab.castor.builder.types.XSString;
import org.exolab.castor.builder.types.XSTime;
import org.exolab.castor.builder.types.XSType;
import org.exolab.castor.builder.types.XSUnsignedByte;
import org.exolab.castor.builder.types.XSUnsignedInt;
import org.exolab.castor.builder.types.XSUnsignedLong;
import org.exolab.castor.builder.types.XSUnsignedShort;
import org.exolab.castor.xml.JavaNaming;
import org.exolab.castor.xml.schema.AttributeDecl;
import org.exolab.castor.xml.schema.ElementDecl;
import org.exolab.castor.xml.schema.Facet;
import org.exolab.castor.xml.schema.Schema;
import org.exolab.castor.xml.schema.SimpleType;
import org.exolab.castor.xml.schema.SimpleTypesFactory;
import org.exolab.castor.xml.schema.Structure;
import org.exolab.castor.xml.schema.Union;
import org.exolab.javasource.JClass;
import org.exolab.javasource.JType;
/**
* A class used to convert XML Schema SimpleTypes into the appropriate XSType.
* @author <a href="mailto:[email protected]">Keith Visco</a>
* @author <a href="mailto:[email protected]">Arnaud Blandin</a>
* @version $Revision$ $Date: 2006-01-21 04:43:28 -0700 (Sat, 21 Jan 2006) $
*/
public final class TypeConversion {
/** Jakarta's common-logging logger. */
private static final Log LOG = LogFactory.getLog(TypeConversion.class);
/** Configuration for our source generator. */
private final BuilderConfiguration _config;
/**
* Creates a new TypeConversion instance.
*
* @param config the BuilderConfiguration instance (must not be null).
*/
public TypeConversion(final BuilderConfiguration config) {
if (config == null) {
String error = "The argument 'config' must not be null.";
throw new IllegalArgumentException(error);
}
_config = config;
} //-- TypeConversion
/**
* Converts the given Simpletype to the appropriate XSType.
*
* @param simpleType the SimpleType to convert to an XSType instance
* @param useJava50 true if source code is to be generated for Java 5
* @return the XSType which represets the given Simpletype
*/
public XSType convertType(final SimpleType simpleType, final boolean useJava50) {
return convertType(simpleType, null, useJava50);
}
/**
* Converts the given Simpletype to the appropriate XSType.
*
* @param simpleType the SimpleType to convert to an XSType instance
* @param packageName the packageName for any new class types
* @param useJava50 true if source code is to be generated for Java 5
* @return the XSType which represets the given Simpletype
*/
public XSType convertType(final SimpleType simpleType, final String packageName,
final boolean useJava50) {
return convertType(simpleType, packageName, _config.usePrimitiveWrapper(), useJava50);
}
/**
* Converts the given Simpletype to the appropriate XSType.
*
* @param simpleType the SimpleType to convert to an XSType instance
* @param packageName the packageName for any new class types
* @param useWrapper a boolean that when true indicates that primitive
* wrappers be used instead of the actual primitives (e.g.
* java.lang.Integer instead of int)
* @param useJava50 true if source code is to be generated for Java 5
* @return the XSType which represets the given Simpletype
*/
public XSType convertType(final SimpleType simpleType, final String packageName,
final boolean useWrapper, final boolean useJava50) {
if (simpleType == null) {
return null;
}
XSType xsType = null;
//-- determine base type
SimpleType base = simpleType;
while ((base != null) && (!base.isBuiltInType())) {
base = (SimpleType) base.getBaseType();
}
// try to find a common type for UNIONs, and use it; if not,
// use 'java.lang.Object' instead.
if (simpleType.getStructureType() == Structure.UNION) {
SimpleType currentUnion = simpleType;
SimpleType common = findCommonType((Union) currentUnion);
// look at type hierarchy (if any), and try to
// find a common type recursively
while (common == null
+ && currentUnion.getBaseType() != null
&& currentUnion.getBaseType().getStructureType() == Structure.UNION)
{
currentUnion = (SimpleType) currentUnion.getBaseType();
common = findCommonType((Union) currentUnion);
}
if (common == null) {
return new XSClass(SGTypes.OBJECT);
}
return convertType(common, packageName, useWrapper, useJava50);
} else if (base == null) {
String className = JavaNaming.toJavaClassName(simpleType.getName());
return new XSClass(new JClass(className));
}
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType != null) {
return xsType;
}
// If we don't have the XSType yet, we have to look at the Type Code
switch (base.getTypeCode()) {
case SimpleTypesFactory.ID_TYPE: //-- ID
return new XSId();
case SimpleTypesFactory.IDREF_TYPE: //-- IDREF
return new XSIdRef();
case SimpleTypesFactory.IDREFS_TYPE: //-- IDREFS
return new XSIdRefs(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.NMTOKEN_TYPE: //-- NMTOKEN
XSNMToken xsNMToken = new XSNMToken();
xsNMToken.setFacets(simpleType);
return xsNMToken;
case SimpleTypesFactory.NMTOKENS_TYPE: //-- NMTOKENS
return new XSNMTokens(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.ANYURI_TYPE: //--AnyURI
return new XSAnyURI();
case SimpleTypesFactory.BASE64BINARY_TYPE: //-- base64Bbinary
return new XSBase64Binary(useJava50);
case SimpleTypesFactory.HEXBINARY_TYPE: //-- hexBinary
return new XSHexBinary(useJava50);
case SimpleTypesFactory.BOOLEAN_TYPE: //-- boolean
return new XSBoolean(useWrapper);
case SimpleTypesFactory.BYTE_TYPE: //--byte
XSByte xsByte = new XSByte(useWrapper);
if (!simpleType.isBuiltInType()) {
xsByte.setFacets(simpleType);
}
return xsByte;
case SimpleTypesFactory.DATE_TYPE: //-- date
XSDate xsDate = new XSDate();
if (!simpleType.isBuiltInType()) {
xsDate.setFacets(simpleType);
}
return xsDate;
case SimpleTypesFactory.DATETIME_TYPE: //-- dateTime
XSDateTime xsDateTime = new XSDateTime();
if (!simpleType.isBuiltInType()) {
xsDateTime.setFacets(simpleType);
}
return xsDateTime;
case SimpleTypesFactory.DOUBLE_TYPE: //-- double
XSDouble xsDouble = new XSDouble(useWrapper);
if (!simpleType.isBuiltInType()) {
xsDouble.setFacets(simpleType);
}
return xsDouble;
case SimpleTypesFactory.DURATION_TYPE: //-- duration
XSDuration xsDuration = new XSDuration();
if (!simpleType.isBuiltInType()) {
xsDuration.setFacets(simpleType);
}
return xsDuration;
case SimpleTypesFactory.DECIMAL_TYPE: //-- decimal
XSDecimal xsDecimal = new XSDecimal();
if (!simpleType.isBuiltInType()) {
xsDecimal.setFacets(simpleType);
}
return xsDecimal;
case SimpleTypesFactory.FLOAT_TYPE: //-- float
XSFloat xsFloat = new XSFloat(useWrapper);
if (!simpleType.isBuiltInType()) {
xsFloat.setFacets(simpleType);
}
return xsFloat;
case SimpleTypesFactory.GDAY_TYPE: //--GDay
XSGDay xsGDay = new XSGDay();
if (!simpleType.isBuiltInType()) {
xsGDay.setFacets(simpleType);
}
return xsGDay;
case SimpleTypesFactory.GMONTHDAY_TYPE: //--GMonthDay
XSGMonthDay xsGMonthDay = new XSGMonthDay();
if (!simpleType.isBuiltInType()) {
xsGMonthDay.setFacets(simpleType);
}
return xsGMonthDay;
case SimpleTypesFactory.GMONTH_TYPE: //--GMonth
XSGMonth xsGMonth = new XSGMonth();
if (!simpleType.isBuiltInType()) {
xsGMonth.setFacets(simpleType);
}
return xsGMonth;
case SimpleTypesFactory.GYEARMONTH_TYPE: //--GYearMonth
XSGYearMonth xsGYearMonth = new XSGYearMonth();
if (!simpleType.isBuiltInType()) {
xsGYearMonth.setFacets(simpleType);
}
return xsGYearMonth;
case SimpleTypesFactory.GYEAR_TYPE: //--GYear
XSGYear xsGYear = new XSGYear();
if (!simpleType.isBuiltInType()) {
xsGYear.setFacets(simpleType);
}
return xsGYear;
case SimpleTypesFactory.INTEGER_TYPE: //-- integer
XSInteger xsInteger = new XSInteger(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInteger.setFacets(simpleType);
}
return xsInteger;
case SimpleTypesFactory.INT_TYPE: //-- int
XSInt xsInt = new XSInt(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInt.setFacets(simpleType);
}
return xsInt;
case SimpleTypesFactory.LANGUAGE_TYPE: //-- Language
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype '" + simpleType.getName()
+ "' is supported only as a String by Castor Source Generator.");
return new XSString();
case SimpleTypesFactory.LONG_TYPE: //-- long
XSLong xsLong = new XSLong(useWrapper);
if (!simpleType.isBuiltInType()) {
xsLong.setFacets(simpleType);
}
return xsLong;
case SimpleTypesFactory.NCNAME_TYPE: //--NCName
return new XSNCName();
case SimpleTypesFactory.NON_POSITIVE_INTEGER_TYPE: //-- nonPositiveInteger
XSNonPositiveInteger xsNPInteger = new XSNonPositiveInteger(useWrapper);
xsNPInteger.setFacets(simpleType);
return xsNPInteger;
case SimpleTypesFactory.NON_NEGATIVE_INTEGER_TYPE: //-- nonNegativeInteger
XSNonNegativeInteger xsNNInteger = new XSNonNegativeInteger(useWrapper);
xsNNInteger.setFacets(simpleType);
return xsNNInteger;
case SimpleTypesFactory.NEGATIVE_INTEGER_TYPE: //-- negative-integer
XSNegativeInteger xsNInteger = new XSNegativeInteger(useWrapper);
xsNInteger.setFacets(simpleType);
return xsNInteger;
case SimpleTypesFactory.UNSIGNED_INT_TYPE: //-- unsigned-integer
XSUnsignedInt xsUnsignedInt = new XSUnsignedInt(useWrapper);
xsUnsignedInt.setFacets(simpleType);
return xsUnsignedInt;
case SimpleTypesFactory.UNSIGNED_SHORT_TYPE: //-- unsigned-short
XSUnsignedShort xsUnsignedShort = new XSUnsignedShort(useWrapper);
xsUnsignedShort.setFacets(simpleType);
return xsUnsignedShort;
case SimpleTypesFactory.UNSIGNED_BYTE_TYPE: //-- unsigned-byte
XSUnsignedByte xsUnsignedByte = new XSUnsignedByte(useWrapper);
xsUnsignedByte.setFacets(simpleType);
return xsUnsignedByte;
case SimpleTypesFactory.UNSIGNED_LONG_TYPE: //-- unsigned-long
XSUnsignedLong xsUnsignedLong = new XSUnsignedLong();
xsUnsignedLong.setFacets(simpleType);
return xsUnsignedLong;
case SimpleTypesFactory.NORMALIZEDSTRING_TYPE: //-- normalizedString
XSNormalizedString xsNormalString = new XSNormalizedString();
if (!simpleType.isBuiltInType()) {
xsNormalString.setFacets(simpleType);
}
return xsNormalString;
case SimpleTypesFactory.POSITIVE_INTEGER_TYPE: //-- positive-integer
XSPositiveInteger xsPInteger = new XSPositiveInteger(useWrapper);
xsPInteger.setFacets(simpleType);
return xsPInteger;
case SimpleTypesFactory.QNAME_TYPE: //-- QName
XSQName xsQName = new XSQName();
xsQName.setFacets(simpleType);
return xsQName;
case SimpleTypesFactory.STRING_TYPE: //-- string
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType == null) {
// Not an enumerated String type
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
xsType = xsString;
}
break;
case SimpleTypesFactory.SHORT_TYPE: //-- short
XSShort xsShort = new XSShort(useWrapper);
if (!simpleType.isBuiltInType()) {
xsShort.setFacets(simpleType);
}
return xsShort;
case SimpleTypesFactory.TIME_TYPE: //-- time
XSTime xsTime = new XSTime();
if (!simpleType.isBuiltInType()) {
xsTime.setFacets(simpleType);
}
return xsTime;
case SimpleTypesFactory.TOKEN_TYPE: //-- token
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype 'token'"
+ " is supported only as a String by Castor Source Generator.");
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
return xsString;
default: //-- error
String name = simpleType.getName();
if (name == null || name.length() == 0) {
//--we know it is a restriction
name = simpleType.getBuiltInBaseType().getName();
}
LOG.warn("Warning: The W3C datatype '" + name + "' "
+ "is not currently supported by Castor Source Generator.");
String className = JavaNaming.toJavaClassName(name);
xsType = new XSClass(new JClass(className));
break;
}
return xsType;
} //-- convertType
/**
* Returns the XSType that corresponds to the given javaType.
* @param javaType name of the Java type for which to look up the XSType
* @return XSType that corresponds to the given javaType
*/
public static XSType convertType(final String javaType) {
if (javaType == null) {
return null;
}
//--Boolean
if (javaType.equals(TypeNames.BOOLEAN_OBJECT)) {
return new XSBoolean(true);
} else if (javaType.equals(TypeNames.BOOLEAN_PRIMITIVE)) {
return new XSBoolean(false);
} else if (javaType.equals(TypeNames.BYTE_OBJECT)) {
return new XSByte(true);
} else if (javaType.equals(TypeNames.BYTE_PRIMITIVE)) {
return new XSBoolean(false);
} else if (javaType.equals(TypeNames.CASTOR_DATE)) {
return new XSDateTime();
} else if (javaType.equals(TypeNames.CASTOR_DURATION)) {
return new XSDuration();
} else if (javaType.equals(TypeNames.CASTOR_GDAY)) {
return new XSGDay();
} else if (javaType.equals(TypeNames.CASTOR_GMONTH)) {
return new XSGMonth();
} else if (javaType.equals(TypeNames.CASTOR_GMONTHDAY)) {
return new XSGMonthDay();
} else if (javaType.equals(TypeNames.CASTOR_GYEAR)) {
return new XSGYear();
} else if (javaType.equals(TypeNames.CASTOR_GYEARMONTH)) {
return new XSGYearMonth();
} else if (javaType.equals(TypeNames.CASTOR_TIME)) {
return new XSTime();
} else if (javaType.equals(TypeNames.DATE)) {
return new XSDate();
} else if (javaType.equals(TypeNames.DECIMAL)) {
return new XSDecimal();
} else if (javaType.equals(TypeNames.DOUBLE_OBJECT)) {
return new XSDouble(true);
} else if (javaType.equals(TypeNames.DOUBLE_PRIMITIVE)) {
return new XSDouble(false);
} else if (javaType.equals(TypeNames.FLOAT_OBJECT)) {
return new XSFloat(true);
} else if (javaType.equals(TypeNames.FLOAT_PRIMITIVE)) {
return new XSDouble(false);
} else if (javaType.equals(TypeNames.INTEGER)) {
return new XSInteger(true);
} else if (javaType.equals(TypeNames.INT)) {
return new XSInt();
} else if (javaType.equals(TypeNames.SHORT_OBJECT)) {
return new XSShort(true);
} else if (javaType.equals(TypeNames.SHORT_PRIMITIVE)) {
return new XSShort(false);
} else if (javaType.equals(TypeNames.STRING)) {
return new XSString();
}
//--no XSType implemented for it we return a XSClass
return new XSClass(new JClass(javaType));
}
/**
* Returns an XSType for an enumerated type. For non-enumerated types,
* returns null.
* @param simpleType the SimpleType being inspected
* @param packageName current package name
* @return an XSType for an enumerated type, null for a non-enumerated type.
*/
private XSType findXSTypeForEnumeration(final SimpleType simpleType, final String packageName) {
if (!simpleType.hasFacet(Facet.ENUMERATION)) {
return null;
}
XSType xsType = null;
String typeName = simpleType.getName();
//-- anonymous type
if (typeName == null) {
Structure parent = simpleType.getParent();
if (parent instanceof ElementDecl) {
typeName = ((ElementDecl) parent).getName();
} else if (parent instanceof AttributeDecl) {
typeName = ((AttributeDecl) parent).getName();
}
typeName = typeName + "Type";
}
String className = JavaNaming.toJavaClassName(typeName);
// Get the appropriate package name for this type
String typePackageName = packageName;
if (typePackageName == null) {
String ns = simpleType.getSchema().getTargetNamespace();
typePackageName = _config.lookupPackageByNamespace(ns);
}
if (typePackageName != null && typePackageName.length() > 0) {
typePackageName = typePackageName + '.' + SourceGeneratorConstants.TYPES_PACKAGE;
} else {
typePackageName = SourceGeneratorConstants.TYPES_PACKAGE;
}
className = typePackageName + '.' + className;
xsType = new XSClass(new JClass(className));
xsType.setAsEnumerated(true);
return xsType;
}
/**
* Returns the common type for the Union, or null if no common type exists
* among the members of the Union.
*
* @param union
* the Union to return the common type for
* @return the common SimpleType for the Union.
*/
private static SimpleType findCommonType(final Union union) {
SimpleType common = null;
Enumeration enumeration = union.getMemberTypes();
while (enumeration.hasMoreElements()) {
SimpleType type = (SimpleType) enumeration.nextElement();
type = type.getBuiltInBaseType();
if (common == null) {
common = type;
} else {
common = findCommonType(common, type);
//-- no common types
if (common == null) {
break;
}
}
}
return common;
} //-- findCommonType
/**
* Compares the two SimpleTypes. The lowest common ancestor of both types
* will be returned, otherwise null is returned if the types are not
* compatible.
*
* @param aType
* the first type to compare
* @param bType
* the second type to compare
* @return the common ancestor of both types if there is one, null if the
* types are not compatible.
*/
private static SimpleType findCommonType(final SimpleType aType, final SimpleType bType) {
int type1 = aType.getTypeCode();
int type2 = bType.getTypeCode();
if (type1 == type2) {
return aType;
}
if (isNumeric(aType) && isNumeric(bType)) {
// TODO Finish this so we can implement Unions
} else if (isString(aType) && isString(bType)) {
// TODO Finish this so we can implement Unions
}
//-- Just return string for now, as all simpleTypes can fit into a string
Schema schema = aType.getSchema();
return schema.getSimpleType("string", schema.getSchemaNamespace());
}
/**
* Returns true if this simpletype is numeric.
* @param type the type to be examined
* @return true if this simpletype is numeric.
*/
private static boolean isNumeric(final SimpleType type) {
int code = type.getTypeCode();
switch (code) {
case SimpleTypesFactory.BYTE_TYPE:
case SimpleTypesFactory.DOUBLE_TYPE:
case SimpleTypesFactory.DECIMAL_TYPE:
case SimpleTypesFactory.FLOAT_TYPE:
case SimpleTypesFactory.INTEGER_TYPE:
case SimpleTypesFactory.INT_TYPE:
case SimpleTypesFactory.LONG_TYPE:
case SimpleTypesFactory.NON_POSITIVE_INTEGER_TYPE:
case SimpleTypesFactory.NON_NEGATIVE_INTEGER_TYPE:
case SimpleTypesFactory.NEGATIVE_INTEGER_TYPE:
case SimpleTypesFactory.POSITIVE_INTEGER_TYPE:
case SimpleTypesFactory.SHORT_TYPE:
return true;
default:
return false;
}
} //-- isNumeric
/**
* Returns true if this simpletype is a String.
* @param type the type to be examined
* @return true if this simpletype is String.
*/
private static boolean isString(final SimpleType type) {
int code = type.getTypeCode();
switch (code) {
//-- string types
case SimpleTypesFactory.ANYURI_TYPE:
case SimpleTypesFactory.ID_TYPE:
case SimpleTypesFactory.IDREF_TYPE:
case SimpleTypesFactory.IDREFS_TYPE:
case SimpleTypesFactory.LANGUAGE_TYPE:
case SimpleTypesFactory.NCNAME_TYPE:
case SimpleTypesFactory.NMTOKEN_TYPE:
case SimpleTypesFactory.NMTOKENS_TYPE:
case SimpleTypesFactory.NORMALIZEDSTRING_TYPE:
case SimpleTypesFactory.STRING_TYPE:
case SimpleTypesFactory.QNAME_TYPE:
return true;
default:
return false;
}
} //-- isString
/**
* Constants.
*/
protected static class TypeNames {
protected static final String BOOLEAN_PRIMITIVE = JType.BOOLEAN.getName();
protected static final String BOOLEAN_OBJECT = JType.BOOLEAN.getWrapperName();
protected static final String BYTE_PRIMITIVE = JType.BYTE.getName();
protected static final String BYTE_OBJECT = JType.BYTE.getWrapperName();
protected static final String DATE = "java.util.Date";
protected static final String CASTOR_DATE = "org.exolab.castor.types.Date";
protected static final String CASTOR_TIME = "org.exolab.castor.types.Time";
protected static final String CASTOR_DURATION = "org.exolab.castor.types.Duration";
protected static final String CASTOR_GMONTH = "org.exolab.castor.types.GMonth";
protected static final String CASTOR_GMONTHDAY = "org.exolab.castor.types.GMonthDay";
protected static final String CASTOR_GYEAR = "org.exolab.castor.types.GYear";
protected static final String CASTOR_GYEARMONTH = "org.exolab.castor.types.GYearMonth";
protected static final String CASTOR_GDAY = "org.exolab.castor.types.GDay";
protected static final String DECIMAL = "java.math.BigDecimal";
protected static final String DOUBLE_PRIMITIVE = JType.DOUBLE.getName();
protected static final String DOUBLE_OBJECT = JType.DOUBLE.getWrapperName();
protected static final String FLOAT_PRIMITIVE = JType.FLOAT.getName();
protected static final String FLOAT_OBJECT = JType.FLOAT.getWrapperName();
protected static final String INT = JType.INT.getName();
protected static final String INTEGER = JType.INT.getWrapperName();
protected static final String SHORT_PRIMITIVE = JType.SHORT.getName();
protected static final String SHORT_OBJECT = JType.SHORT.getWrapperName();
protected static final String STRING = "java.lang.String";
}
} //-- TypeConversion
| true | true | public XSType convertType(final SimpleType simpleType, final String packageName,
final boolean useWrapper, final boolean useJava50) {
if (simpleType == null) {
return null;
}
XSType xsType = null;
//-- determine base type
SimpleType base = simpleType;
while ((base != null) && (!base.isBuiltInType())) {
base = (SimpleType) base.getBaseType();
}
// try to find a common type for UNIONs, and use it; if not,
// use 'java.lang.Object' instead.
if (simpleType.getStructureType() == Structure.UNION) {
SimpleType currentUnion = simpleType;
SimpleType common = findCommonType((Union) currentUnion);
// look at type hierarchy (if any), and try to
// find a common type recursively
while (common == null
&& currentUnion.getBaseType().getStructureType() == Structure.UNION)
{
currentUnion = (SimpleType) currentUnion.getBaseType();
common = findCommonType((Union) currentUnion);
}
if (common == null) {
return new XSClass(SGTypes.OBJECT);
}
return convertType(common, packageName, useWrapper, useJava50);
} else if (base == null) {
String className = JavaNaming.toJavaClassName(simpleType.getName());
return new XSClass(new JClass(className));
}
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType != null) {
return xsType;
}
// If we don't have the XSType yet, we have to look at the Type Code
switch (base.getTypeCode()) {
case SimpleTypesFactory.ID_TYPE: //-- ID
return new XSId();
case SimpleTypesFactory.IDREF_TYPE: //-- IDREF
return new XSIdRef();
case SimpleTypesFactory.IDREFS_TYPE: //-- IDREFS
return new XSIdRefs(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.NMTOKEN_TYPE: //-- NMTOKEN
XSNMToken xsNMToken = new XSNMToken();
xsNMToken.setFacets(simpleType);
return xsNMToken;
case SimpleTypesFactory.NMTOKENS_TYPE: //-- NMTOKENS
return new XSNMTokens(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.ANYURI_TYPE: //--AnyURI
return new XSAnyURI();
case SimpleTypesFactory.BASE64BINARY_TYPE: //-- base64Bbinary
return new XSBase64Binary(useJava50);
case SimpleTypesFactory.HEXBINARY_TYPE: //-- hexBinary
return new XSHexBinary(useJava50);
case SimpleTypesFactory.BOOLEAN_TYPE: //-- boolean
return new XSBoolean(useWrapper);
case SimpleTypesFactory.BYTE_TYPE: //--byte
XSByte xsByte = new XSByte(useWrapper);
if (!simpleType.isBuiltInType()) {
xsByte.setFacets(simpleType);
}
return xsByte;
case SimpleTypesFactory.DATE_TYPE: //-- date
XSDate xsDate = new XSDate();
if (!simpleType.isBuiltInType()) {
xsDate.setFacets(simpleType);
}
return xsDate;
case SimpleTypesFactory.DATETIME_TYPE: //-- dateTime
XSDateTime xsDateTime = new XSDateTime();
if (!simpleType.isBuiltInType()) {
xsDateTime.setFacets(simpleType);
}
return xsDateTime;
case SimpleTypesFactory.DOUBLE_TYPE: //-- double
XSDouble xsDouble = new XSDouble(useWrapper);
if (!simpleType.isBuiltInType()) {
xsDouble.setFacets(simpleType);
}
return xsDouble;
case SimpleTypesFactory.DURATION_TYPE: //-- duration
XSDuration xsDuration = new XSDuration();
if (!simpleType.isBuiltInType()) {
xsDuration.setFacets(simpleType);
}
return xsDuration;
case SimpleTypesFactory.DECIMAL_TYPE: //-- decimal
XSDecimal xsDecimal = new XSDecimal();
if (!simpleType.isBuiltInType()) {
xsDecimal.setFacets(simpleType);
}
return xsDecimal;
case SimpleTypesFactory.FLOAT_TYPE: //-- float
XSFloat xsFloat = new XSFloat(useWrapper);
if (!simpleType.isBuiltInType()) {
xsFloat.setFacets(simpleType);
}
return xsFloat;
case SimpleTypesFactory.GDAY_TYPE: //--GDay
XSGDay xsGDay = new XSGDay();
if (!simpleType.isBuiltInType()) {
xsGDay.setFacets(simpleType);
}
return xsGDay;
case SimpleTypesFactory.GMONTHDAY_TYPE: //--GMonthDay
XSGMonthDay xsGMonthDay = new XSGMonthDay();
if (!simpleType.isBuiltInType()) {
xsGMonthDay.setFacets(simpleType);
}
return xsGMonthDay;
case SimpleTypesFactory.GMONTH_TYPE: //--GMonth
XSGMonth xsGMonth = new XSGMonth();
if (!simpleType.isBuiltInType()) {
xsGMonth.setFacets(simpleType);
}
return xsGMonth;
case SimpleTypesFactory.GYEARMONTH_TYPE: //--GYearMonth
XSGYearMonth xsGYearMonth = new XSGYearMonth();
if (!simpleType.isBuiltInType()) {
xsGYearMonth.setFacets(simpleType);
}
return xsGYearMonth;
case SimpleTypesFactory.GYEAR_TYPE: //--GYear
XSGYear xsGYear = new XSGYear();
if (!simpleType.isBuiltInType()) {
xsGYear.setFacets(simpleType);
}
return xsGYear;
case SimpleTypesFactory.INTEGER_TYPE: //-- integer
XSInteger xsInteger = new XSInteger(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInteger.setFacets(simpleType);
}
return xsInteger;
case SimpleTypesFactory.INT_TYPE: //-- int
XSInt xsInt = new XSInt(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInt.setFacets(simpleType);
}
return xsInt;
case SimpleTypesFactory.LANGUAGE_TYPE: //-- Language
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype '" + simpleType.getName()
+ "' is supported only as a String by Castor Source Generator.");
return new XSString();
case SimpleTypesFactory.LONG_TYPE: //-- long
XSLong xsLong = new XSLong(useWrapper);
if (!simpleType.isBuiltInType()) {
xsLong.setFacets(simpleType);
}
return xsLong;
case SimpleTypesFactory.NCNAME_TYPE: //--NCName
return new XSNCName();
case SimpleTypesFactory.NON_POSITIVE_INTEGER_TYPE: //-- nonPositiveInteger
XSNonPositiveInteger xsNPInteger = new XSNonPositiveInteger(useWrapper);
xsNPInteger.setFacets(simpleType);
return xsNPInteger;
case SimpleTypesFactory.NON_NEGATIVE_INTEGER_TYPE: //-- nonNegativeInteger
XSNonNegativeInteger xsNNInteger = new XSNonNegativeInteger(useWrapper);
xsNNInteger.setFacets(simpleType);
return xsNNInteger;
case SimpleTypesFactory.NEGATIVE_INTEGER_TYPE: //-- negative-integer
XSNegativeInteger xsNInteger = new XSNegativeInteger(useWrapper);
xsNInteger.setFacets(simpleType);
return xsNInteger;
case SimpleTypesFactory.UNSIGNED_INT_TYPE: //-- unsigned-integer
XSUnsignedInt xsUnsignedInt = new XSUnsignedInt(useWrapper);
xsUnsignedInt.setFacets(simpleType);
return xsUnsignedInt;
case SimpleTypesFactory.UNSIGNED_SHORT_TYPE: //-- unsigned-short
XSUnsignedShort xsUnsignedShort = new XSUnsignedShort(useWrapper);
xsUnsignedShort.setFacets(simpleType);
return xsUnsignedShort;
case SimpleTypesFactory.UNSIGNED_BYTE_TYPE: //-- unsigned-byte
XSUnsignedByte xsUnsignedByte = new XSUnsignedByte(useWrapper);
xsUnsignedByte.setFacets(simpleType);
return xsUnsignedByte;
case SimpleTypesFactory.UNSIGNED_LONG_TYPE: //-- unsigned-long
XSUnsignedLong xsUnsignedLong = new XSUnsignedLong();
xsUnsignedLong.setFacets(simpleType);
return xsUnsignedLong;
case SimpleTypesFactory.NORMALIZEDSTRING_TYPE: //-- normalizedString
XSNormalizedString xsNormalString = new XSNormalizedString();
if (!simpleType.isBuiltInType()) {
xsNormalString.setFacets(simpleType);
}
return xsNormalString;
case SimpleTypesFactory.POSITIVE_INTEGER_TYPE: //-- positive-integer
XSPositiveInteger xsPInteger = new XSPositiveInteger(useWrapper);
xsPInteger.setFacets(simpleType);
return xsPInteger;
case SimpleTypesFactory.QNAME_TYPE: //-- QName
XSQName xsQName = new XSQName();
xsQName.setFacets(simpleType);
return xsQName;
case SimpleTypesFactory.STRING_TYPE: //-- string
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType == null) {
// Not an enumerated String type
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
xsType = xsString;
}
break;
case SimpleTypesFactory.SHORT_TYPE: //-- short
XSShort xsShort = new XSShort(useWrapper);
if (!simpleType.isBuiltInType()) {
xsShort.setFacets(simpleType);
}
return xsShort;
case SimpleTypesFactory.TIME_TYPE: //-- time
XSTime xsTime = new XSTime();
if (!simpleType.isBuiltInType()) {
xsTime.setFacets(simpleType);
}
return xsTime;
case SimpleTypesFactory.TOKEN_TYPE: //-- token
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype 'token'"
+ " is supported only as a String by Castor Source Generator.");
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
return xsString;
default: //-- error
String name = simpleType.getName();
if (name == null || name.length() == 0) {
//--we know it is a restriction
name = simpleType.getBuiltInBaseType().getName();
}
LOG.warn("Warning: The W3C datatype '" + name + "' "
+ "is not currently supported by Castor Source Generator.");
String className = JavaNaming.toJavaClassName(name);
xsType = new XSClass(new JClass(className));
break;
}
return xsType;
} //-- convertType
| public XSType convertType(final SimpleType simpleType, final String packageName,
final boolean useWrapper, final boolean useJava50) {
if (simpleType == null) {
return null;
}
XSType xsType = null;
//-- determine base type
SimpleType base = simpleType;
while ((base != null) && (!base.isBuiltInType())) {
base = (SimpleType) base.getBaseType();
}
// try to find a common type for UNIONs, and use it; if not,
// use 'java.lang.Object' instead.
if (simpleType.getStructureType() == Structure.UNION) {
SimpleType currentUnion = simpleType;
SimpleType common = findCommonType((Union) currentUnion);
// look at type hierarchy (if any), and try to
// find a common type recursively
while (common == null
&& currentUnion.getBaseType() != null
&& currentUnion.getBaseType().getStructureType() == Structure.UNION)
{
currentUnion = (SimpleType) currentUnion.getBaseType();
common = findCommonType((Union) currentUnion);
}
if (common == null) {
return new XSClass(SGTypes.OBJECT);
}
return convertType(common, packageName, useWrapper, useJava50);
} else if (base == null) {
String className = JavaNaming.toJavaClassName(simpleType.getName());
return new XSClass(new JClass(className));
}
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType != null) {
return xsType;
}
// If we don't have the XSType yet, we have to look at the Type Code
switch (base.getTypeCode()) {
case SimpleTypesFactory.ID_TYPE: //-- ID
return new XSId();
case SimpleTypesFactory.IDREF_TYPE: //-- IDREF
return new XSIdRef();
case SimpleTypesFactory.IDREFS_TYPE: //-- IDREFS
return new XSIdRefs(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.NMTOKEN_TYPE: //-- NMTOKEN
XSNMToken xsNMToken = new XSNMToken();
xsNMToken.setFacets(simpleType);
return xsNMToken;
case SimpleTypesFactory.NMTOKENS_TYPE: //-- NMTOKENS
return new XSNMTokens(SourceGeneratorConstants.FIELD_INFO_VECTOR, useJava50);
case SimpleTypesFactory.ANYURI_TYPE: //--AnyURI
return new XSAnyURI();
case SimpleTypesFactory.BASE64BINARY_TYPE: //-- base64Bbinary
return new XSBase64Binary(useJava50);
case SimpleTypesFactory.HEXBINARY_TYPE: //-- hexBinary
return new XSHexBinary(useJava50);
case SimpleTypesFactory.BOOLEAN_TYPE: //-- boolean
return new XSBoolean(useWrapper);
case SimpleTypesFactory.BYTE_TYPE: //--byte
XSByte xsByte = new XSByte(useWrapper);
if (!simpleType.isBuiltInType()) {
xsByte.setFacets(simpleType);
}
return xsByte;
case SimpleTypesFactory.DATE_TYPE: //-- date
XSDate xsDate = new XSDate();
if (!simpleType.isBuiltInType()) {
xsDate.setFacets(simpleType);
}
return xsDate;
case SimpleTypesFactory.DATETIME_TYPE: //-- dateTime
XSDateTime xsDateTime = new XSDateTime();
if (!simpleType.isBuiltInType()) {
xsDateTime.setFacets(simpleType);
}
return xsDateTime;
case SimpleTypesFactory.DOUBLE_TYPE: //-- double
XSDouble xsDouble = new XSDouble(useWrapper);
if (!simpleType.isBuiltInType()) {
xsDouble.setFacets(simpleType);
}
return xsDouble;
case SimpleTypesFactory.DURATION_TYPE: //-- duration
XSDuration xsDuration = new XSDuration();
if (!simpleType.isBuiltInType()) {
xsDuration.setFacets(simpleType);
}
return xsDuration;
case SimpleTypesFactory.DECIMAL_TYPE: //-- decimal
XSDecimal xsDecimal = new XSDecimal();
if (!simpleType.isBuiltInType()) {
xsDecimal.setFacets(simpleType);
}
return xsDecimal;
case SimpleTypesFactory.FLOAT_TYPE: //-- float
XSFloat xsFloat = new XSFloat(useWrapper);
if (!simpleType.isBuiltInType()) {
xsFloat.setFacets(simpleType);
}
return xsFloat;
case SimpleTypesFactory.GDAY_TYPE: //--GDay
XSGDay xsGDay = new XSGDay();
if (!simpleType.isBuiltInType()) {
xsGDay.setFacets(simpleType);
}
return xsGDay;
case SimpleTypesFactory.GMONTHDAY_TYPE: //--GMonthDay
XSGMonthDay xsGMonthDay = new XSGMonthDay();
if (!simpleType.isBuiltInType()) {
xsGMonthDay.setFacets(simpleType);
}
return xsGMonthDay;
case SimpleTypesFactory.GMONTH_TYPE: //--GMonth
XSGMonth xsGMonth = new XSGMonth();
if (!simpleType.isBuiltInType()) {
xsGMonth.setFacets(simpleType);
}
return xsGMonth;
case SimpleTypesFactory.GYEARMONTH_TYPE: //--GYearMonth
XSGYearMonth xsGYearMonth = new XSGYearMonth();
if (!simpleType.isBuiltInType()) {
xsGYearMonth.setFacets(simpleType);
}
return xsGYearMonth;
case SimpleTypesFactory.GYEAR_TYPE: //--GYear
XSGYear xsGYear = new XSGYear();
if (!simpleType.isBuiltInType()) {
xsGYear.setFacets(simpleType);
}
return xsGYear;
case SimpleTypesFactory.INTEGER_TYPE: //-- integer
XSInteger xsInteger = new XSInteger(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInteger.setFacets(simpleType);
}
return xsInteger;
case SimpleTypesFactory.INT_TYPE: //-- int
XSInt xsInt = new XSInt(useWrapper);
if (!simpleType.isBuiltInType()) {
xsInt.setFacets(simpleType);
}
return xsInt;
case SimpleTypesFactory.LANGUAGE_TYPE: //-- Language
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype '" + simpleType.getName()
+ "' is supported only as a String by Castor Source Generator.");
return new XSString();
case SimpleTypesFactory.LONG_TYPE: //-- long
XSLong xsLong = new XSLong(useWrapper);
if (!simpleType.isBuiltInType()) {
xsLong.setFacets(simpleType);
}
return xsLong;
case SimpleTypesFactory.NCNAME_TYPE: //--NCName
return new XSNCName();
case SimpleTypesFactory.NON_POSITIVE_INTEGER_TYPE: //-- nonPositiveInteger
XSNonPositiveInteger xsNPInteger = new XSNonPositiveInteger(useWrapper);
xsNPInteger.setFacets(simpleType);
return xsNPInteger;
case SimpleTypesFactory.NON_NEGATIVE_INTEGER_TYPE: //-- nonNegativeInteger
XSNonNegativeInteger xsNNInteger = new XSNonNegativeInteger(useWrapper);
xsNNInteger.setFacets(simpleType);
return xsNNInteger;
case SimpleTypesFactory.NEGATIVE_INTEGER_TYPE: //-- negative-integer
XSNegativeInteger xsNInteger = new XSNegativeInteger(useWrapper);
xsNInteger.setFacets(simpleType);
return xsNInteger;
case SimpleTypesFactory.UNSIGNED_INT_TYPE: //-- unsigned-integer
XSUnsignedInt xsUnsignedInt = new XSUnsignedInt(useWrapper);
xsUnsignedInt.setFacets(simpleType);
return xsUnsignedInt;
case SimpleTypesFactory.UNSIGNED_SHORT_TYPE: //-- unsigned-short
XSUnsignedShort xsUnsignedShort = new XSUnsignedShort(useWrapper);
xsUnsignedShort.setFacets(simpleType);
return xsUnsignedShort;
case SimpleTypesFactory.UNSIGNED_BYTE_TYPE: //-- unsigned-byte
XSUnsignedByte xsUnsignedByte = new XSUnsignedByte(useWrapper);
xsUnsignedByte.setFacets(simpleType);
return xsUnsignedByte;
case SimpleTypesFactory.UNSIGNED_LONG_TYPE: //-- unsigned-long
XSUnsignedLong xsUnsignedLong = new XSUnsignedLong();
xsUnsignedLong.setFacets(simpleType);
return xsUnsignedLong;
case SimpleTypesFactory.NORMALIZEDSTRING_TYPE: //-- normalizedString
XSNormalizedString xsNormalString = new XSNormalizedString();
if (!simpleType.isBuiltInType()) {
xsNormalString.setFacets(simpleType);
}
return xsNormalString;
case SimpleTypesFactory.POSITIVE_INTEGER_TYPE: //-- positive-integer
XSPositiveInteger xsPInteger = new XSPositiveInteger(useWrapper);
xsPInteger.setFacets(simpleType);
return xsPInteger;
case SimpleTypesFactory.QNAME_TYPE: //-- QName
XSQName xsQName = new XSQName();
xsQName.setFacets(simpleType);
return xsQName;
case SimpleTypesFactory.STRING_TYPE: //-- string
xsType = findXSTypeForEnumeration(simpleType, packageName);
if (xsType == null) {
// Not an enumerated String type
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
xsType = xsString;
}
break;
case SimpleTypesFactory.SHORT_TYPE: //-- short
XSShort xsShort = new XSShort(useWrapper);
if (!simpleType.isBuiltInType()) {
xsShort.setFacets(simpleType);
}
return xsShort;
case SimpleTypesFactory.TIME_TYPE: //-- time
XSTime xsTime = new XSTime();
if (!simpleType.isBuiltInType()) {
xsTime.setFacets(simpleType);
}
return xsTime;
case SimpleTypesFactory.TOKEN_TYPE: //-- token
//-- since we don't actually support this type, yet, we'll simply treat
//-- it as a string, but warn the user.
LOG.warn("Warning: Currently, the W3C datatype 'token'"
+ " is supported only as a String by Castor Source Generator.");
XSString xsString = new XSString();
if (!simpleType.isBuiltInType()) {
xsString.setFacets(simpleType);
}
return xsString;
default: //-- error
String name = simpleType.getName();
if (name == null || name.length() == 0) {
//--we know it is a restriction
name = simpleType.getBuiltInBaseType().getName();
}
LOG.warn("Warning: The W3C datatype '" + name + "' "
+ "is not currently supported by Castor Source Generator.");
String className = JavaNaming.toJavaClassName(name);
xsType = new XSClass(new JClass(className));
break;
}
return xsType;
} //-- convertType
|
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs/provider/sftp/SftpFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs/provider/sftp/SftpFileObject.java
index 46b8eab..8e61172 100644
--- a/trunk/core/src/main/java/org/apache/commons/vfs/provider/sftp/SftpFileObject.java
+++ b/trunk/core/src/main/java/org/apache/commons/vfs/provider/sftp/SftpFileObject.java
@@ -1,586 +1,587 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs.provider.sftp;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileNotFoundException;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.NameScope;
import org.apache.commons.vfs.RandomAccessContent;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.provider.AbstractFileObject;
import org.apache.commons.vfs.provider.UriParser;
import org.apache.commons.vfs.util.FileObjectUtils;
import org.apache.commons.vfs.util.MonitorInputStream;
import org.apache.commons.vfs.util.MonitorOutputStream;
import org.apache.commons.vfs.util.RandomAccessMode;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
/**
* An SFTP file.
*
* @author <a href="mailto:[email protected]">Adam Murdoch</a>
* @version $Revision$ $Date: 2005-10-14 19:59:47 +0200 (Fr, 14 Okt
* 2005) $
*/
public class SftpFileObject extends AbstractFileObject implements FileObject
{
private final SftpFileSystem fileSystem;
private SftpATTRS attrs;
private final String relPath;
private boolean inRefresh;
protected SftpFileObject(final FileName name,
final SftpFileSystem fileSystem) throws FileSystemException
{
super(name, fileSystem);
this.fileSystem = fileSystem;
relPath = UriParser.decode(fileSystem.getRootName().getRelativeName(
name));
}
@Override
protected void doDetach() throws Exception
{
attrs = null;
}
@Override
public void refresh() throws FileSystemException
{
if (!inRefresh)
{
try
{
inRefresh = true;
super.refresh();
try
{
attrs = null;
getType();
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
finally
{
inRefresh = false;
}
}
}
/**
* Determines the type of this file, returns null if the file does not
* exist.
*/
@Override
protected FileType doGetType() throws Exception
{
if (attrs == null)
{
statSelf();
}
if (attrs == null)
{
return FileType.IMAGINARY;
}
if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-permissions.error");
}
if (attrs.isDir())
{
return FileType.FOLDER;
}
else
{
return FileType.FILE;
}
}
/**
* Called when the type or content of this file changes.
*/
@Override
protected void onChange() throws Exception
{
statSelf();
}
/**
* Fetches file attrs from server.
*/
private void statSelf() throws Exception
{
ChannelSftp channel = fileSystem.getChannel();
try
{
setStat(channel.stat(relPath));
}
catch (final SftpException e)
{
try
{
// maybe the channel has some problems, so recreate the channel and retry
if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE)
{
channel.disconnect();
channel = fileSystem.getChannel();
setStat(channel.stat(relPath));
}
else
{
// Really does not exist
attrs = null;
}
}
catch (final SftpException e2)
{
// TODO - not strictly true, but jsch 0.1.2 does not give us
// enough info in the exception. Should be using:
// if ( e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE )
// However, sometimes the exception has the correct id, and
// sometimes
// it does not. Need to look into why.
// Does not exist
attrs = null;
}
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Set attrs from listChildrenResolved
*/
private void setStat(SftpATTRS attrs)
{
this.attrs = attrs;
}
/**
* Creates this file as a folder.
*/
@Override
protected void doCreateFolder() throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
channel.mkdir(relPath);
}
finally
{
fileSystem.putChannel(channel);
}
}
@Override
protected long doGetLastModifiedTime() throws Exception
{
if (attrs == null
|| (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-modtime.error");
}
return attrs.getMTime() * 1000L;
}
/**
* Sets the last modified time of this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}. <p/>
*
* @param modtime
* is modification time in milliseconds. SFTP protocol can send
* times with nanosecond precision but at the moment jsch send
* them with second precision.
*/
@Override
protected void doSetLastModifiedTime(final long modtime) throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
int newMTime = (int) (modtime / 1000L);
attrs.setACMODTIME(attrs.getATime(), newMTime);
channel.setStat(relPath, attrs);
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Deletes the file.
*/
@Override
protected void doDelete() throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
if (getType() == FileType.FILE)
{
channel.rm(relPath);
}
else
{
channel.rmdir(relPath);
}
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Rename the file.
*/
@Override
protected void doRename(FileObject newfile) throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
channel.rename(relPath, ((SftpFileObject) newfile).relPath);
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Lists the children of this file.
*/
@Override
protected FileObject[] doListChildrenResolved() throws Exception
{
// List the contents of the folder
- Vector<LsEntry> vector = null;
+ Vector<?> vector = null;
final ChannelSftp channel = fileSystem.getChannel();
try
{
// try the direct way to list the directory on the server to avoid too many roundtrips
vector = channel.ls(relPath);
}
catch (SftpException e)
{
String workingDirectory = null;
try
{
if (relPath != null)
{
workingDirectory = channel.pwd();
channel.cd(relPath);
}
}
catch (SftpException ex)
{
// VFS-210: seems not to be a directory
return null;
}
SftpException lsEx = null;
try
{
vector = channel.ls(".");
}
catch (SftpException ex)
{
lsEx = ex;
}
finally
{
try
{
if (relPath != null)
{
channel.cd(workingDirectory);
}
}
catch (SftpException xe)
{
throw new FileSystemException("vfs.provider.sftp/change-work-directory-back.error", workingDirectory, lsEx);
}
}
if (lsEx != null)
{
throw lsEx;
}
}
finally
{
fileSystem.putChannel(channel);
}
if (vector == null)
{
throw new FileSystemException(
"vfs.provider.sftp/list-children.error");
}
// Extract the child names
final ArrayList<FileObject> children = new ArrayList<FileObject>();
- for (Iterator<LsEntry> iterator = vector.iterator(); iterator.hasNext();)
+ for (@SuppressWarnings("unchecked") // OK because ChannelSftp.ls() is documented to return Vector<LsEntry>
+ Iterator<LsEntry> iterator = (Iterator<LsEntry>) vector.iterator(); iterator.hasNext();)
{
final LsEntry stat = iterator.next();
String name = stat.getFilename();
if (VFS.isUriStyle())
{
if (stat.getAttrs().isDir()
&& name.charAt(name.length() - 1) != '/')
{
name = name + "/";
}
}
if (name.equals(".") || name.equals("..") || name.equals("./")
|| name.equals("../"))
{
continue;
}
FileObject fo =
getFileSystem()
.resolveFile(
getFileSystem().getFileSystemManager().resolveName(
getName(), UriParser.encode(name),
NameScope.CHILD));
((SftpFileObject) FileObjectUtils.getAbstractFileObject(fo)).setStat(stat.getAttrs());
children.add(fo);
}
return children.toArray(new FileObject[children.size()]);
}
/**
* Lists the children of this file.
*/
@Override
protected String[] doListChildren() throws Exception
{
// use doListChildrenResolved for performance
return null;
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
if (attrs == null
|| (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-size.error");
}
return attrs.getSize();
}
@Override
protected RandomAccessContent doGetRandomAccessContent(
final RandomAccessMode mode) throws Exception
{
return new SftpRandomAccessContent(this, mode);
}
/**
* Creates an input stream to read the file content from.
*/
InputStream getInputStream(long filePointer) throws IOException
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
// hmmm - using the in memory method is soooo much faster ...
// TODO - Don't read the entire file into memory. Use the
// stream-based methods on ChannelSftp once they work properly final
// .... no stream based method with resume???
ByteArrayOutputStream outstr = new ByteArrayOutputStream();
try
{
channel.get(getName().getPathDecoded(), outstr, null,
ChannelSftp.RESUME, filePointer);
}
catch (SftpException e)
{
throw new FileSystemException(e);
}
outstr.close();
return new ByteArrayInputStream(outstr.toByteArray());
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Creates an input stream to read the file content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
// VFS-113: avoid npe
synchronized (fileSystem)
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
// return channel.get(getName().getPath());
// hmmm - using the in memory method is soooo much faster ...
// TODO - Don't read the entire file into memory. Use the
// stream-based methods on ChannelSftp once they work properly
/*
final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
channel.get(relPath, outstr);
outstr.close();
return new ByteArrayInputStream(outstr.toByteArray());
*/
InputStream is;
try
{
// VFS-210: sftp allows to gather an input stream even from a directory and will
// fail on first read. So we need to check the type anyway
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", getName());
}
is = channel.get(relPath);
}
catch (SftpException e)
{
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
{
throw new FileNotFoundException(getName());
}
throw new FileSystemException(e);
}
return new SftpInputStream(channel, is);
}
finally
{
// fileSystem.putChannel(channel);
}
}
}
/**
* Creates an output stream to write the file content to.
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
// TODO - Don't write the entire file into memory. Use the stream-based
// methods on ChannelSftp once the work properly
/*
final ChannelSftp channel = fileSystem.getChannel();
return new SftpOutputStream(channel);
*/
final ChannelSftp channel = fileSystem.getChannel();
return new SftpOutputStream(channel, channel.put(relPath));
}
/**
* An InputStream that monitors for end-of-file.
*/
private class SftpInputStream extends MonitorInputStream
{
private final ChannelSftp channel;
public SftpInputStream(final ChannelSftp channel, final InputStream in)
{
super(in);
this.channel = channel;
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
fileSystem.putChannel(channel);
}
}
/**
* An OutputStream that wraps an sftp OutputStream, and closes the channel
* when the stream is closed.
*/
private class SftpOutputStream extends MonitorOutputStream
{
private final ChannelSftp channel;
public SftpOutputStream(final ChannelSftp channel, OutputStream out)
{
super(out);
this.channel = channel;
}
/**
* Called after this stream is closed.
*/
@Override
protected void onClose() throws IOException
{
fileSystem.putChannel(channel);
}
}
}
| false | true | protected FileObject[] doListChildrenResolved() throws Exception
{
// List the contents of the folder
Vector<LsEntry> vector = null;
final ChannelSftp channel = fileSystem.getChannel();
try
{
// try the direct way to list the directory on the server to avoid too many roundtrips
vector = channel.ls(relPath);
}
catch (SftpException e)
{
String workingDirectory = null;
try
{
if (relPath != null)
{
workingDirectory = channel.pwd();
channel.cd(relPath);
}
}
catch (SftpException ex)
{
// VFS-210: seems not to be a directory
return null;
}
SftpException lsEx = null;
try
{
vector = channel.ls(".");
}
catch (SftpException ex)
{
lsEx = ex;
}
finally
{
try
{
if (relPath != null)
{
channel.cd(workingDirectory);
}
}
catch (SftpException xe)
{
throw new FileSystemException("vfs.provider.sftp/change-work-directory-back.error", workingDirectory, lsEx);
}
}
if (lsEx != null)
{
throw lsEx;
}
}
finally
{
fileSystem.putChannel(channel);
}
if (vector == null)
{
throw new FileSystemException(
"vfs.provider.sftp/list-children.error");
}
// Extract the child names
final ArrayList<FileObject> children = new ArrayList<FileObject>();
for (Iterator<LsEntry> iterator = vector.iterator(); iterator.hasNext();)
{
final LsEntry stat = iterator.next();
String name = stat.getFilename();
if (VFS.isUriStyle())
{
if (stat.getAttrs().isDir()
&& name.charAt(name.length() - 1) != '/')
{
name = name + "/";
}
}
if (name.equals(".") || name.equals("..") || name.equals("./")
|| name.equals("../"))
{
continue;
}
FileObject fo =
getFileSystem()
.resolveFile(
getFileSystem().getFileSystemManager().resolveName(
getName(), UriParser.encode(name),
NameScope.CHILD));
((SftpFileObject) FileObjectUtils.getAbstractFileObject(fo)).setStat(stat.getAttrs());
children.add(fo);
}
return children.toArray(new FileObject[children.size()]);
}
| protected FileObject[] doListChildrenResolved() throws Exception
{
// List the contents of the folder
Vector<?> vector = null;
final ChannelSftp channel = fileSystem.getChannel();
try
{
// try the direct way to list the directory on the server to avoid too many roundtrips
vector = channel.ls(relPath);
}
catch (SftpException e)
{
String workingDirectory = null;
try
{
if (relPath != null)
{
workingDirectory = channel.pwd();
channel.cd(relPath);
}
}
catch (SftpException ex)
{
// VFS-210: seems not to be a directory
return null;
}
SftpException lsEx = null;
try
{
vector = channel.ls(".");
}
catch (SftpException ex)
{
lsEx = ex;
}
finally
{
try
{
if (relPath != null)
{
channel.cd(workingDirectory);
}
}
catch (SftpException xe)
{
throw new FileSystemException("vfs.provider.sftp/change-work-directory-back.error", workingDirectory, lsEx);
}
}
if (lsEx != null)
{
throw lsEx;
}
}
finally
{
fileSystem.putChannel(channel);
}
if (vector == null)
{
throw new FileSystemException(
"vfs.provider.sftp/list-children.error");
}
// Extract the child names
final ArrayList<FileObject> children = new ArrayList<FileObject>();
for (@SuppressWarnings("unchecked") // OK because ChannelSftp.ls() is documented to return Vector<LsEntry>
Iterator<LsEntry> iterator = (Iterator<LsEntry>) vector.iterator(); iterator.hasNext();)
{
final LsEntry stat = iterator.next();
String name = stat.getFilename();
if (VFS.isUriStyle())
{
if (stat.getAttrs().isDir()
&& name.charAt(name.length() - 1) != '/')
{
name = name + "/";
}
}
if (name.equals(".") || name.equals("..") || name.equals("./")
|| name.equals("../"))
{
continue;
}
FileObject fo =
getFileSystem()
.resolveFile(
getFileSystem().getFileSystemManager().resolveName(
getName(), UriParser.encode(name),
NameScope.CHILD));
((SftpFileObject) FileObjectUtils.getAbstractFileObject(fo)).setStat(stat.getAttrs());
children.add(fo);
}
return children.toArray(new FileObject[children.size()]);
}
|
diff --git a/flex-pmd-maven-plugin/src/main/java/com/adobe/ac/pmd/maven/FlexPmdHtmlEngine.java b/flex-pmd-maven-plugin/src/main/java/com/adobe/ac/pmd/maven/FlexPmdHtmlEngine.java
index 3d1b82af..4286a3e1 100644
--- a/flex-pmd-maven-plugin/src/main/java/com/adobe/ac/pmd/maven/FlexPmdHtmlEngine.java
+++ b/flex-pmd-maven-plugin/src/main/java/com/adobe/ac/pmd/maven/FlexPmdHtmlEngine.java
@@ -1,134 +1,135 @@
/**
* Copyright (c) 2008. Adobe Systems Incorporated.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Adobe Systems Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.ac.pmd.maven;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;
import net.sourceforge.pmd.PMDException;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.renderers.HTMLRenderer;
import org.apache.maven.plugin.pmd.PmdFileInfo;
import org.apache.maven.plugin.pmd.PmdReportListener;
import org.apache.maven.project.MavenProject;
import org.codehaus.doxia.sink.Sink;
import com.adobe.ac.pmd.FlexPmdViolations;
import com.adobe.ac.pmd.IFlexViolation;
import com.adobe.ac.pmd.engines.AbstractFlexPmdEngine;
import com.adobe.ac.pmd.engines.FlexPMDFormat;
import com.adobe.ac.pmd.files.IFlexFile;
public class FlexPmdHtmlEngine extends AbstractFlexPmdEngine
{
private final boolean aggregate;
private final ResourceBundle bundle;
private final MavenProject project;
private final Sink sink;
public FlexPmdHtmlEngine( final Sink sinkToBeSet,
final ResourceBundle bundleToBeSet,
final boolean aggregateToBeSet,
final MavenProject projectToBeSet )
{
super();
sink = sinkToBeSet;
bundle = bundleToBeSet;
aggregate = aggregateToBeSet;
project = projectToBeSet;
}
@Override
protected final void writeReport( final FlexPmdViolations pmd,
final File outputDirectory ) throws PMDException
{
writeReport( outputDirectory,
computeReport( pmd ) );
}
private Report computeReport( final FlexPmdViolations pmd )
{
final Report report = new Report();
final RuleContext ruleContext = new RuleContext();
final PmdReportListener reportSink = new PmdReportListener( sink, bundle, aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
report.start();
for ( final IFlexFile file : pmd.getViolations().keySet() )
{
final File javaFile = new File( file.getFilePath() );
final List< IFlexViolation > violations = pmd.getViolations().get( file );
reportSink.beginFile( javaFile,
new PmdFileInfo( project, javaFile.getParentFile(), "" ) );
ruleContext.setSourceCodeFilename( javaFile.getAbsolutePath() );
for ( final IFlexViolation violation : violations )
{
+ report.addRuleViolation( violation );
reportSink.ruleViolationAdded( violation );
}
reportSink.endFile( javaFile );
}
reportSink.endDocument();
report.end();
return report;
}
private void writeReport( final File outputDirectory,
final Report report ) throws PMDException
{
final HTMLRenderer renderer = new HTMLRenderer( "", "" );
try
{
renderer.render( new FileWriter( new File( outputDirectory.getAbsolutePath()
+ "/" + FlexPMDFormat.HTML.toString() ) ),
report );
renderer.getWriter().flush();
renderer.getWriter().close();
}
catch ( final IOException e )
{
throw new PMDException( "unable to write the HTML report", e );
}
}
}
| true | true | private Report computeReport( final FlexPmdViolations pmd )
{
final Report report = new Report();
final RuleContext ruleContext = new RuleContext();
final PmdReportListener reportSink = new PmdReportListener( sink, bundle, aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
report.start();
for ( final IFlexFile file : pmd.getViolations().keySet() )
{
final File javaFile = new File( file.getFilePath() );
final List< IFlexViolation > violations = pmd.getViolations().get( file );
reportSink.beginFile( javaFile,
new PmdFileInfo( project, javaFile.getParentFile(), "" ) );
ruleContext.setSourceCodeFilename( javaFile.getAbsolutePath() );
for ( final IFlexViolation violation : violations )
{
reportSink.ruleViolationAdded( violation );
}
reportSink.endFile( javaFile );
}
reportSink.endDocument();
report.end();
return report;
}
| private Report computeReport( final FlexPmdViolations pmd )
{
final Report report = new Report();
final RuleContext ruleContext = new RuleContext();
final PmdReportListener reportSink = new PmdReportListener( sink, bundle, aggregate );
report.addListener( reportSink );
ruleContext.setReport( report );
reportSink.beginDocument();
report.start();
for ( final IFlexFile file : pmd.getViolations().keySet() )
{
final File javaFile = new File( file.getFilePath() );
final List< IFlexViolation > violations = pmd.getViolations().get( file );
reportSink.beginFile( javaFile,
new PmdFileInfo( project, javaFile.getParentFile(), "" ) );
ruleContext.setSourceCodeFilename( javaFile.getAbsolutePath() );
for ( final IFlexViolation violation : violations )
{
report.addRuleViolation( violation );
reportSink.ruleViolationAdded( violation );
}
reportSink.endFile( javaFile );
}
reportSink.endDocument();
report.end();
return report;
}
|
diff --git a/table-import-impl/src/main/java/org/cytoscape/tableimport/internal/CyActivator.java b/table-import-impl/src/main/java/org/cytoscape/tableimport/internal/CyActivator.java
index da25262d2..6ace8e2ee 100644
--- a/table-import-impl/src/main/java/org/cytoscape/tableimport/internal/CyActivator.java
+++ b/table-import-impl/src/main/java/org/cytoscape/tableimport/internal/CyActivator.java
@@ -1,136 +1,136 @@
package org.cytoscape.tableimport.internal;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.property.CyProperty;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.io.util.StreamUtil;
import org.cytoscape.session.CyNetworkNaming;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.property.bookmark.BookmarksUtil;
import org.cytoscape.model.CyTableManager;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.work.swing.DialogTaskManager;
import org.cytoscape.work.swing.GUITunableHandlerFactory;
import org.cytoscape.model.CyTableFactory;
import org.cytoscape.util.swing.FileUtil;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.util.swing.OpenBrowser;
import org.cytoscape.tableimport.internal.ImportAttributeTableReaderFactory;
import static org.cytoscape.io.DataCategory.*;
import org.cytoscape.tableimport.internal.ImportNetworkTableReaderFactory;
import org.cytoscape.tableimport.internal.task.ImportOntologyAndAnnotationAction;
import org.cytoscape.tableimport.internal.tunable.AttributeMappingParametersHandlerFactory;
import org.cytoscape.tableimport.internal.tunable.NetworkTableMappingParametersHandlerFactory;
import org.cytoscape.io.BasicCyFileFilter;
import org.cytoscape.tableimport.internal.reader.ontology.OBONetworkReaderFactory;
import org.cytoscape.tableimport.internal.ui.ImportTablePanel;
import org.cytoscape.tableimport.internal.util.CytoscapeServices;
import org.cytoscape.io.read.InputStreamTaskFactory;
import org.cytoscape.application.swing.CyAction;
import org.osgi.framework.BundleContext;
import org.cytoscape.service.util.AbstractCyActivator;
import java.io.InputStream;
import java.util.Properties;
public class CyActivator extends AbstractCyActivator {
public CyActivator() {
super();
}
public void start(BundleContext bc) {
CytoscapeServices.cyLayouts = getService(bc,CyLayoutAlgorithmManager.class);
CytoscapeServices.cyNetworkFactory = getService(bc,CyNetworkFactory.class);
CytoscapeServices.cyRootNetworkFactory = getService(bc,CyRootNetworkManager.class);
CytoscapeServices.cyNetworkViewFactory = getService(bc,CyNetworkViewFactory.class);
CytoscapeServices.cySwingApplication = getService(bc,CySwingApplication.class);
CytoscapeServices.cyApplicationManager = getService(bc,CyApplicationManager.class);
CytoscapeServices.cyNetworkManager = getService(bc,CyNetworkManager.class);
CytoscapeServices.cyTableManager = getService(bc,CyTableManager.class);
CytoscapeServices.dialogTaskManager = getService(bc,DialogTaskManager.class);
CytoscapeServices.bookmark = getService(bc,CyProperty.class,"(cyPropertyName=bookmarks)");
CytoscapeServices.bookmarksUtil = getService(bc,BookmarksUtil.class);
CytoscapeServices.cyProperties = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CytoscapeServices.fileUtil = getService(bc,FileUtil.class);
CytoscapeServices.openBrowser = getService(bc,OpenBrowser.class);
CytoscapeServices.cyNetworkNaming = getService(bc,CyNetworkNaming.class);
CytoscapeServices.cyNetworkViewManager = getService(bc,CyNetworkViewManager.class);
CytoscapeServices.cyTableFactory = getService(bc,CyTableFactory.class);
CytoscapeServices.streamUtil = getService(bc,StreamUtil.class);
CytoscapeServices.cyEventHelper = getService(bc,CyEventHelper.class);
- BasicCyFileFilter attrsTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt", "tab", "net"}, new String[]{"text/plain","text/tab-separated-values"},"Comma or Tab Separated Value Files",TABLE,CytoscapeServices.streamUtil);
+ BasicCyFileFilter attrsTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt", "tab", "net"}, new String[]{"text/csv","text/plain","text/tab-separated-values"},"Comma or Tab Separated Value Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter attrsTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter oboFilter = new BasicCyFileFilter(new String[]{"obo"}, new String[]{"text/obo"},"OBO Files",NETWORK,CytoscapeServices.streamUtil);
OBONetworkReaderFactory oboReaderFactory = new OBONetworkReaderFactory(oboFilter);
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_txt = new ImportAttributeTableReaderFactory(attrsTableFilter_txt); //,".txt");
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_xls = new ImportAttributeTableReaderFactory(attrsTableFilter_xls); //,".xls");
ImportOntologyAndAnnotationAction ontologyAction = new ImportOntologyAndAnnotationAction(oboReaderFactory);
BasicCyFileFilter networkTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt"}, new String[]{"text/csv","text/tab-separated-values"},"Comma or Tab Separated Value Files",NETWORK,CytoscapeServices.streamUtil);
BasicCyFileFilter networkTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",NETWORK,CytoscapeServices.streamUtil);
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_txt = new ImportNetworkTableReaderFactory(networkTableFilter_txt);//, "txt");
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_xls = new ImportNetworkTableReaderFactory(networkTableFilter_xls); //,".xls");
Properties importAttributeTableReaderFactory_xlsProps = new Properties();
importAttributeTableReaderFactory_xlsProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_xlsProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_xlsProps.setProperty("readerId","attributeTableReader");
registerService(bc,importAttributeTableReaderFactory_xls,InputStreamTaskFactory.class, importAttributeTableReaderFactory_xlsProps);
Properties importAttributeTableReaderFactory_txtProps = new Properties();
importAttributeTableReaderFactory_txtProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_txtProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_txtProps.setProperty("readerId","attributeTableReader_txt");
registerService(bc,importAttributeTableReaderFactory_txt,InputStreamTaskFactory.class, importAttributeTableReaderFactory_txtProps);
Properties oboReaderFactoryProps = new Properties();
oboReaderFactoryProps.setProperty("serviceType","oboReaderFactory");
oboReaderFactoryProps.setProperty("readerDescription","Open Biomedical Ontology (OBO) file reader");
oboReaderFactoryProps.setProperty("readerId","oboReader");
registerService(bc,oboReaderFactory,InputStreamTaskFactory.class, oboReaderFactoryProps);
registerService(bc,ontologyAction,CyAction.class, new Properties());
Properties importNetworkTableReaderFactory_txtProps = new Properties();
importNetworkTableReaderFactory_txtProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_txtProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_txtProps.setProperty("readerId","networkTableReader_txt");
registerService(bc,importNetworkTableReaderFactory_txt,InputStreamTaskFactory.class, importNetworkTableReaderFactory_txtProps);
Properties importNetworkTableReaderFactory_xlsProps = new Properties();
importNetworkTableReaderFactory_xlsProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_xlsProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_xlsProps.setProperty("readerId","networkTableReader_xls");
registerService(bc,importNetworkTableReaderFactory_xls,InputStreamTaskFactory.class, importNetworkTableReaderFactory_xlsProps);
int dialogTypeAttribute = ImportTablePanel.SIMPLE_ATTRIBUTE_IMPORT;
CyTableManager tableManager= CytoscapeServices.cyTableManager;
AttributeMappingParametersHandlerFactory attributeMappingParametersHandlerFactory = new AttributeMappingParametersHandlerFactory(dialogTypeAttribute, tableManager);
registerService(bc,attributeMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
int dialogTypeNetwork = ImportTablePanel.NETWORK_IMPORT;
CyTableManager tableManagerNetwork= CytoscapeServices.cyTableManager;
NetworkTableMappingParametersHandlerFactory networkTableMappingParametersHandlerFactory = new NetworkTableMappingParametersHandlerFactory(dialogTypeNetwork, tableManagerNetwork);
registerService(bc,networkTableMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
}
}
| true | true | public void start(BundleContext bc) {
CytoscapeServices.cyLayouts = getService(bc,CyLayoutAlgorithmManager.class);
CytoscapeServices.cyNetworkFactory = getService(bc,CyNetworkFactory.class);
CytoscapeServices.cyRootNetworkFactory = getService(bc,CyRootNetworkManager.class);
CytoscapeServices.cyNetworkViewFactory = getService(bc,CyNetworkViewFactory.class);
CytoscapeServices.cySwingApplication = getService(bc,CySwingApplication.class);
CytoscapeServices.cyApplicationManager = getService(bc,CyApplicationManager.class);
CytoscapeServices.cyNetworkManager = getService(bc,CyNetworkManager.class);
CytoscapeServices.cyTableManager = getService(bc,CyTableManager.class);
CytoscapeServices.dialogTaskManager = getService(bc,DialogTaskManager.class);
CytoscapeServices.bookmark = getService(bc,CyProperty.class,"(cyPropertyName=bookmarks)");
CytoscapeServices.bookmarksUtil = getService(bc,BookmarksUtil.class);
CytoscapeServices.cyProperties = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CytoscapeServices.fileUtil = getService(bc,FileUtil.class);
CytoscapeServices.openBrowser = getService(bc,OpenBrowser.class);
CytoscapeServices.cyNetworkNaming = getService(bc,CyNetworkNaming.class);
CytoscapeServices.cyNetworkViewManager = getService(bc,CyNetworkViewManager.class);
CytoscapeServices.cyTableFactory = getService(bc,CyTableFactory.class);
CytoscapeServices.streamUtil = getService(bc,StreamUtil.class);
CytoscapeServices.cyEventHelper = getService(bc,CyEventHelper.class);
BasicCyFileFilter attrsTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt", "tab", "net"}, new String[]{"text/plain","text/tab-separated-values"},"Comma or Tab Separated Value Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter attrsTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter oboFilter = new BasicCyFileFilter(new String[]{"obo"}, new String[]{"text/obo"},"OBO Files",NETWORK,CytoscapeServices.streamUtil);
OBONetworkReaderFactory oboReaderFactory = new OBONetworkReaderFactory(oboFilter);
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_txt = new ImportAttributeTableReaderFactory(attrsTableFilter_txt); //,".txt");
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_xls = new ImportAttributeTableReaderFactory(attrsTableFilter_xls); //,".xls");
ImportOntologyAndAnnotationAction ontologyAction = new ImportOntologyAndAnnotationAction(oboReaderFactory);
BasicCyFileFilter networkTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt"}, new String[]{"text/csv","text/tab-separated-values"},"Comma or Tab Separated Value Files",NETWORK,CytoscapeServices.streamUtil);
BasicCyFileFilter networkTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",NETWORK,CytoscapeServices.streamUtil);
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_txt = new ImportNetworkTableReaderFactory(networkTableFilter_txt);//, "txt");
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_xls = new ImportNetworkTableReaderFactory(networkTableFilter_xls); //,".xls");
Properties importAttributeTableReaderFactory_xlsProps = new Properties();
importAttributeTableReaderFactory_xlsProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_xlsProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_xlsProps.setProperty("readerId","attributeTableReader");
registerService(bc,importAttributeTableReaderFactory_xls,InputStreamTaskFactory.class, importAttributeTableReaderFactory_xlsProps);
Properties importAttributeTableReaderFactory_txtProps = new Properties();
importAttributeTableReaderFactory_txtProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_txtProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_txtProps.setProperty("readerId","attributeTableReader_txt");
registerService(bc,importAttributeTableReaderFactory_txt,InputStreamTaskFactory.class, importAttributeTableReaderFactory_txtProps);
Properties oboReaderFactoryProps = new Properties();
oboReaderFactoryProps.setProperty("serviceType","oboReaderFactory");
oboReaderFactoryProps.setProperty("readerDescription","Open Biomedical Ontology (OBO) file reader");
oboReaderFactoryProps.setProperty("readerId","oboReader");
registerService(bc,oboReaderFactory,InputStreamTaskFactory.class, oboReaderFactoryProps);
registerService(bc,ontologyAction,CyAction.class, new Properties());
Properties importNetworkTableReaderFactory_txtProps = new Properties();
importNetworkTableReaderFactory_txtProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_txtProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_txtProps.setProperty("readerId","networkTableReader_txt");
registerService(bc,importNetworkTableReaderFactory_txt,InputStreamTaskFactory.class, importNetworkTableReaderFactory_txtProps);
Properties importNetworkTableReaderFactory_xlsProps = new Properties();
importNetworkTableReaderFactory_xlsProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_xlsProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_xlsProps.setProperty("readerId","networkTableReader_xls");
registerService(bc,importNetworkTableReaderFactory_xls,InputStreamTaskFactory.class, importNetworkTableReaderFactory_xlsProps);
int dialogTypeAttribute = ImportTablePanel.SIMPLE_ATTRIBUTE_IMPORT;
CyTableManager tableManager= CytoscapeServices.cyTableManager;
AttributeMappingParametersHandlerFactory attributeMappingParametersHandlerFactory = new AttributeMappingParametersHandlerFactory(dialogTypeAttribute, tableManager);
registerService(bc,attributeMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
int dialogTypeNetwork = ImportTablePanel.NETWORK_IMPORT;
CyTableManager tableManagerNetwork= CytoscapeServices.cyTableManager;
NetworkTableMappingParametersHandlerFactory networkTableMappingParametersHandlerFactory = new NetworkTableMappingParametersHandlerFactory(dialogTypeNetwork, tableManagerNetwork);
registerService(bc,networkTableMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
}
}
| public void start(BundleContext bc) {
CytoscapeServices.cyLayouts = getService(bc,CyLayoutAlgorithmManager.class);
CytoscapeServices.cyNetworkFactory = getService(bc,CyNetworkFactory.class);
CytoscapeServices.cyRootNetworkFactory = getService(bc,CyRootNetworkManager.class);
CytoscapeServices.cyNetworkViewFactory = getService(bc,CyNetworkViewFactory.class);
CytoscapeServices.cySwingApplication = getService(bc,CySwingApplication.class);
CytoscapeServices.cyApplicationManager = getService(bc,CyApplicationManager.class);
CytoscapeServices.cyNetworkManager = getService(bc,CyNetworkManager.class);
CytoscapeServices.cyTableManager = getService(bc,CyTableManager.class);
CytoscapeServices.dialogTaskManager = getService(bc,DialogTaskManager.class);
CytoscapeServices.bookmark = getService(bc,CyProperty.class,"(cyPropertyName=bookmarks)");
CytoscapeServices.bookmarksUtil = getService(bc,BookmarksUtil.class);
CytoscapeServices.cyProperties = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CytoscapeServices.fileUtil = getService(bc,FileUtil.class);
CytoscapeServices.openBrowser = getService(bc,OpenBrowser.class);
CytoscapeServices.cyNetworkNaming = getService(bc,CyNetworkNaming.class);
CytoscapeServices.cyNetworkViewManager = getService(bc,CyNetworkViewManager.class);
CytoscapeServices.cyTableFactory = getService(bc,CyTableFactory.class);
CytoscapeServices.streamUtil = getService(bc,StreamUtil.class);
CytoscapeServices.cyEventHelper = getService(bc,CyEventHelper.class);
BasicCyFileFilter attrsTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt", "tab", "net"}, new String[]{"text/csv","text/plain","text/tab-separated-values"},"Comma or Tab Separated Value Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter attrsTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",TABLE,CytoscapeServices.streamUtil);
BasicCyFileFilter oboFilter = new BasicCyFileFilter(new String[]{"obo"}, new String[]{"text/obo"},"OBO Files",NETWORK,CytoscapeServices.streamUtil);
OBONetworkReaderFactory oboReaderFactory = new OBONetworkReaderFactory(oboFilter);
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_txt = new ImportAttributeTableReaderFactory(attrsTableFilter_txt); //,".txt");
ImportAttributeTableReaderFactory importAttributeTableReaderFactory_xls = new ImportAttributeTableReaderFactory(attrsTableFilter_xls); //,".xls");
ImportOntologyAndAnnotationAction ontologyAction = new ImportOntologyAndAnnotationAction(oboReaderFactory);
BasicCyFileFilter networkTableFilter_txt = new BasicCyFileFilter(new String[]{"csv","tsv", "txt"}, new String[]{"text/csv","text/tab-separated-values"},"Comma or Tab Separated Value Files",NETWORK,CytoscapeServices.streamUtil);
BasicCyFileFilter networkTableFilter_xls = new BasicCyFileFilter(new String[]{"xls","xlsx"}, new String[]{"application/excel"},"Excel Files",NETWORK,CytoscapeServices.streamUtil);
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_txt = new ImportNetworkTableReaderFactory(networkTableFilter_txt);//, "txt");
ImportNetworkTableReaderFactory importNetworkTableReaderFactory_xls = new ImportNetworkTableReaderFactory(networkTableFilter_xls); //,".xls");
Properties importAttributeTableReaderFactory_xlsProps = new Properties();
importAttributeTableReaderFactory_xlsProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_xlsProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_xlsProps.setProperty("readerId","attributeTableReader");
registerService(bc,importAttributeTableReaderFactory_xls,InputStreamTaskFactory.class, importAttributeTableReaderFactory_xlsProps);
Properties importAttributeTableReaderFactory_txtProps = new Properties();
importAttributeTableReaderFactory_txtProps.setProperty("serviceType","importAttributeTableTaskFactory");
importAttributeTableReaderFactory_txtProps.setProperty("readerDescription","Attribute Table file reader");
importAttributeTableReaderFactory_txtProps.setProperty("readerId","attributeTableReader_txt");
registerService(bc,importAttributeTableReaderFactory_txt,InputStreamTaskFactory.class, importAttributeTableReaderFactory_txtProps);
Properties oboReaderFactoryProps = new Properties();
oboReaderFactoryProps.setProperty("serviceType","oboReaderFactory");
oboReaderFactoryProps.setProperty("readerDescription","Open Biomedical Ontology (OBO) file reader");
oboReaderFactoryProps.setProperty("readerId","oboReader");
registerService(bc,oboReaderFactory,InputStreamTaskFactory.class, oboReaderFactoryProps);
registerService(bc,ontologyAction,CyAction.class, new Properties());
Properties importNetworkTableReaderFactory_txtProps = new Properties();
importNetworkTableReaderFactory_txtProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_txtProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_txtProps.setProperty("readerId","networkTableReader_txt");
registerService(bc,importNetworkTableReaderFactory_txt,InputStreamTaskFactory.class, importNetworkTableReaderFactory_txtProps);
Properties importNetworkTableReaderFactory_xlsProps = new Properties();
importNetworkTableReaderFactory_xlsProps.setProperty("serviceType","importNetworkTableTaskFactory");
importNetworkTableReaderFactory_xlsProps.setProperty("readerDescription","Network Table file reader");
importNetworkTableReaderFactory_xlsProps.setProperty("readerId","networkTableReader_xls");
registerService(bc,importNetworkTableReaderFactory_xls,InputStreamTaskFactory.class, importNetworkTableReaderFactory_xlsProps);
int dialogTypeAttribute = ImportTablePanel.SIMPLE_ATTRIBUTE_IMPORT;
CyTableManager tableManager= CytoscapeServices.cyTableManager;
AttributeMappingParametersHandlerFactory attributeMappingParametersHandlerFactory = new AttributeMappingParametersHandlerFactory(dialogTypeAttribute, tableManager);
registerService(bc,attributeMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
int dialogTypeNetwork = ImportTablePanel.NETWORK_IMPORT;
CyTableManager tableManagerNetwork= CytoscapeServices.cyTableManager;
NetworkTableMappingParametersHandlerFactory networkTableMappingParametersHandlerFactory = new NetworkTableMappingParametersHandlerFactory(dialogTypeNetwork, tableManagerNetwork);
registerService(bc,networkTableMappingParametersHandlerFactory,GUITunableHandlerFactory.class, new Properties());
}
}
|
diff --git a/src/main/java/de/preusslerpark/android/tools/Converter.java b/src/main/java/de/preusslerpark/android/tools/Converter.java
index 1d1c599..39633b7 100644
--- a/src/main/java/de/preusslerpark/android/tools/Converter.java
+++ b/src/main/java/de/preusslerpark/android/tools/Converter.java
@@ -1,140 +1,140 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.preusslerpark.android.tools;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.InstrumentationResultParser;
import com.android.ddmlib.testrunner.TestIdentifier;
public class Converter {
private final String testSuiteName;
private final String outPath;
public static Converter createConverForFile(String testSuiteName, String outPath) {
return new Converter(testSuiteName, outPath, true);
}
public static Converter createConverForPath(String testSuiteName, String outPath) {
return new Converter(testSuiteName, outPath, false);
}
private Converter(String testSuiteName, String outPath, boolean isFilename) {
this.testSuiteName = testSuiteName;
this.outPath = isFilename ? outPath : outPath + testSuiteName + ".xml";
}
public void convert(String streamToRead) throws FileNotFoundException, IOException {
FileOutputStream currentFile = new FileOutputStream(outPath);
final XMLResultFormatter outputter = new XMLResultFormatter();
InstrumentationResultParser parser = createParser(testSuiteName, outputter);
outputter.setOutput(currentFile);
outputter.startTestSuite(testSuiteName);
String[] lines = streamToRead.split("\n");;
parser.processNewLines(lines);
parser.done();
outputter.endTestSuite(testSuiteName, 0);
currentFile.close();
}
private InstrumentationResultParser createParser(String testSuite, final XMLResultFormatter outputter) {
ITestRunListener listener = new ITestRunListener() {
@Override
public void testEnded(TestIdentifier test, Map<String, String> arg1) {
System.out.println("testEnded " + test);
outputter.endTest(test);
}
@Override
public void testFailed(TestFailure arg0, TestIdentifier test, String arg2) {
System.out.println("testFailed " + arg0 + "/" + arg2);
BufferedReader reader = new BufferedReader(new StringReader(arg2));
try {
String error = reader.readLine();
- String[] errorSeperated = error.split(":");
+ String[] errorSeperated = error.split(":", 2);
outputter.addFailure(test, errorSeperated.length > 1 ? errorSeperated[1].trim() : "Failed", errorSeperated[0].trim(), arg2.substring(error.length()));
} catch (IOException e) {
e.printStackTrace();
outputter.addFailure(test, e);
}
}
@Override
public void testRunEnded(long elapsedTime, Map<String, String> arg1) {
// System.out.println("testRunEnded " + elapsedTime + "/" + arg1);
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testRunFailed(String name) {
System.out.println("testRunFailed " + name);
// outputter.endTestSuite(name, 0);
}
@Override
public void testRunStarted(String name, int arg1) {
// System.out.println("testRunStarted " + name + "/" + arg1);
// if (name.equals(currentSuite)) {
// name = name + "1";
// }
// currentSuite = name;
// try {
// if (currentFile != null) {
// currentFile.close();
// }
// currentFile = new FileOutputStream(outPath + currentSuite + ".xml");
// }
// catch (IOException e) {
// }
//
// outputter.setOutput(currentFile);
// outputter.startTestSuite(currentSuite);
}
@Override
public void testRunStopped(long elapsedTime) {
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testStarted(final TestIdentifier test) {
System.out.println("testStarted " + test.toString());
outputter.startTest(test);
}
};
return new InstrumentationResultParser(testSuite, listener);
}
}
| true | true | private InstrumentationResultParser createParser(String testSuite, final XMLResultFormatter outputter) {
ITestRunListener listener = new ITestRunListener() {
@Override
public void testEnded(TestIdentifier test, Map<String, String> arg1) {
System.out.println("testEnded " + test);
outputter.endTest(test);
}
@Override
public void testFailed(TestFailure arg0, TestIdentifier test, String arg2) {
System.out.println("testFailed " + arg0 + "/" + arg2);
BufferedReader reader = new BufferedReader(new StringReader(arg2));
try {
String error = reader.readLine();
String[] errorSeperated = error.split(":");
outputter.addFailure(test, errorSeperated.length > 1 ? errorSeperated[1].trim() : "Failed", errorSeperated[0].trim(), arg2.substring(error.length()));
} catch (IOException e) {
e.printStackTrace();
outputter.addFailure(test, e);
}
}
@Override
public void testRunEnded(long elapsedTime, Map<String, String> arg1) {
// System.out.println("testRunEnded " + elapsedTime + "/" + arg1);
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testRunFailed(String name) {
System.out.println("testRunFailed " + name);
// outputter.endTestSuite(name, 0);
}
@Override
public void testRunStarted(String name, int arg1) {
// System.out.println("testRunStarted " + name + "/" + arg1);
// if (name.equals(currentSuite)) {
// name = name + "1";
// }
// currentSuite = name;
// try {
// if (currentFile != null) {
// currentFile.close();
// }
// currentFile = new FileOutputStream(outPath + currentSuite + ".xml");
// }
// catch (IOException e) {
// }
//
// outputter.setOutput(currentFile);
// outputter.startTestSuite(currentSuite);
}
@Override
public void testRunStopped(long elapsedTime) {
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testStarted(final TestIdentifier test) {
System.out.println("testStarted " + test.toString());
outputter.startTest(test);
}
};
return new InstrumentationResultParser(testSuite, listener);
}
| private InstrumentationResultParser createParser(String testSuite, final XMLResultFormatter outputter) {
ITestRunListener listener = new ITestRunListener() {
@Override
public void testEnded(TestIdentifier test, Map<String, String> arg1) {
System.out.println("testEnded " + test);
outputter.endTest(test);
}
@Override
public void testFailed(TestFailure arg0, TestIdentifier test, String arg2) {
System.out.println("testFailed " + arg0 + "/" + arg2);
BufferedReader reader = new BufferedReader(new StringReader(arg2));
try {
String error = reader.readLine();
String[] errorSeperated = error.split(":", 2);
outputter.addFailure(test, errorSeperated.length > 1 ? errorSeperated[1].trim() : "Failed", errorSeperated[0].trim(), arg2.substring(error.length()));
} catch (IOException e) {
e.printStackTrace();
outputter.addFailure(test, e);
}
}
@Override
public void testRunEnded(long elapsedTime, Map<String, String> arg1) {
// System.out.println("testRunEnded " + elapsedTime + "/" + arg1);
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testRunFailed(String name) {
System.out.println("testRunFailed " + name);
// outputter.endTestSuite(name, 0);
}
@Override
public void testRunStarted(String name, int arg1) {
// System.out.println("testRunStarted " + name + "/" + arg1);
// if (name.equals(currentSuite)) {
// name = name + "1";
// }
// currentSuite = name;
// try {
// if (currentFile != null) {
// currentFile.close();
// }
// currentFile = new FileOutputStream(outPath + currentSuite + ".xml");
// }
// catch (IOException e) {
// }
//
// outputter.setOutput(currentFile);
// outputter.startTestSuite(currentSuite);
}
@Override
public void testRunStopped(long elapsedTime) {
// outputter.endTestSuite(currentSuite, elapsedTime);
}
@Override
public void testStarted(final TestIdentifier test) {
System.out.println("testStarted " + test.toString());
outputter.startTest(test);
}
};
return new InstrumentationResultParser(testSuite, listener);
}
|
diff --git a/src/main/java/ltg/ps/phenomena/wallcology/population_calculators/PopulationCalculator.java b/src/main/java/ltg/ps/phenomena/wallcology/population_calculators/PopulationCalculator.java
index e0e7a01..01cce7c 100644
--- a/src/main/java/ltg/ps/phenomena/wallcology/population_calculators/PopulationCalculator.java
+++ b/src/main/java/ltg/ps/phenomena/wallcology/population_calculators/PopulationCalculator.java
@@ -1,64 +1,65 @@
package ltg.ps.phenomena.wallcology.population_calculators;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ltg.ps.phenomena.wallcology.Wall;
import ltg.ps.phenomena.wallcology.WallcologyPhase;
public abstract class PopulationCalculator {
// Logger
protected final Logger log = LoggerFactory.getLogger(this.getClass());
// Noise amount
public static final double noisePercent = 0.02;
/**
*
* TODO Description
*
* @param currentPhaseWalls
* @param currentPhase
*/
abstract public void updatePopulationStable(List<Wall> currentPhaseWalls, WallcologyPhase currentPhase);
/**
*
* TODO Description
*
* @param nextPhase
* @param walls
* @param prevPhaseWalls
* @param nextPhaseWalls
* @param totTransTime
* @param elapsedTransTime
*/
abstract public void updatePopulationTransit(WallcologyPhase nextPhase, List<Wall> walls, List<Wall> prevPhaseWalls, List<Wall> nextPhaseWalls, long totTransTime, long elapsedTransTime);
/**
* TODO Description
*
* @param ca
* @return
*/
protected int[] addNoise(int[] ca) {
// Randomize +/- noisePercent
double dev;
int[] ra = new int[ca.length];
for(int i=0; i< ca.length; i++) {
dev = Math.round(Math.random()*((double)ca[i])*noisePercent);
- if (dev < 1) dev = 1; // This makes sure that the deviation is always at least one
+ // Make sure that the deviation is always at least one for all creatures that are not 0
+ if (dev < 1 && ca[i] != 0) dev = 1;
if(Math.random()<.5) {
ra[i] = ca[i] + (int)dev;
} else {
ra[i] = ca[i] - (int)dev;
}
}
return ra;
}
}
| true | true | protected int[] addNoise(int[] ca) {
// Randomize +/- noisePercent
double dev;
int[] ra = new int[ca.length];
for(int i=0; i< ca.length; i++) {
dev = Math.round(Math.random()*((double)ca[i])*noisePercent);
if (dev < 1) dev = 1; // This makes sure that the deviation is always at least one
if(Math.random()<.5) {
ra[i] = ca[i] + (int)dev;
} else {
ra[i] = ca[i] - (int)dev;
}
}
return ra;
}
| protected int[] addNoise(int[] ca) {
// Randomize +/- noisePercent
double dev;
int[] ra = new int[ca.length];
for(int i=0; i< ca.length; i++) {
dev = Math.round(Math.random()*((double)ca[i])*noisePercent);
// Make sure that the deviation is always at least one for all creatures that are not 0
if (dev < 1 && ca[i] != 0) dev = 1;
if(Math.random()<.5) {
ra[i] = ca[i] + (int)dev;
} else {
ra[i] = ca[i] - (int)dev;
}
}
return ra;
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelScopeParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelScopeParticipant.java
index e8caf288b..7dfee9b14 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelScopeParticipant.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelScopeParticipant.java
@@ -1,186 +1,188 @@
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ui.mapping;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.mapping.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.team.core.mapping.*;
import org.eclipse.team.internal.ui.TeamUIPlugin;
import org.eclipse.team.internal.ui.Utils;
import org.eclipse.ui.*;
public class ResourceModelScopeParticipant implements
ISynchronizationScopeParticipant, IResourceChangeListener, IPropertyChangeListener {
private final ModelProvider provider;
private final ISynchronizationScope scope;
public ResourceModelScopeParticipant(ModelProvider provider, ISynchronizationScope scope) {
this.provider = provider;
this.scope = scope;
if (hasWorkspaceMapping()) {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
if (hasWorkingSetMappings()) {
PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(this);
}
}
private boolean hasWorkingSetMappings() {
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
Object modelObject = mapping.getModelObject();
if (modelObject instanceof IWorkingSet) {
return true;
}
}
return false;
}
private boolean hasWorkspaceMapping() {
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
Object modelObject = mapping.getModelObject();
if (modelObject instanceof IResource) {
IResource resource = (IResource) modelObject;
if (resource.getType() == IResource.ROOT) {
return true;
}
}
}
return false;
}
public ResourceMapping[] handleContextChange(
ISynchronizationScope scope, IResource[] resources,
IProject[] projects) {
Set result = new HashSet();
for (int i = 0; i < projects.length; i++) {
IProject project = projects[i];
collectMappings(project, result);
}
return (ResourceMapping[]) result.toArray(new ResourceMapping[result.size()]);
}
private void collectMappings(IProject project, Set result) {
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
boolean refresh = false;
Object modelObject = mapping.getModelObject();
if (modelObject instanceof IWorkingSet) {
IWorkingSet set = (IWorkingSet)modelObject;
IAdaptable[] elements = set.getElements();
for (int j = 0; j < elements.length; j++) {
IAdaptable adaptable = elements[j];
ResourceMapping m = (ResourceMapping)Utils.getAdapter(adaptable, ResourceMapping.class);
- IProject[] p = m.getProjects();
- for (int k = 0; k < p.length; k++) {
- IProject mp = p[k];
- if (mp.equals(project)) {
- refresh = true;
- break;
+ if (m != null) {
+ IProject[] p = m.getProjects();
+ for (int k = 0; k < p.length; k++) {
+ IProject mp = p[k];
+ if (mp.equals(project)) {
+ refresh = true;
+ break;
+ }
}
}
if (refresh)
break;
}
} else if (modelObject instanceof IResource) {
IResource resource = (IResource) modelObject;
if (resource.getType() == IResource.ROOT) {
refresh = true;
}
} else if (modelObject instanceof ModelProvider) {
ModelProvider mp = (ModelProvider) modelObject;
try {
ResourceMapping[] list = mp.getMappings(project, ResourceMappingContext.LOCAL_CONTEXT, null);
if (list.length > 0) {
refresh = true;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
}
}
if (refresh) {
result.add(mapping);
}
}
}
public void dispose() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(this);
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
*/
public void resourceChanged(IResourceChangeEvent event) {
// Only interested in project additions and removals
Set result = new HashSet();
IResourceDelta[] children = event.getDelta().getAffectedChildren();
for (int i = 0; i < children.length; i++) {
IResourceDelta delta = children[i];
IResource resource = delta.getResource();
if (resource.getType() == IResource.PROJECT
&& ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.REMOVED)) != 0
|| (delta.getFlags() & IResourceDelta.OPEN) != 0)) {
if (isInContext(resource))
collectMappings((IProject)resource, result);
}
}
if (!result.isEmpty())
fireChange((ResourceMapping[]) result.toArray(new ResourceMapping[result.size()]));
}
private boolean isInContext(IResource resource) {
IProject[] projects = scope.getProjects();
for (int i = 0; i < projects.length; i++) {
IProject project = projects[i];
if (project.equals(resource.getProject())) {
return true;
}
}
return false;
}
private void fireChange(ResourceMapping[] mappings) {
scope.refresh(mappings);
}
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty() == IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE) {
IWorkingSet newSet = (IWorkingSet) event.getNewValue();
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
if (newSet == mapping.getModelObject()) {
fireChange(new ResourceMapping[] { mapping });
}
}
} else if(event.getProperty() == IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE) {
// TODO: Need to update the participant description somehow
//firePropertyChangedEvent(new PropertyChangeEvent(this, NAME, null, event.getNewValue()));
}
}
}
| true | true | private void collectMappings(IProject project, Set result) {
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
boolean refresh = false;
Object modelObject = mapping.getModelObject();
if (modelObject instanceof IWorkingSet) {
IWorkingSet set = (IWorkingSet)modelObject;
IAdaptable[] elements = set.getElements();
for (int j = 0; j < elements.length; j++) {
IAdaptable adaptable = elements[j];
ResourceMapping m = (ResourceMapping)Utils.getAdapter(adaptable, ResourceMapping.class);
IProject[] p = m.getProjects();
for (int k = 0; k < p.length; k++) {
IProject mp = p[k];
if (mp.equals(project)) {
refresh = true;
break;
}
}
if (refresh)
break;
}
} else if (modelObject instanceof IResource) {
IResource resource = (IResource) modelObject;
if (resource.getType() == IResource.ROOT) {
refresh = true;
}
} else if (modelObject instanceof ModelProvider) {
ModelProvider mp = (ModelProvider) modelObject;
try {
ResourceMapping[] list = mp.getMappings(project, ResourceMappingContext.LOCAL_CONTEXT, null);
if (list.length > 0) {
refresh = true;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
}
}
if (refresh) {
result.add(mapping);
}
}
}
| private void collectMappings(IProject project, Set result) {
ResourceMapping[] mappings = scope.getMappings(provider.getDescriptor().getId());
for (int i = 0; i < mappings.length; i++) {
ResourceMapping mapping = mappings[i];
boolean refresh = false;
Object modelObject = mapping.getModelObject();
if (modelObject instanceof IWorkingSet) {
IWorkingSet set = (IWorkingSet)modelObject;
IAdaptable[] elements = set.getElements();
for (int j = 0; j < elements.length; j++) {
IAdaptable adaptable = elements[j];
ResourceMapping m = (ResourceMapping)Utils.getAdapter(adaptable, ResourceMapping.class);
if (m != null) {
IProject[] p = m.getProjects();
for (int k = 0; k < p.length; k++) {
IProject mp = p[k];
if (mp.equals(project)) {
refresh = true;
break;
}
}
}
if (refresh)
break;
}
} else if (modelObject instanceof IResource) {
IResource resource = (IResource) modelObject;
if (resource.getType() == IResource.ROOT) {
refresh = true;
}
} else if (modelObject instanceof ModelProvider) {
ModelProvider mp = (ModelProvider) modelObject;
try {
ResourceMapping[] list = mp.getMappings(project, ResourceMappingContext.LOCAL_CONTEXT, null);
if (list.length > 0) {
refresh = true;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
}
}
if (refresh) {
result.add(mapping);
}
}
}
|
diff --git a/trunk/src/webcamstudio/sources/VideoSourceDesktop.java b/trunk/src/webcamstudio/sources/VideoSourceDesktop.java
index dee93cc..50f31c4 100644
--- a/trunk/src/webcamstudio/sources/VideoSourceDesktop.java
+++ b/trunk/src/webcamstudio/sources/VideoSourceDesktop.java
@@ -1,164 +1,164 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webcamstudio.sources;
import java.awt.AWTException;
import java.awt.Robot;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import webcamstudio.components.PreciseTimer;
import webcamstudio.controls.ControlDesktop;
/**
*
* @author pballeux
*/
public class VideoSourceDesktop extends VideoSource {
protected Robot robot = null;
protected int screenwidth = java.awt.MouseInfo.getPointerInfo().getDevice().getDisplayMode().getWidth();
protected int screenheight = java.awt.MouseInfo.getPointerInfo().getDevice().getDisplayMode().getHeight();
public VideoSourceDesktop() {
try {
robot = new Robot();
} catch (AWTException ex) {
Logger.getLogger(VideoSourceDesktop.class.getName()).log(Level.SEVERE, null, ex);
}
name = "Desktop";
location = name;
frameRate = 15;
showMouseCursor = true;
}
@Override
public void startSource() {
isPlaying = true;
stopMe = false;
new Thread(new imageDesktop(this), name).start();
}
public boolean canUpdateSource() {
return false;
}
@Override
public boolean isPlaying() {
return isPlaying;
}
@Override
public void pause() {
}
@Override
public void play() {
}
@Override
public boolean isPaused() {
return false;
}
@Override
public void stopSource() {
stopMe = true;
image = null;
isPlaying = false;
}
public boolean hasText() {
return false;
}
public String toString() {
return "Desktop: " + "(" + captureAtX + "," + captureAtY + ":" + captureWidth + "x" + captureHeight + ")";
}
@Override
public java.util.Collection<JPanel> getControls() {
java.util.Vector<JPanel> list = new java.util.Vector<JPanel>();
list.add(new ControlDesktop(this));
list.add(new webcamstudio.controls.ControlShapes(this));
list.add(new webcamstudio.controls.ControlEffects(this));
list.add(new webcamstudio.controls.ControlActivity(this));
list.add(new webcamstudio.controls.ControlIdentity(this));
return list;
}
}
class imageDesktop implements Runnable {
private Robot robot = null;
VideoSourceDesktop desktop = null;
public imageDesktop(VideoSourceDesktop d) {
robot = d.robot;
desktop = d;
}
@Override
public void run() {
long timestamp = 0;
while (!desktop.stopMe) {
timestamp = System.currentTimeMillis();
if (desktop.getOutputWidth() == 0 && desktop.getOutputHeight() == 0) {
desktop.setOutputWidth(320);
desktop.setOutputHeight(240);
}
int x = 0;
int y = 0;
int mouseX = 0;
int mouseY = 0;
x = desktop.getCaptureAtX();
y = desktop.getCaptureAtY();
if (desktop.getImage() == null || (desktop.image.getWidth() != desktop.getCaptureWidth()) || (desktop.image.getHeight() != desktop.getCaptureHeight())) {
desktop.image = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(desktop.getCaptureWidth(), desktop.getCaptureHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB);
}
if (desktop.isFollowingMouse()) {
x = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - (desktop.getCaptureWidth() / 2);
y = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - (desktop.getCaptureHeight() / 2);
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > (desktop.screenwidth - desktop.captureWidth)) {
x = desktop.screenwidth - desktop.captureWidth - 1;
}
if (y > (desktop.screenheight - desktop.captureHeight)) {
y = desktop.screenheight - desktop.captureHeight - 1;
}
desktop.captureAtX = x;
desktop.captureAtY = y;
if (robot != null) {
- desktop.tempimage = desktop.graphicConfiguration.createCompatibleImage(desktop.captureWidth, desktop.captureHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB);
+ desktop.tempimage = desktop.graphicConfiguration.createCompatibleImage(desktop.captureWidth, desktop.captureHeight, java.awt.image.BufferedImage.TRANSLUCENT);
java.awt.Graphics2D buffer = desktop.tempimage.createGraphics();
buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.0F));
buffer.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_DITHERING, java.awt.RenderingHints.VALUE_DITHER_ENABLE);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_COLOR_RENDERING, java.awt.RenderingHints.VALUE_COLOR_RENDER_QUALITY);
buffer.drawImage(robot.createScreenCapture(new java.awt.Rectangle(desktop.captureAtX, desktop.captureAtY, desktop.captureWidth, desktop.captureHeight)), 0, 0, desktop.captureWidth, desktop.captureHeight, null);
if (desktop.showMouseCursor) {
mouseX = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - desktop.captureAtX;
mouseY = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - desktop.captureAtY;
buffer.setXORMode(java.awt.Color.BLACK);
buffer.fillOval(mouseX, mouseY, 15, 15);
}
buffer.dispose();
desktop.detectActivity(desktop.tempimage);
desktop.applyEffects(desktop.tempimage);
desktop.applyShape(desktop.tempimage);
desktop.image = desktop.tempimage;
}
PreciseTimer.sleep(timestamp, 1000 / desktop.frameRate);
}
}
}
| true | true | public void run() {
long timestamp = 0;
while (!desktop.stopMe) {
timestamp = System.currentTimeMillis();
if (desktop.getOutputWidth() == 0 && desktop.getOutputHeight() == 0) {
desktop.setOutputWidth(320);
desktop.setOutputHeight(240);
}
int x = 0;
int y = 0;
int mouseX = 0;
int mouseY = 0;
x = desktop.getCaptureAtX();
y = desktop.getCaptureAtY();
if (desktop.getImage() == null || (desktop.image.getWidth() != desktop.getCaptureWidth()) || (desktop.image.getHeight() != desktop.getCaptureHeight())) {
desktop.image = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(desktop.getCaptureWidth(), desktop.getCaptureHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB);
}
if (desktop.isFollowingMouse()) {
x = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - (desktop.getCaptureWidth() / 2);
y = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - (desktop.getCaptureHeight() / 2);
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > (desktop.screenwidth - desktop.captureWidth)) {
x = desktop.screenwidth - desktop.captureWidth - 1;
}
if (y > (desktop.screenheight - desktop.captureHeight)) {
y = desktop.screenheight - desktop.captureHeight - 1;
}
desktop.captureAtX = x;
desktop.captureAtY = y;
if (robot != null) {
desktop.tempimage = desktop.graphicConfiguration.createCompatibleImage(desktop.captureWidth, desktop.captureHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB);
java.awt.Graphics2D buffer = desktop.tempimage.createGraphics();
buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.0F));
buffer.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_DITHERING, java.awt.RenderingHints.VALUE_DITHER_ENABLE);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_COLOR_RENDERING, java.awt.RenderingHints.VALUE_COLOR_RENDER_QUALITY);
buffer.drawImage(robot.createScreenCapture(new java.awt.Rectangle(desktop.captureAtX, desktop.captureAtY, desktop.captureWidth, desktop.captureHeight)), 0, 0, desktop.captureWidth, desktop.captureHeight, null);
if (desktop.showMouseCursor) {
mouseX = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - desktop.captureAtX;
mouseY = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - desktop.captureAtY;
buffer.setXORMode(java.awt.Color.BLACK);
buffer.fillOval(mouseX, mouseY, 15, 15);
}
buffer.dispose();
desktop.detectActivity(desktop.tempimage);
desktop.applyEffects(desktop.tempimage);
desktop.applyShape(desktop.tempimage);
desktop.image = desktop.tempimage;
}
PreciseTimer.sleep(timestamp, 1000 / desktop.frameRate);
}
}
| public void run() {
long timestamp = 0;
while (!desktop.stopMe) {
timestamp = System.currentTimeMillis();
if (desktop.getOutputWidth() == 0 && desktop.getOutputHeight() == 0) {
desktop.setOutputWidth(320);
desktop.setOutputHeight(240);
}
int x = 0;
int y = 0;
int mouseX = 0;
int mouseY = 0;
x = desktop.getCaptureAtX();
y = desktop.getCaptureAtY();
if (desktop.getImage() == null || (desktop.image.getWidth() != desktop.getCaptureWidth()) || (desktop.image.getHeight() != desktop.getCaptureHeight())) {
desktop.image = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(desktop.getCaptureWidth(), desktop.getCaptureHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB);
}
if (desktop.isFollowingMouse()) {
x = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - (desktop.getCaptureWidth() / 2);
y = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - (desktop.getCaptureHeight() / 2);
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > (desktop.screenwidth - desktop.captureWidth)) {
x = desktop.screenwidth - desktop.captureWidth - 1;
}
if (y > (desktop.screenheight - desktop.captureHeight)) {
y = desktop.screenheight - desktop.captureHeight - 1;
}
desktop.captureAtX = x;
desktop.captureAtY = y;
if (robot != null) {
desktop.tempimage = desktop.graphicConfiguration.createCompatibleImage(desktop.captureWidth, desktop.captureHeight, java.awt.image.BufferedImage.TRANSLUCENT);
java.awt.Graphics2D buffer = desktop.tempimage.createGraphics();
buffer.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.0F));
buffer.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_DITHERING, java.awt.RenderingHints.VALUE_DITHER_ENABLE);
buffer.setRenderingHint(java.awt.RenderingHints.KEY_COLOR_RENDERING, java.awt.RenderingHints.VALUE_COLOR_RENDER_QUALITY);
buffer.drawImage(robot.createScreenCapture(new java.awt.Rectangle(desktop.captureAtX, desktop.captureAtY, desktop.captureWidth, desktop.captureHeight)), 0, 0, desktop.captureWidth, desktop.captureHeight, null);
if (desktop.showMouseCursor) {
mouseX = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getX() - desktop.captureAtX;
mouseY = (int) java.awt.MouseInfo.getPointerInfo().getLocation().getY() - desktop.captureAtY;
buffer.setXORMode(java.awt.Color.BLACK);
buffer.fillOval(mouseX, mouseY, 15, 15);
}
buffer.dispose();
desktop.detectActivity(desktop.tempimage);
desktop.applyEffects(desktop.tempimage);
desktop.applyShape(desktop.tempimage);
desktop.image = desktop.tempimage;
}
PreciseTimer.sleep(timestamp, 1000 / desktop.frameRate);
}
}
|
diff --git a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java
index a40bf09294d..584fc0fa58e 100644
--- a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java
+++ b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java
@@ -1,1532 +1,1529 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.percolator;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.percolate.PercolateResponse;
import org.elasticsearch.action.percolate.PercolateSourceBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IgnoreIndices;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.ImmutableSettings.Builder;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.DocumentMissingException;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.factor.FactorBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;
import java.util.*;
import static org.elasticsearch.action.percolate.PercolateSourceBuilder.docBuilder;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import static org.elasticsearch.index.query.FilterBuilders.termFilter;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.*;
/**
*
*/
public class PercolatorTests extends ElasticsearchIntegrationTest {
@Test
public void testSimple1() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Add dummy doc");
client().prepareIndex("test", "type", "1").setSource("field", "value").execute().actionGet();
logger.info("--> register a queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Percolate doc with field1=b");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject()))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "4"));
logger.info("--> Percolate doc with field1=c");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(yamlBuilder().startObject().field("field1", "c").endObject()))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));
logger.info("--> Percolate doc with field1=b c");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(smileBuilder().startObject().field("field1", "b c").endObject()))
.execute().actionGet();
assertMatchCount(response, 4l);
assertThat(response.getMatches(), arrayWithSize(4));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4"));
logger.info("--> Percolate doc with field1=d");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "d").endObject()))
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("4"));
logger.info("--> Search dummy doc, percolate queries must not be included");
SearchResponse searchResponse = client().prepareSearch("test", "test").execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(1L));
assertThat(searchResponse.getHits().getAt(0).type(), equalTo("type"));
assertThat(searchResponse.getHits().getAt(0).id(), equalTo("1"));
logger.info("--> Percolate non existing doc");
try {
client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("5"))
.execute().actionGet();
fail("Exception should have been thrown");
} catch (DocumentMissingException e) {
}
}
@Test
public void testSimple2() throws Exception {
client().admin().indices().prepareCreate("index").setSettings(
ImmutableSettings.settingsBuilder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
.build()
).execute().actionGet();
client().admin().indices().prepareCreate("test").setSettings(
ImmutableSettings.settingsBuilder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 0)
.build()
).execute().actionGet();
ensureGreen();
// introduce the doc
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startObject("doc")
.field("field1", 1)
.field("field2", "value")
.endObject().endObject();
XContentBuilder docWithType = XContentFactory.jsonBuilder().startObject().startObject("doc").startObject("type1")
.field("field1", 1)
.field("field2", "value")
.endObject().endObject().endObject();
PercolateResponse response = client().preparePercolate().setSource(doc)
.setIndices("test").setDocumentType("type1")
.execute().actionGet();
assertMatchCount(response, 0l);
assertThat(response.getMatches(), emptyArray());
// add first query...
client().prepareIndex("test", PercolatorService.TYPE_NAME, "test1")
.setSource(XContentFactory.jsonBuilder().startObject().field("query", termQuery("field2", "value")).endObject())
.execute().actionGet();
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(doc).execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("test1"));
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(docWithType).execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("test1"));
// add second query...
client().prepareIndex("test", PercolatorService.TYPE_NAME, "test2")
.setSource(XContentFactory.jsonBuilder().startObject().field("query", termQuery("field1", 1)).endObject())
.execute().actionGet();
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(doc)
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("test1", "test2"));
client().prepareDelete("test", PercolatorService.TYPE_NAME, "test2").execute().actionGet();
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(doc).execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("test1"));
// add a range query (cached)
// add a query
client().prepareIndex("test1", PercolatorService.TYPE_NAME)
.setSource(
XContentFactory.jsonBuilder().startObject().field("query",
constantScoreQuery(FilterBuilders.rangeFilter("field2").from("value").includeLower(true))
).endObject()
)
.execute().actionGet();
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(doc).execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("test1"));
}
@Test
public void testPercolateQueriesWithRouting() throws Exception {
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
ensureGreen();
logger.info("--> register a queries");
for (int i = 1; i <= 100; i++) {
client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.setRouting(Integer.toString(i % 2))
.execute().actionGet();
}
logger.info("--> Percolate doc with no routing");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 100l);
assertThat(response.getMatches(), arrayWithSize(100));
logger.info("--> Percolate doc with routing=0");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.setRouting("0")
.execute().actionGet();
assertMatchCount(response, 50l);
assertThat(response.getMatches(), arrayWithSize(50));
logger.info("--> Percolate doc with routing=1");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.setRouting("1")
.execute().actionGet();
assertMatchCount(response, 50l);
assertThat(response.getMatches(), arrayWithSize(50));
}
@Test
public void percolateOnRecreatedIndex() throws Exception {
prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute().actionGet();
ensureGreen();
client().prepareIndex("test", "test", "1").setSource("field1", "value1").execute().actionGet();
logger.info("--> register a query");
client().prepareIndex("my-queries-index", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.execute().actionGet();
wipeIndices("test");
prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute().actionGet();
ensureGreen();
client().prepareIndex("test", "test", "1").setSource("field1", "value1").execute().actionGet();
logger.info("--> register a query");
client().prepareIndex("my-queries-index", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.execute().actionGet();
}
@Test
// see #2814
public void percolateCustomAnalyzer() throws Exception {
Builder builder = ImmutableSettings.builder();
builder.put("index.analysis.analyzer.lwhitespacecomma.tokenizer", "whitespacecomma");
builder.putArray("index.analysis.analyzer.lwhitespacecomma.filter", "lowercase");
builder.put("index.analysis.tokenizer.whitespacecomma.type", "pattern");
builder.put("index.analysis.tokenizer.whitespacecomma.pattern", "(,|\\s+)");
XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("doc")
.startObject("properties")
.startObject("filingcategory").field("type", "string").field("analyzer", "lwhitespacecomma").endObject()
.endObject()
.endObject().endObject();
client().admin().indices().prepareCreate("test")
.addMapping("doc", mapping)
.setSettings(builder.put("index.number_of_shards", 1))
.execute().actionGet();
ensureGreen();
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject()
.field("source", "productizer")
.field("query", QueryBuilders.constantScoreQuery(QueryBuilders.queryString("filingcategory:s")))
.endObject())
.setRefresh(true)
.execute().actionGet();
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("doc")
.setSource(jsonBuilder().startObject()
.startObject("doc").field("filingcategory", "s").endObject()
.field("query", termQuery("source", "productizer"))
.endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
}
@Test
public void createIndexAndThenRegisterPercolator() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)));
ensureGreen();
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.execute().actionGet();
refresh();
CountResponse countResponse = client().prepareCount()
.setQuery(matchAllQuery()).setTypes(PercolatorService.TYPE_NAME)
.execute().actionGet();
assertThat(countResponse.getCount(), equalTo(1l));
for (int i = 0; i < 10; i++) {
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value1").endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
}
for (int i = 0; i < 10; i++) {
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setPreference("_local")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value1").endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
}
logger.info("--> delete the index");
client().admin().indices().prepareDelete("test").execute().actionGet();
logger.info("--> make sure percolated queries for it have been deleted as well");
countResponse = client().prepareCount()
.setQuery(matchAllQuery()).setTypes(PercolatorService.TYPE_NAME)
.execute().actionGet();
assertHitCount(countResponse, 0l);
}
@Test
public void multiplePercolators() throws Exception {
client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute().actionGet();
ensureGreen();
logger.info("--> register a query 1");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.execute().actionGet();
logger.info("--> register a query 2");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "bubu")
.setSource(jsonBuilder().startObject()
.field("color", "green")
.field("query", termQuery("field1", "value2"))
.endObject())
.setRefresh(true)
.execute().actionGet();
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value1").endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("kuku"));
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").startObject("type1").field("field1", "value2").endObject().endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("bubu"));
}
@Test
public void dynamicAddingRemovingQueries() throws Exception {
client().admin().indices().prepareCreate("test").setSettings(settingsBuilder().put("index.number_of_shards", 1)).execute().actionGet();
ensureGreen();
logger.info("--> register a query 1");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.execute().actionGet();
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value1").endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("kuku"));
logger.info("--> register a query 2");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "bubu")
.setSource(jsonBuilder().startObject()
.field("color", "green")
.field("query", termQuery("field1", "value2"))
.endObject())
.setRefresh(true)
.execute().actionGet();
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").startObject("type1").field("field1", "value2").endObject().endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("bubu"));
logger.info("--> register a query 3");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "susu")
.setSource(jsonBuilder().startObject()
.field("color", "red")
.field("query", termQuery("field1", "value2"))
.endObject())
.setRefresh(true)
.execute().actionGet();
PercolateSourceBuilder sourceBuilder = new PercolateSourceBuilder()
.setDoc(docBuilder().setDoc(jsonBuilder().startObject().startObject("type1").field("field1", "value2").endObject().endObject()))
.setQueryBuilder(termQuery("color", "red"));
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(sourceBuilder)
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("susu"));
logger.info("--> deleting query 1");
client().prepareDelete("test", PercolatorService.TYPE_NAME, "kuku").setRefresh(true).execute().actionGet();
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").startObject("type1")
.field("field1", "value1")
.endObject().endObject().endObject())
.execute().actionGet();
assertMatchCount(percolate, 0l);
assertThat(percolate.getMatches(), emptyArray());
}
@Test
public void percolateWithSizeField() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("_size").field("enabled", true).field("stored", "yes").endObject()
.endObject().endObject().string();
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 2))
.addMapping("type1", mapping)
.execute().actionGet();
ensureGreen();
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.execute().actionGet();
logger.info("--> percolate a document");
PercolateResponse percolate = client().preparePercolate().setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject()
.startObject("doc").startObject("type1")
.field("field1", "value1")
.endObject().endObject()
.endObject())
.execute().actionGet();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(percolate.getMatches(), "test"), arrayContaining("kuku"));
}
@Test
public void testPercolateStatistics() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> First percolate request");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field", "val").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("1"));
IndicesStatsResponse indicesResponse = client().admin().indices().prepareStats("test").execute().actionGet();
assertThat(indicesResponse.getTotal().getPercolate().getCount(), equalTo(5l)); // We have 5 partitions
assertThat(indicesResponse.getTotal().getPercolate().getCurrent(), equalTo(0l));
assertThat(indicesResponse.getTotal().getPercolate().getNumQueries(), equalTo(2l)); // One primary and replica
assertThat(indicesResponse.getTotal().getPercolate().getMemorySizeInBytes(), greaterThan(0l));
NodesStatsResponse nodesResponse = client().admin().cluster().prepareNodesStats().execute().actionGet();
long percolateCount = 0;
for (NodeStats nodeStats : nodesResponse) {
percolateCount += nodeStats.getIndices().getPercolate().getCount();
}
assertThat(percolateCount, equalTo(5l)); // We have 5 partitions
logger.info("--> Second percolate request");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field", "val").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("1"));
indicesResponse = client().admin().indices().prepareStats().setPercolate(true).execute().actionGet();
assertThat(indicesResponse.getTotal().getPercolate().getCount(), equalTo(10l));
assertThat(indicesResponse.getTotal().getPercolate().getCurrent(), equalTo(0l));
assertThat(indicesResponse.getTotal().getPercolate().getNumQueries(), equalTo(2l));
assertThat(indicesResponse.getTotal().getPercolate().getMemorySizeInBytes(), greaterThan(0l));
percolateCount = 0;
nodesResponse = client().admin().cluster().prepareNodesStats().execute().actionGet();
for (NodeStats nodeStats : nodesResponse) {
percolateCount += nodeStats.getIndices().getPercolate().getCount();
}
assertThat(percolateCount, equalTo(10l));
// We might be faster than 1 ms, so run upto 1000 times until have spend 1ms or more on percolating
boolean moreThanOneMs = false;
int counter = 3; // We already ran two times.
do {
indicesResponse = client().admin().indices().prepareStats("test").execute().actionGet();
if (indicesResponse.getTotal().getPercolate().getTimeInMillis() > 0) {
moreThanOneMs = true;
break;
}
logger.info("--> {}th percolate request", counter);
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field", "val").endObject().endObject())
.execute().actionGet();
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("1"));
} while (++counter <= 1000);
assertTrue("Something is off, we should have spent at least 1ms on percolating...", moreThanOneMs);
long percolateSumTime = 0;
nodesResponse = client().admin().cluster().prepareNodesStats().execute().actionGet();
for (NodeStats nodeStats : nodesResponse) {
percolateCount += nodeStats.getIndices().getPercolate().getCount();
percolateSumTime += nodeStats.getIndices().getPercolate().getTimeInMillis();
}
assertThat(percolateSumTime, greaterThan(0l));
}
@Test
public void testPercolatingExistingDocs() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Adding docs");
client().prepareIndex("test", "type", "1").setSource("field1", "b").execute().actionGet();
client().prepareIndex("test", "type", "2").setSource("field1", "c").execute().actionGet();
client().prepareIndex("test", "type", "3").setSource("field1", "b c").execute().actionGet();
client().prepareIndex("test", "type", "4").setSource("field1", "d").execute().actionGet();
logger.info("--> register a queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Percolate existing doc with id 1");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("1"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "4"));
logger.info("--> Percolate existing doc with id 2");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("2"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));
logger.info("--> Percolate existing doc with id 3");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("3"))
.execute().actionGet();
assertMatchCount(response, 4l);
assertThat(response.getMatches(), arrayWithSize(4));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4"));
logger.info("--> Percolate existing doc with id 4");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("4"))
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("4"));
logger.info("--> Search normals docs, percolate queries must not be included");
SearchResponse searchResponse = client().prepareSearch("test").execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(4L));
assertThat(searchResponse.getHits().getAt(0).type(), equalTo("type"));
assertThat(searchResponse.getHits().getAt(1).type(), equalTo("type"));
assertThat(searchResponse.getHits().getAt(2).type(), equalTo("type"));
assertThat(searchResponse.getHits().getAt(3).type(), equalTo("type"));
}
@Test
public void testPercolatingExistingDocs_routing() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Adding docs");
client().prepareIndex("test", "type", "1").setSource("field1", "b").setRouting("4").execute().actionGet();
client().prepareIndex("test", "type", "2").setSource("field1", "c").setRouting("3").execute().actionGet();
client().prepareIndex("test", "type", "3").setSource("field1", "b c").setRouting("2").execute().actionGet();
client().prepareIndex("test", "type", "4").setSource("field1", "d").setRouting("1").execute().actionGet();
logger.info("--> register a queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Percolate existing doc with id 1");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("1").routing("4"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "4"));
logger.info("--> Percolate existing doc with id 2");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("2").routing("3"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));
logger.info("--> Percolate existing doc with id 3");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("3").routing("2"))
.execute().actionGet();
assertMatchCount(response, 4l);
assertThat(response.getMatches(), arrayWithSize(4));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4"));
logger.info("--> Percolate existing doc with id 4");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("4").routing("1"))
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContaining("4"));
}
@Test
public void testPercolatingExistingDocs_versionCheck() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Adding docs");
client().prepareIndex("test", "type", "1").setSource("field1", "b").execute().actionGet();
client().prepareIndex("test", "type", "2").setSource("field1", "c").execute().actionGet();
client().prepareIndex("test", "type", "3").setSource("field1", "b c").execute().actionGet();
client().prepareIndex("test", "type", "4").setSource("field1", "d").execute().actionGet();
logger.info("--> registering queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Percolate existing doc with id 2 and version 1");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("2").version(1l))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));
logger.info("--> Percolate existing doc with id 2 and version 2");
try {
client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("2").version(2l))
.execute().actionGet();
fail("Error should have been thrown");
} catch (VersionConflictEngineException e) {
}
logger.info("--> Index doc with id for the second time");
client().prepareIndex("test", "type", "2").setSource("field1", "c").execute().actionGet();
logger.info("--> Percolate existing doc with id 2 and version 2");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type")
.setGetRequest(Requests.getRequest("test").type("type").id("2").version(2l))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), arrayWithSize(2));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("2", "4"));
}
@Test
public void testPercolateMultipleIndicesAndAliases() throws Exception {
client().admin().indices().prepareCreate("test1")
.setSettings(settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
client().admin().indices().prepareCreate("test2")
.setSettings(settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
ensureGreen();
logger.info("--> registering queries");
for (int i = 1; i <= 10; i++) {
String index = i % 2 == 0 ? "test1" : "test2";
client().prepareIndex(index, PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
}
logger.info("--> Percolate doc to index test1");
PercolateResponse response = client().preparePercolate()
.setIndices("test1").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
logger.info("--> Percolate doc to index test2");
response = client().preparePercolate()
.setIndices("test2").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
logger.info("--> Percolate doc to index test1 and test2");
response = client().preparePercolate()
.setIndices("test1", "test2").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 10l);
assertThat(response.getMatches(), arrayWithSize(10));
logger.info("--> Percolate doc to index test2 and test3, with ignore missing");
response = client().preparePercolate()
.setIndices("test1", "test3").setDocumentType("type")
.setIgnoreIndices(IgnoreIndices.MISSING)
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
logger.info("--> Adding aliases");
IndicesAliasesResponse aliasesResponse = client().admin().indices().prepareAliases()
.addAlias("test1", "my-alias1")
.addAlias("test2", "my-alias1")
.addAlias("test2", "my-alias2")
.setTimeout(TimeValue.timeValueHours(10))
.execute().actionGet();
assertTrue(aliasesResponse.isAcknowledged());
logger.info("--> Percolate doc to my-alias1");
response = client().preparePercolate()
.setIndices("my-alias1").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 10l);
assertThat(response.getMatches(), arrayWithSize(10));
for (PercolateResponse.Match match : response) {
assertThat(match.getIndex().string(), anyOf(equalTo("test1"), equalTo("test2")));
}
logger.info("--> Percolate doc to my-alias2");
response = client().preparePercolate()
.setIndices("my-alias2").setDocumentType("type")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", "value").endObject().endObject())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
for (PercolateResponse.Match match : response) {
assertThat(match.getIndex().string(), equalTo("test2"));
}
}
@Test
public void testCountPercolation() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Add dummy doc");
client().prepareIndex("test", "type", "1").setSource("field", "value").execute().actionGet();
logger.info("--> register a queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Count percolate doc with field1=b");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject()))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate doc with field1=c");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(yamlBuilder().startObject().field("field1", "c").endObject()))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate doc with field1=b c");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(smileBuilder().startObject().field("field1", "b c").endObject()))
.execute().actionGet();
assertMatchCount(response, 4l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate doc with field1=d");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "d").endObject()))
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate non existing doc");
try {
client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setGetRequest(Requests.getRequest("test").type("type").id("5"))
.execute().actionGet();
fail("Exception should have been thrown");
} catch (DocumentMissingException e) {
}
}
@Test
public void testCountPercolatingExistingDocs() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
logger.info("--> Adding docs");
client().prepareIndex("test", "type", "1").setSource("field1", "b").execute().actionGet();
client().prepareIndex("test", "type", "2").setSource("field1", "c").execute().actionGet();
client().prepareIndex("test", "type", "3").setSource("field1", "b c").execute().actionGet();
client().prepareIndex("test", "type", "4").setSource("field1", "d").execute().actionGet();
logger.info("--> register a queries");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Count percolate existing doc with id 1");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setGetRequest(Requests.getRequest("test").type("type").id("1"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate existing doc with id 2");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setGetRequest(Requests.getRequest("test").type("type").id("2"))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate existing doc with id 3");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setGetRequest(Requests.getRequest("test").type("type").id("3"))
.execute().actionGet();
assertMatchCount(response, 4l);
assertThat(response.getMatches(), emptyArray());
logger.info("--> Count percolate existing doc with id 4");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type").setOnlyCount(true)
.setGetRequest(Requests.getRequest("test").type("type").id("4"))
.execute().actionGet();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), emptyArray());
}
@Test
public void testPercolateSizingWithQueryAndFilter() throws Exception {
client().admin().indices().prepareCreate("test").execute().actionGet();
ensureGreen();
int numLevels = randomIntBetween(1, 25);
long numQueriesPerLevel = randomIntBetween(10, 250);
long totalQueries = numLevels * numQueriesPerLevel;
logger.info("--> register " + totalQueries + " queries");
for (int level = 1; level <= numLevels; level++) {
for (int query = 1; query <= numQueriesPerLevel; query++) {
client().prepareIndex("my-index", PercolatorService.TYPE_NAME, level + "-" + query)
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("level", level).endObject())
.execute().actionGet();
}
}
boolean onlyCount = randomBoolean();
PercolateResponse response = client().preparePercolate()
.setIndices("my-index").setDocumentType("my-type")
.setOnlyCount(onlyCount)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.execute().actionGet();
assertMatchCount(response, totalQueries);
if (!onlyCount) {
assertThat(response.getMatches().length, equalTo((int) totalQueries));
}
int size = randomIntBetween(0, (int) totalQueries - 1);
response = client().preparePercolate()
.setIndices("my-index").setDocumentType("my-type")
.setOnlyCount(onlyCount)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setSize(size)
.execute().actionGet();
assertMatchCount(response, totalQueries);
if (!onlyCount) {
assertThat(response.getMatches().length, equalTo(size));
}
// The query / filter capabilities are NOT in realtime
client().admin().indices().prepareRefresh("my-index").execute().actionGet();
int runs = randomIntBetween(3, 16);
for (int i = 0; i < runs; i++) {
onlyCount = randomBoolean();
response = client().preparePercolate()
.setIndices("my-index").setDocumentType("my-type")
.setOnlyCount(onlyCount)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(termQuery("level", 1 + randomInt(numLevels - 1)))
.execute().actionGet();
assertMatchCount(response, numQueriesPerLevel);
if (!onlyCount) {
assertThat(response.getMatches().length, equalTo((int) numQueriesPerLevel));
}
}
for (int i = 0; i < runs; i++) {
onlyCount = randomBoolean();
response = client().preparePercolate()
.setIndices("my-index").setDocumentType("my-type")
.setOnlyCount(onlyCount)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateFilter(termFilter("level", 1 + randomInt(numLevels - 1)))
.execute().actionGet();
assertMatchCount(response, numQueriesPerLevel);
if (!onlyCount) {
assertThat(response.getMatches().length, equalTo((int) numQueriesPerLevel));
}
}
for (int i = 0; i < runs; i++) {
onlyCount = randomBoolean();
size = randomIntBetween(0, (int) numQueriesPerLevel - 1);
response = client().preparePercolate()
.setIndices("my-index").setDocumentType("my-type")
.setOnlyCount(onlyCount)
.setSize(size)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateFilter(termFilter("level", 1 + randomInt(numLevels - 1)))
.execute().actionGet();
assertMatchCount(response, numQueriesPerLevel);
if (!onlyCount) {
assertThat(response.getMatches().length, equalTo(size));
}
}
}
@Test
public void testPercolateScoreAndSorting() throws Exception {
client().admin().indices().prepareCreate("my-index")
.setSettings(ImmutableSettings.settingsBuilder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
.build())
.execute().actionGet();
ensureGreen();
// Add a dummy doc, that shouldn't never interfere with percolate operations.
client().prepareIndex("my-index", "my-type", "1").setSource("field", "value").execute().actionGet();
Map<Integer, NavigableSet<Integer>> controlMap = new HashMap<Integer, NavigableSet<Integer>>();
long numQueries = randomIntBetween(100, 250);
logger.info("--> register " + numQueries + " queries");
for (int i = 0; i < numQueries; i++) {
int value = randomInt(10);
client().prepareIndex("my-index", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("level", i).field("field1", value).endObject())
.execute().actionGet();
if (!controlMap.containsKey(value)) {
controlMap.put(value, new TreeSet<Integer>());
}
controlMap.get(value).add(i);
}
refresh();
// Only retrieve the score
int runs = randomInt(27);
for (int i = 0; i < runs; i++) {
int size = randomIntBetween(1, 50);
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setScore(true)
.setSize(size)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, numQueries);
assertThat(response.getMatches().length, equalTo(size));
for (int j = 0; j < response.getMatches().length; j++) {
String id = response.getMatches()[j].getId().string();
assertThat(Integer.valueOf(id), equalTo((int) response.getMatches()[j].getScore()));
}
}
// Sort the queries by the score
runs = randomInt(27);
for (int i = 0; i < runs; i++) {
int size = randomIntBetween(1, 10);
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setSize(size)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, numQueries);
assertThat(response.getMatches().length, equalTo(size));
int expectedId = (int) (numQueries - 1);
for (PercolateResponse.Match match : response) {
assertThat(match.getId().string(), equalTo(Integer.toString(expectedId)));
assertThat(match.getScore(), equalTo((float) expectedId));
assertThat(match.getIndex().string(), equalTo("my-index"));
expectedId--;
}
}
runs = randomInt(27);
for (int i = 0; i < runs; i++) {
int value = randomInt(10);
NavigableSet<Integer> levels = controlMap.get(value);
int size = randomIntBetween(1, levels.size());
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setSize(size)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchQuery("field1", value), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, levels.size());
assertThat(response.getMatches().length, equalTo(Math.min(levels.size(), size)));
Iterator<Integer> levelIterator = levels.descendingIterator();
for (PercolateResponse.Match match : response) {
int controlLevel = levelIterator.next();
assertThat(match.getId().string(), equalTo(Integer.toString(controlLevel)));
assertThat(match.getScore(), equalTo((float) controlLevel));
assertThat(match.getIndex().string(), equalTo("my-index"));
}
}
}
@Test
public void testPercolateSortingWithNoSize() throws Exception {
client().admin().indices().prepareCreate("my-index").execute().actionGet();
ensureGreen();
client().prepareIndex("my-index", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("level", 1).endObject())
.execute().actionGet();
client().prepareIndex("my-index", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("level", 2).endObject())
.execute().actionGet();
refresh();
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setSize(2)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, 2l);
assertThat(response.getMatches()[0].getId().string(), equalTo("2"));
assertThat(response.getMatches()[0].getScore(), equalTo(2f));
assertThat(response.getMatches()[1].getId().string(), equalTo("1"));
assertThat(response.getMatches()[1].getScore(), equalTo(1f));
response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertThat(response.getCount(), equalTo(0l));
assertThat(response.getSuccessfulShards(), equalTo(3));
assertThat(response.getShardFailures().length, equalTo(2));
assertThat(response.getShardFailures()[0].status().getStatus(), equalTo(400));
assertThat(response.getShardFailures()[0].reason(), containsString("Can't sort if size isn't specified"));
assertThat(response.getShardFailures()[1].status().getStatus(), equalTo(400));
assertThat(response.getShardFailures()[1].reason(), containsString("Can't sort if size isn't specified"));
}
@Test
public void testPercolateOnEmptyIndex() throws Exception {
client().admin().indices().prepareCreate("my-index").execute().actionGet();
ensureGreen();
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setSize(2)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, 0l);
}
@Test
public void testPercolateNotEmptyIndexButNoRefresh() throws Exception {
client().admin().indices().prepareCreate("my-index")
.setSettings(ImmutableSettings.settingsBuilder().put("index.refresh_interval", -1))
.execute().actionGet();
ensureGreen();
client().prepareIndex("my-index", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).field("level", 1).endObject())
.execute().actionGet();
PercolateResponse response = client().preparePercolate().setIndices("my-index").setDocumentType("my-type")
.setSort(true)
.setSize(2)
.setPercolateDoc(docBuilder().setDoc("field", "value"))
.setPercolateQuery(QueryBuilders.functionScoreQuery(matchAllQuery(), scriptFunction("doc['level'].value")))
.execute().actionGet();
assertMatchCount(response, 0l);
}
@Test
public void testPercolatorWithHighlighting() throws Exception {
Client client = client();
client.admin().indices().prepareCreate("test")
.setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
ensureGreen();
if (randomBoolean()) {
// FVH HL
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", randomBoolean())
.field("term_vector", "with_positions_offsets").endObject()
.endObject()
.endObject().endObject()
- )
- .execute().actionGet();
- } if (randomBoolean()) {
+ ).get();
+ } else if (randomBoolean()) {
// plain hl with stored fields
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", true).endObject()
.endObject()
.endObject().endObject()
- )
- .execute().actionGet();
+ ).get();
} else if (randomBoolean()) {
// positions hl
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string")
.field("index_options", "offsets")
.endObject()
.endObject()
.endObject().endObject()
- )
- .execute().actionGet();
+ ).get();
}
logger.info("--> register a queries");
client.prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "brown fox")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "lazy dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "jumps")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "5")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "fox")).endObject())
.execute().actionGet();
logger.info("--> Percolate doc with field1=The quick brown fox jumps over the lazy dog");
PercolateResponse response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
PercolateResponse.Match[] matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
// Anything with percolate query isn't realtime
client.admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Query percolate doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(matchAllQuery())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Query percolate with score for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setScore(true)
.execute().actionGet();
assertNoFailures(response);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Top percolate for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setSort(true)
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
}
@Test
public void testDeletePercolatorType() throws Exception {
DeleteIndexResponse deleteIndexResponse = client().admin().indices().prepareDelete().execute().actionGet();
assertThat("Delete Index failed - not acked", deleteIndexResponse.isAcknowledged(), equalTo(true));
ensureGreen();
client().admin().indices().prepareCreate("test1").execute().actionGet();
client().admin().indices().prepareCreate("test2").execute().actionGet();
ensureGreen();
client().prepareIndex("test1", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().prepareIndex("test2", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
PercolateResponse response = client().preparePercolate()
.setIndices("test1", "test2").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject()))
.execute().actionGet();
assertMatchCount(response, 2l);
assertAcked(client().admin().indices().prepareDeleteMapping("test1").setType(PercolatorService.TYPE_NAME));
response = client().preparePercolate()
.setIndices("test1", "test2").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject()))
.execute().actionGet();
assertMatchCount(response, 1l);
assertAcked(client().admin().indices().prepareDeleteMapping("test2").setType(PercolatorService.TYPE_NAME));
// Percolate api should return 0 matches, because all docs in _percolate type have been removed.
response = client().preparePercolate()
.setIndices("test1", "test2").setDocumentType("type").setOnlyCount(true)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "b").endObject()))
.execute().actionGet();
assertMatchCount(response, 0l);
}
public static String[] convertFromTextArray(PercolateResponse.Match[] matches, String index) {
if (matches.length == 0) {
return Strings.EMPTY_ARRAY;
}
String[] strings = new String[matches.length];
for (int i = 0; i < matches.length; i++) {
assert index.equals(matches[i].getIndex().string());
strings[i] = matches[i].getId().string();
}
return strings;
}
}
| false | true | public void testPercolatorWithHighlighting() throws Exception {
Client client = client();
client.admin().indices().prepareCreate("test")
.setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
ensureGreen();
if (randomBoolean()) {
// FVH HL
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", randomBoolean())
.field("term_vector", "with_positions_offsets").endObject()
.endObject()
.endObject().endObject()
)
.execute().actionGet();
} if (randomBoolean()) {
// plain hl with stored fields
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", true).endObject()
.endObject()
.endObject().endObject()
)
.execute().actionGet();
} else if (randomBoolean()) {
// positions hl
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string")
.field("index_options", "offsets")
.endObject()
.endObject()
.endObject().endObject()
)
.execute().actionGet();
}
logger.info("--> register a queries");
client.prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "brown fox")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "lazy dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "jumps")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "5")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "fox")).endObject())
.execute().actionGet();
logger.info("--> Percolate doc with field1=The quick brown fox jumps over the lazy dog");
PercolateResponse response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
PercolateResponse.Match[] matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
// Anything with percolate query isn't realtime
client.admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Query percolate doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(matchAllQuery())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Query percolate with score for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setScore(true)
.execute().actionGet();
assertNoFailures(response);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Top percolate for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setSort(true)
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
}
| public void testPercolatorWithHighlighting() throws Exception {
Client client = client();
client.admin().indices().prepareCreate("test")
.setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2))
.execute().actionGet();
ensureGreen();
if (randomBoolean()) {
// FVH HL
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", randomBoolean())
.field("term_vector", "with_positions_offsets").endObject()
.endObject()
.endObject().endObject()
).get();
} else if (randomBoolean()) {
// plain hl with stored fields
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string").field("store", true).endObject()
.endObject()
.endObject().endObject()
).get();
} else if (randomBoolean()) {
// positions hl
client.admin().indices().preparePutMapping("test").setType("type")
.setSource(
jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1").field("type", "string")
.field("index_options", "offsets")
.endObject()
.endObject()
.endObject().endObject()
).get();
}
logger.info("--> register a queries");
client.prepareIndex("test", PercolatorService.TYPE_NAME, "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "brown fox")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "lazy dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "3")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "jumps")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "4")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "dog")).endObject())
.execute().actionGet();
client.prepareIndex("test", PercolatorService.TYPE_NAME, "5")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "fox")).endObject())
.execute().actionGet();
logger.info("--> Percolate doc with field1=The quick brown fox jumps over the lazy dog");
PercolateResponse response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
PercolateResponse.Match[] matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
// Anything with percolate query isn't realtime
client.admin().indices().prepareRefresh("test").execute().actionGet();
logger.info("--> Query percolate doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(matchAllQuery())
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Query percolate with score for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setScore(true)
.execute().actionGet();
assertNoFailures(response);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
logger.info("--> Top percolate for doc with field1=The quick brown fox jumps over the lazy dog");
response = client.preparePercolate()
.setIndices("test").setDocumentType("type")
.setSize(5)
.setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject()))
.setHighlightBuilder(new HighlightBuilder().field("field1"))
.setPercolateQuery(functionScoreQuery(matchAllQuery()).add(new FactorBuilder().boostFactor(5.5f)))
.setSort(true)
.execute().actionGet();
assertMatchCount(response, 5l);
assertThat(response.getMatches(), arrayWithSize(5));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("1", "2", "3", "4", "5"));
matches = response.getMatches();
Arrays.sort(matches, new Comparator<PercolateResponse.Match>() {
@Override
public int compare(PercolateResponse.Match a, PercolateResponse.Match b) {
return a.getId().compareTo(b.getId());
}
});
assertThat(matches[0].getScore(), equalTo(5.5f));
assertThat(matches[0].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(matches[1].getScore(), equalTo(5.5f));
assertThat(matches[1].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(matches[2].getScore(), equalTo(5.5f));
assertThat(matches[2].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(matches[3].getScore(), equalTo(5.5f));
assertThat(matches[3].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(matches[4].getScore(), equalTo(5.5f));
assertThat(matches[4].getHighlightFields().get("field1").fragments()[0].string(), equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/ChangeOperation.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/ChangeOperation.java
index b9a4e352..8de2dcfe 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/ChangeOperation.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/ChangeOperation.java
@@ -1,68 +1,68 @@
package net.sourceforge.vrapper.vim.commands;
import static net.sourceforge.vrapper.vim.commands.ConstructorWrappers.seq;
import net.sourceforge.vrapper.utils.ContentType;
import net.sourceforge.vrapper.utils.PositionlessSelection;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.modes.ExecuteCommandHint;
import net.sourceforge.vrapper.vim.modes.InsertMode;
class ChangeOperationRepetition implements TextOperation {
public static final TextOperation INSTANCE = new ChangeOperationRepetition();
@Override
public void execute(final EditorAdaptor editorAdaptor, final int count,
final TextObject textObject) throws CommandExecutionException {
final Command lastInsertion = editorAdaptor.getRegisterManager().getLastInsertion();
seq(ChangeOperation.getHintCommand(editorAdaptor, count, textObject), lastInsertion).execute(editorAdaptor);
}
@Override
public TextOperation repetition() {
return this;
}
}
public class ChangeOperation implements TextOperation {
public static final ChangeOperation INSTANCE = new ChangeOperation();
private ChangeOperation() { /* NOP */ }
@Override
public TextOperation repetition() {
return ChangeOperationRepetition.INSTANCE;
}
@Override
public void execute(final EditorAdaptor editorAdaptor, final int count, final TextObject textObject) throws CommandExecutionException {
final Command beforeInsertCmd = getHintCommand(editorAdaptor, count, textObject);
final PositionlessSelection lastSel = editorAdaptor.getRegisterManager().getLastActiveSelection();
- if (textObject instanceof Selection
+ if (textObject instanceof Selection && lastSel != null
&& ContentType.TEXT_RECTANGLE.equals(lastSel.getContentType(editorAdaptor.getConfiguration()))) {
// insert in block mode
// the SelectionBasedTextOperationCommand already locked history for us
final Command afterInsertCmd = getLeaveHintCommand(editorAdaptor, count, lastSel);
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd),
new ExecuteCommandHint.OnLeave(afterInsertCmd));
} else {
// normal insert
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd));
}
}
static Command getHintCommand(final EditorAdaptor editorAdaptor, final int count, final TextObject textObject) {
Command result = new TextOperationTextObjectCommand(DeleteOperation.INSTANCE, textObject).withCount(count);
if (ContentType.LINES.equals(textObject.getContentType(editorAdaptor.getConfiguration()))) {
result = seq(result, InsertLineCommand.PRE_CURSOR);
}
return result;
}
Command getLeaveHintCommand(final EditorAdaptor editorAdaptor, final int count, final TextObject textObject) {
return new SelectionBasedTextOperationCommand.BlockwiseRepeatCommand(this, count, true, true);
}
}
| true | true | public void execute(final EditorAdaptor editorAdaptor, final int count, final TextObject textObject) throws CommandExecutionException {
final Command beforeInsertCmd = getHintCommand(editorAdaptor, count, textObject);
final PositionlessSelection lastSel = editorAdaptor.getRegisterManager().getLastActiveSelection();
if (textObject instanceof Selection
&& ContentType.TEXT_RECTANGLE.equals(lastSel.getContentType(editorAdaptor.getConfiguration()))) {
// insert in block mode
// the SelectionBasedTextOperationCommand already locked history for us
final Command afterInsertCmd = getLeaveHintCommand(editorAdaptor, count, lastSel);
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd),
new ExecuteCommandHint.OnLeave(afterInsertCmd));
} else {
// normal insert
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd));
}
}
| public void execute(final EditorAdaptor editorAdaptor, final int count, final TextObject textObject) throws CommandExecutionException {
final Command beforeInsertCmd = getHintCommand(editorAdaptor, count, textObject);
final PositionlessSelection lastSel = editorAdaptor.getRegisterManager().getLastActiveSelection();
if (textObject instanceof Selection && lastSel != null
&& ContentType.TEXT_RECTANGLE.equals(lastSel.getContentType(editorAdaptor.getConfiguration()))) {
// insert in block mode
// the SelectionBasedTextOperationCommand already locked history for us
final Command afterInsertCmd = getLeaveHintCommand(editorAdaptor, count, lastSel);
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd),
new ExecuteCommandHint.OnLeave(afterInsertCmd));
} else {
// normal insert
editorAdaptor.changeMode(InsertMode.NAME, new ExecuteCommandHint.OnEnter(beforeInsertCmd));
}
}
|
diff --git a/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java b/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
index 10d0db01..75dddf77 100644
--- a/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
+++ b/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
@@ -1,61 +1,61 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.patient;
import junit.framework.Assert;
import org.junit.Test;
import org.openmrs.test.Verifies;
import org.openmrs.web.controller.patient.PatientDashboardGraphController;
import org.openmrs.web.controller.patient.PatientGraphData;
import org.openmrs.web.test.BaseWebContextSensitiveTest;
import org.springframework.ui.ModelMap;
/**
* Test for graphs on the patient dashboard
*/
public class PatientDashboardGraphControllerTest extends BaseWebContextSensitiveTest {
/**
* Test getting a concept by name and by partial name.
*
* @see {@link PatientDashboardGraphController#showGraphData(Integer, Integer, ModelMap)}
*/
@Test
@Verifies(value = "return json data with observation details and critical values for the concept", method = "showGraphData(Integer, Integer, ModelMap)")
public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
- Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139509800000,2.0],[1139423400000,1.0]]}", graph
+ Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139547600000,2.0],[1139461200000,1.0]]}", graph
.toString());
}
/**
* Test the path of the form for rendering the json data
*
* @see {@link PatientDashboardGraphController#showGraphData(Integer, Integer, ModelMap)}
*/
@Test
@Verifies(value = "return form for rendering the json data", method = "showGraphData(Integer, Integer, ModelMap)")
public void shouldDisplayPatientDashboardGraphForm() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
Assert.assertEquals("patientGraphJsonForm", new PatientDashboardGraphController().showGraphData(2, 1,
new ModelMap()));
}
}
| true | true | public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139509800000,2.0],[1139423400000,1.0]]}", graph
.toString());
}
| public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139547600000,2.0],[1139461200000,1.0]]}", graph
.toString());
}
|
diff --git a/src/mil/af/rl/EPTEstimator/client/EPTEstimator.java b/src/mil/af/rl/EPTEstimator/client/EPTEstimator.java
index a1de35a..6b70681 100755
--- a/src/mil/af/rl/EPTEstimator/client/EPTEstimator.java
+++ b/src/mil/af/rl/EPTEstimator/client/EPTEstimator.java
@@ -1,516 +1,516 @@
package mil.af.rl.EPTEstimator.client;
import java.util.ArrayList;
import mil.af.rl.EPTEstimator.shared.FieldVerifier;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.text.DecimalFormat;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class EPTEstimator implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final CreateEPTAsync EPTService = GWT
.create(CreateEPT.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
try{
/* for use in setting focus in event naming dialog
final EventBus eventBus = GWT.create(SimpleEventBus.class);
class ReadyForFocus extends GwtEvent<EventHandler>{
public Type<EventHandler> TYPE = new Type<EventHandler>();
@Override
public com.google.gwt.event.shared.GwtEvent.Type<EventHandler> getAssociatedType(){
return (Type<EventHandler>)TYPE;
}
@Override
protected void dispatch(EventHandler handler){
}
}
*/
EPTService.MMCALCReset(// resets the server without saving anything
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
}
});
final TextArea currentStep = new TextArea();
currentStep.setText("Ready to Add an Effect");
currentStep.setReadOnly(true);
currentStep.setStylePrimaryName("currentStep");
final Button extendButton = new Button("Extend");
final Button addEventButton = new Button("Add Effect");
addEventButton.setStylePrimaryName("addEvent");
addEventButton.setFocus(true);
final TextBox nameField = new TextBox();
nameField.setText("New Effect");
final Button doneButton = new Button("Done");
doneButton.setStylePrimaryName("DoneStyle");
doneButton.setTitle("The EPT is complete");
final TextBox marginalEvent = new TextBox();
marginalEvent.setText("0");
marginalEvent.setTitle("Index of powerset of base events in order added");
final TextBox currentValue = new TextBox();
currentValue.setTitle("Current probability of indexed event");
currentValue.setText("1.0");
currentValue.setReadOnly(true);
final Label lowerBound = new Label();
lowerBound.setText("<=");
lowerBound.setTitle("Minimum value of indexed event");
lowerBound.setStylePrimaryName("lowerBound");
final TextBox newValue = new TextBox();
newValue.setText("1.0");
newValue.setTitle("Edit probability of indexed event");
final Label upperBound = new Label();
- upperBound.setText(">=");
+ upperBound.setText("<=");
upperBound.setTitle("Maximum value of indexed event");
final Button setValueButton = new Button("Set Value");
setValueButton.setFocus(false);
setValueButton.setEnabled(false);
setValueButton.setStyleName("valueButton");
final Button showMarginalButton = new Button("Show Marginal");
showMarginalButton.setStylePrimaryName("showMarginal");
final Button correlationListOK = new Button("Correlation List OK");
correlationListOK.setStylePrimaryName("correlationListOK");
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
final ArrayList<CheckBox> checkBoxList = new ArrayList<CheckBox>();
final FlexTable corTable = new FlexTable();
final Grid marginalGrid = new Grid(64,2);
marginalGrid.setBorderWidth(1);
marginalGrid.setText(0, 0, "1.0");
final Grid subsetGrid = new Grid(64,2);
subsetGrid.setBorderWidth(1);
final Grid pearsonGrid = new Grid(64,2);
pearsonGrid.setStylePrimaryName("jointGrid");
pearsonGrid.setBorderWidth(1);
pearsonGrid.setText(0, 00, "1.0");
pearsonGrid.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
com.google.gwt.user.client.ui.HTMLTable.Cell clickedCell = pearsonGrid.getCellForEvent(e);
if(clickedCell != null){
String styleNames = pearsonGrid.getStyleName();
String OriginalprimaryStyle = pearsonGrid.getStylePrimaryName();
int cellIndex = clickedCell.getCellIndex();
int rowIndex = clickedCell.getRowIndex();
String primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
pearsonGrid.getRowFormatter().setStyleName(rowIndex, "selected");
pearsonGrid.getCellFormatter().setStyleName(0, 0, "columnHeader");
primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
primaryStyle = pearsonGrid.getRowFormatter().getStyleName(rowIndex);
int psIndex= new Integer(pearsonGrid.getHTML(rowIndex, cellIndex)).intValue();
int j = 0;
int k = 0;
for(CheckBox cb: checkBoxList){
if(((psIndex&(1<<j)) != 0)){
String name = cb.getText();
subsetGrid.setText(k++, 0, name);
}
j += 1;
}
}
}
});
final ScrollPanel marginalScrollPanel = new ScrollPanel(marginalGrid);
marginalScrollPanel.setHeight("200px");
marginalScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel jointScrollPanel = new ScrollPanel(pearsonGrid);
jointScrollPanel.setHeight("200px");
jointScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel subsetScrollPanel = new ScrollPanel(subsetGrid);
subsetScrollPanel.setHeight("200px");
subsetScrollPanel.setAlwaysShowScrollBars(true);
// We can add style names to widgets
// RootPanel.setStyleName("outerFrame");
doneButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
EPTService.MMCALCReset(// will create a new EPT object on the server
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
marginalGrid.clear(true);
pearsonGrid.clear(true);
checkBoxList.clear();
corTable.clear(true); //has the buttons which determine events to correlate
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
}
});
;
return;
}
});
RootPanel.get("currentStepContainer").add(currentStep);
RootPanel.get("correlationListContainer").add(corTable);
RootPanel.get("extendButtonContainer").add(extendButton);
RootPanel.get("addEventContainer").add(addEventButton);
RootPanel.get("doneContainer").add(doneButton);
RootPanel.get("marginalEventContainer").add(marginalEvent);
RootPanel.get("currentValueContainer").add(currentValue);
RootPanel.get("lowerBoundContainer").add(lowerBound);
RootPanel.get("newValueContainer").add(newValue);
RootPanel.get("upperBoundContainer").add(upperBound);
RootPanel.get("setValueContainer").add(setValueButton);
RootPanel.get("marginalGridContainer").add(marginalScrollPanel);
RootPanel.get("jointGridContainer").add(jointScrollPanel);
RootPanel.get("powerSubsetContainer").add(subsetScrollPanel);
RootPanel.get("showMarginalButtonContainer").add(showMarginalButton);
RootPanel.get("correlationListOKContainer").add(correlationListOK);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box for adding a new event (name)
final DialogBox addEventDialogBox = new DialogBox();
addEventDialogBox.setText("Name New Event");
addEventDialogBox.setAnimationEnabled(true);
final TextBox eventField = new TextBox();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("Enter Name"));
dialogVPanel.add(eventField);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(extendButton);
addEventDialogBox.setWidget(dialogVPanel);
//Add a handler for "show marginal"
class ShowMarginal implements ClickHandler{
public void onClick(ClickEvent event){
getMarginal();
}
private void getMarginal() {
//EPTService.getPearsonCorrelations(
EPTService.getPearsonCorrelations(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] pearsonCors){
int j = 0;
pearsonGrid.setText(j, 0, "Power Set Index");
pearsonGrid.setText(j, 1, "Pearson Correlation");
j += 1;
for(String cor: pearsonCors){
pearsonGrid.setText(j, 0, Integer.toString(j-1));
pearsonGrid.setText(j, 1, cor);
j++;
}
}
});
EPTService.getMarginalDistribution(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] marginalDistribution){
int j = 0;
marginalGrid.setText(j, 0, "Power Set Index");
marginalGrid.setText(j, 1, "Marginal Probability");
j += 1;
for(String prob: marginalDistribution){
marginalGrid.setText(j, 0, Integer.toString(j-1));
marginalGrid.setText(j, 1, prob);
j++;
}
}
});
}
}
final ShowMarginal showMarginal = new ShowMarginal();
showMarginalButton.addClickHandler(showMarginal);
class Extender implements ClickHandler, KeyUpHandler{
Extender(){};
/* private void coreCorrelationListOK(){
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
*/ public void onClick(ClickEvent event){
getCorrelatesAndExtend();
}
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
getCorrelatesAndExtend();
}
}
private void getCorrelatesAndExtend(){
nameField.setText(eventField.getText());
eventField.setText("");
addEventDialogBox.hide();
CheckBox nextCB = new CheckBox(nameField.getText());
nextCB.setEnabled(false);
nextCB.setValue(true);
int oldCorCount = corTable.getRowCount();
corTable.setWidget(oldCorCount, 0, nextCB);
checkBoxList.add(nextCB);
if(oldCorCount > 0){
correlationListOK.setVisible(true);
correlationListOK.setFocus(true);
correlationListOK.setEnabled(true);
extendButton.setEnabled(false);
currentStep.setText("Make sure important correlates (only) are checked; then push 'Correlation List OK' button.");
}else{
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
}
private void coreExtender() {
int correlators[] = new int[32];
int cCount = 0; // the number of events to be used as constraints
int cbCount = 0;
extendButton.setEnabled(false);
int cblLen = checkBoxList.size() - 1;// the new CB take out of length
for(int k = 0; k < cblLen; k++){// get the checked boxes (except for the new variable) and put them in the list first
if(checkBoxList.get(k).getValue()){
correlators[cCount++] = k;
}
}
int ncCount = cCount;
cbCount = 0;
for(CheckBox x: checkBoxList){// puts the on checked boxes in the list
if(! x.getValue()){// depends on CB for new value being checked
correlators[ncCount++] = cbCount;
}
cbCount++;
}
correlators[cbCount-1] = cbCount - 1;// this correctly puts the new event in the list last
EPTService.MMCALC(nameField.getText(), correlators, cCount,
new AsyncCallback<String[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
/*
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
*/
}
public void onSuccess(String[]range) {
// range = {cv, down, up, next}
lowerBound.setText(range[1]);
currentValue.setText(range[0]);
upperBound.setText(range[2]);
for(CheckBox x: checkBoxList){
x.setEnabled(true);
}
marginalEvent.setText(nameField.getText());
nameField.setText(null);
extendButton.setEnabled(false);
nameField.setEnabled(false);
nameField.setText("");
setValueButton.setEnabled(true);
correlationListOK.setEnabled(false);
newValue.setFocus(true);
newValue.selectAll();
}
});// end of MMCALC
}
}
final Extender extender = new Extender();
extendButton.addClickHandler(extender);
eventField.addKeyUpHandler(extender);
class CorrelationsOKHandler implements ClickHandler, KeyUpHandler{
CorrelationsOKHandler(){
correlationListOK.setEnabled(false);
correlationListOK.setFocus(false);
}
public void onKeyUp(KeyUpEvent event){
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
coreCorrelationListOK();
}
}
public void onClick(ClickEvent event){
coreCorrelationListOK();
}
private void coreCorrelationListOK(){
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
extender.coreExtender();
}
}
CorrelationsOKHandler correlationHandler = new CorrelationsOKHandler();
correlationListOK.addClickHandler(correlationHandler);
correlationListOK.addKeyUpHandler(correlationHandler);
class SetValueHandler implements ClickHandler, KeyUpHandler{
public void onClick(ClickEvent event) {
coreSetValue( );
}
private void coreSetValue() {
//get the new probability value over to mmc which has hopefully been initialized
double desiredValue = new Double(newValue.getText());
EPTService.MMCALC(desiredValue,
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[]range){//setValue
// range = {cv, down, up, next}
if(range[3].equals(new String("done"))){
setValueButton.setEnabled(false);
extendButton.setEnabled(true);
nameField.setEnabled(true);
marginalEvent.setText("");
newValue.setText("");
currentValue.setText("");
nameField.setFocus(true);
currentStep.setText("Ready to Add an Effect");
upperBound.setText("");
lowerBound.setText("");
addEventButton.setEnabled(true);
addEventButton.setFocus(true);
}else{
lowerBound.setText(range[1]);
currentValue.setText(range[0]);
upperBound.setText(range[2]);
for(CheckBox x: checkBoxList){
x.setEnabled(true);
}
marginalEvent.setText(range[3]);
setValueButton.setEnabled(true);
newValue.setText(range[0]);
newValue.selectAll();
}
showMarginal.getMarginal();
}
});
}
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
coreSetValue();
}
}
}
SetValueHandler settingValue = new SetValueHandler();
setValueButton.addClickHandler(settingValue);
newValue.addKeyUpHandler(settingValue);
class AddEventClickHandler implements ClickHandler, KeyUpHandler{
public void onClick(ClickEvent theClick){
coreEventAdder();
theClick.stopPropagation();
}
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
coreEventAdder();
event.stopPropagation();
}
}
private void coreEventAdder(){
addEventButton.setEnabled(false);
addEventDialogBox.center();
addEventDialogBox.show();
//eventField.setFocus(true); // would like to do this but then keyUp in the event dialog is triggered by this very event!
addEventDialogBox.setModal(true);
}
}
addEventButton.addClickHandler(new AddEventClickHandler());
addEventButton.setFocus(true);
}
catch(Exception e){
String message = e.getMessage();
message = null;
}
}
}
| true | true | public void onModuleLoad() {
try{
/* for use in setting focus in event naming dialog
final EventBus eventBus = GWT.create(SimpleEventBus.class);
class ReadyForFocus extends GwtEvent<EventHandler>{
public Type<EventHandler> TYPE = new Type<EventHandler>();
@Override
public com.google.gwt.event.shared.GwtEvent.Type<EventHandler> getAssociatedType(){
return (Type<EventHandler>)TYPE;
}
@Override
protected void dispatch(EventHandler handler){
}
}
*/
EPTService.MMCALCReset(// resets the server without saving anything
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
}
});
final TextArea currentStep = new TextArea();
currentStep.setText("Ready to Add an Effect");
currentStep.setReadOnly(true);
currentStep.setStylePrimaryName("currentStep");
final Button extendButton = new Button("Extend");
final Button addEventButton = new Button("Add Effect");
addEventButton.setStylePrimaryName("addEvent");
addEventButton.setFocus(true);
final TextBox nameField = new TextBox();
nameField.setText("New Effect");
final Button doneButton = new Button("Done");
doneButton.setStylePrimaryName("DoneStyle");
doneButton.setTitle("The EPT is complete");
final TextBox marginalEvent = new TextBox();
marginalEvent.setText("0");
marginalEvent.setTitle("Index of powerset of base events in order added");
final TextBox currentValue = new TextBox();
currentValue.setTitle("Current probability of indexed event");
currentValue.setText("1.0");
currentValue.setReadOnly(true);
final Label lowerBound = new Label();
lowerBound.setText("<=");
lowerBound.setTitle("Minimum value of indexed event");
lowerBound.setStylePrimaryName("lowerBound");
final TextBox newValue = new TextBox();
newValue.setText("1.0");
newValue.setTitle("Edit probability of indexed event");
final Label upperBound = new Label();
upperBound.setText(">=");
upperBound.setTitle("Maximum value of indexed event");
final Button setValueButton = new Button("Set Value");
setValueButton.setFocus(false);
setValueButton.setEnabled(false);
setValueButton.setStyleName("valueButton");
final Button showMarginalButton = new Button("Show Marginal");
showMarginalButton.setStylePrimaryName("showMarginal");
final Button correlationListOK = new Button("Correlation List OK");
correlationListOK.setStylePrimaryName("correlationListOK");
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
final ArrayList<CheckBox> checkBoxList = new ArrayList<CheckBox>();
final FlexTable corTable = new FlexTable();
final Grid marginalGrid = new Grid(64,2);
marginalGrid.setBorderWidth(1);
marginalGrid.setText(0, 0, "1.0");
final Grid subsetGrid = new Grid(64,2);
subsetGrid.setBorderWidth(1);
final Grid pearsonGrid = new Grid(64,2);
pearsonGrid.setStylePrimaryName("jointGrid");
pearsonGrid.setBorderWidth(1);
pearsonGrid.setText(0, 00, "1.0");
pearsonGrid.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
com.google.gwt.user.client.ui.HTMLTable.Cell clickedCell = pearsonGrid.getCellForEvent(e);
if(clickedCell != null){
String styleNames = pearsonGrid.getStyleName();
String OriginalprimaryStyle = pearsonGrid.getStylePrimaryName();
int cellIndex = clickedCell.getCellIndex();
int rowIndex = clickedCell.getRowIndex();
String primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
pearsonGrid.getRowFormatter().setStyleName(rowIndex, "selected");
pearsonGrid.getCellFormatter().setStyleName(0, 0, "columnHeader");
primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
primaryStyle = pearsonGrid.getRowFormatter().getStyleName(rowIndex);
int psIndex= new Integer(pearsonGrid.getHTML(rowIndex, cellIndex)).intValue();
int j = 0;
int k = 0;
for(CheckBox cb: checkBoxList){
if(((psIndex&(1<<j)) != 0)){
String name = cb.getText();
subsetGrid.setText(k++, 0, name);
}
j += 1;
}
}
}
});
final ScrollPanel marginalScrollPanel = new ScrollPanel(marginalGrid);
marginalScrollPanel.setHeight("200px");
marginalScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel jointScrollPanel = new ScrollPanel(pearsonGrid);
jointScrollPanel.setHeight("200px");
jointScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel subsetScrollPanel = new ScrollPanel(subsetGrid);
subsetScrollPanel.setHeight("200px");
subsetScrollPanel.setAlwaysShowScrollBars(true);
// We can add style names to widgets
// RootPanel.setStyleName("outerFrame");
doneButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
EPTService.MMCALCReset(// will create a new EPT object on the server
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
marginalGrid.clear(true);
pearsonGrid.clear(true);
checkBoxList.clear();
corTable.clear(true); //has the buttons which determine events to correlate
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
}
});
;
return;
}
});
RootPanel.get("currentStepContainer").add(currentStep);
RootPanel.get("correlationListContainer").add(corTable);
RootPanel.get("extendButtonContainer").add(extendButton);
RootPanel.get("addEventContainer").add(addEventButton);
RootPanel.get("doneContainer").add(doneButton);
RootPanel.get("marginalEventContainer").add(marginalEvent);
RootPanel.get("currentValueContainer").add(currentValue);
RootPanel.get("lowerBoundContainer").add(lowerBound);
RootPanel.get("newValueContainer").add(newValue);
RootPanel.get("upperBoundContainer").add(upperBound);
RootPanel.get("setValueContainer").add(setValueButton);
RootPanel.get("marginalGridContainer").add(marginalScrollPanel);
RootPanel.get("jointGridContainer").add(jointScrollPanel);
RootPanel.get("powerSubsetContainer").add(subsetScrollPanel);
RootPanel.get("showMarginalButtonContainer").add(showMarginalButton);
RootPanel.get("correlationListOKContainer").add(correlationListOK);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box for adding a new event (name)
final DialogBox addEventDialogBox = new DialogBox();
addEventDialogBox.setText("Name New Event");
addEventDialogBox.setAnimationEnabled(true);
final TextBox eventField = new TextBox();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("Enter Name"));
dialogVPanel.add(eventField);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(extendButton);
addEventDialogBox.setWidget(dialogVPanel);
//Add a handler for "show marginal"
class ShowMarginal implements ClickHandler{
public void onClick(ClickEvent event){
getMarginal();
}
private void getMarginal() {
//EPTService.getPearsonCorrelations(
EPTService.getPearsonCorrelations(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] pearsonCors){
int j = 0;
pearsonGrid.setText(j, 0, "Power Set Index");
pearsonGrid.setText(j, 1, "Pearson Correlation");
j += 1;
for(String cor: pearsonCors){
pearsonGrid.setText(j, 0, Integer.toString(j-1));
pearsonGrid.setText(j, 1, cor);
j++;
}
}
});
EPTService.getMarginalDistribution(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] marginalDistribution){
int j = 0;
marginalGrid.setText(j, 0, "Power Set Index");
marginalGrid.setText(j, 1, "Marginal Probability");
j += 1;
for(String prob: marginalDistribution){
marginalGrid.setText(j, 0, Integer.toString(j-1));
marginalGrid.setText(j, 1, prob);
j++;
}
}
});
}
}
final ShowMarginal showMarginal = new ShowMarginal();
showMarginalButton.addClickHandler(showMarginal);
class Extender implements ClickHandler, KeyUpHandler{
Extender(){};
/* private void coreCorrelationListOK(){
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
*/ public void onClick(ClickEvent event){
getCorrelatesAndExtend();
}
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
getCorrelatesAndExtend();
}
}
private void getCorrelatesAndExtend(){
nameField.setText(eventField.getText());
eventField.setText("");
addEventDialogBox.hide();
CheckBox nextCB = new CheckBox(nameField.getText());
nextCB.setEnabled(false);
nextCB.setValue(true);
int oldCorCount = corTable.getRowCount();
corTable.setWidget(oldCorCount, 0, nextCB);
checkBoxList.add(nextCB);
if(oldCorCount > 0){
correlationListOK.setVisible(true);
correlationListOK.setFocus(true);
correlationListOK.setEnabled(true);
extendButton.setEnabled(false);
currentStep.setText("Make sure important correlates (only) are checked; then push 'Correlation List OK' button.");
}else{
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
}
private void coreExtender() {
int correlators[] = new int[32];
int cCount = 0; // the number of events to be used as constraints
int cbCount = 0;
extendButton.setEnabled(false);
int cblLen = checkBoxList.size() - 1;// the new CB take out of length
for(int k = 0; k < cblLen; k++){// get the checked boxes (except for the new variable) and put them in the list first
if(checkBoxList.get(k).getValue()){
correlators[cCount++] = k;
}
}
int ncCount = cCount;
cbCount = 0;
for(CheckBox x: checkBoxList){// puts the on checked boxes in the list
if(! x.getValue()){// depends on CB for new value being checked
correlators[ncCount++] = cbCount;
}
cbCount++;
}
correlators[cbCount-1] = cbCount - 1;// this correctly puts the new event in the list last
EPTService.MMCALC(nameField.getText(), correlators, cCount,
new AsyncCallback<String[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
/*
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
*/
}
public void onSuccess(String[]range) {
// range = {cv, down, up, next}
lowerBound.setText(range[1]);
currentValue.setText(range[0]);
upperBound.setText(range[2]);
for(CheckBox x: checkBoxList){
x.setEnabled(true);
}
marginalEvent.setText(nameField.getText());
nameField.setText(null);
extendButton.setEnabled(false);
nameField.setEnabled(false);
nameField.setText("");
setValueButton.setEnabled(true);
correlationListOK.setEnabled(false);
newValue.setFocus(true);
newValue.selectAll();
}
});// end of MMCALC
}
}
| public void onModuleLoad() {
try{
/* for use in setting focus in event naming dialog
final EventBus eventBus = GWT.create(SimpleEventBus.class);
class ReadyForFocus extends GwtEvent<EventHandler>{
public Type<EventHandler> TYPE = new Type<EventHandler>();
@Override
public com.google.gwt.event.shared.GwtEvent.Type<EventHandler> getAssociatedType(){
return (Type<EventHandler>)TYPE;
}
@Override
protected void dispatch(EventHandler handler){
}
}
*/
EPTService.MMCALCReset(// resets the server without saving anything
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
}
});
final TextArea currentStep = new TextArea();
currentStep.setText("Ready to Add an Effect");
currentStep.setReadOnly(true);
currentStep.setStylePrimaryName("currentStep");
final Button extendButton = new Button("Extend");
final Button addEventButton = new Button("Add Effect");
addEventButton.setStylePrimaryName("addEvent");
addEventButton.setFocus(true);
final TextBox nameField = new TextBox();
nameField.setText("New Effect");
final Button doneButton = new Button("Done");
doneButton.setStylePrimaryName("DoneStyle");
doneButton.setTitle("The EPT is complete");
final TextBox marginalEvent = new TextBox();
marginalEvent.setText("0");
marginalEvent.setTitle("Index of powerset of base events in order added");
final TextBox currentValue = new TextBox();
currentValue.setTitle("Current probability of indexed event");
currentValue.setText("1.0");
currentValue.setReadOnly(true);
final Label lowerBound = new Label();
lowerBound.setText("<=");
lowerBound.setTitle("Minimum value of indexed event");
lowerBound.setStylePrimaryName("lowerBound");
final TextBox newValue = new TextBox();
newValue.setText("1.0");
newValue.setTitle("Edit probability of indexed event");
final Label upperBound = new Label();
upperBound.setText("<=");
upperBound.setTitle("Maximum value of indexed event");
final Button setValueButton = new Button("Set Value");
setValueButton.setFocus(false);
setValueButton.setEnabled(false);
setValueButton.setStyleName("valueButton");
final Button showMarginalButton = new Button("Show Marginal");
showMarginalButton.setStylePrimaryName("showMarginal");
final Button correlationListOK = new Button("Correlation List OK");
correlationListOK.setStylePrimaryName("correlationListOK");
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
final ArrayList<CheckBox> checkBoxList = new ArrayList<CheckBox>();
final FlexTable corTable = new FlexTable();
final Grid marginalGrid = new Grid(64,2);
marginalGrid.setBorderWidth(1);
marginalGrid.setText(0, 0, "1.0");
final Grid subsetGrid = new Grid(64,2);
subsetGrid.setBorderWidth(1);
final Grid pearsonGrid = new Grid(64,2);
pearsonGrid.setStylePrimaryName("jointGrid");
pearsonGrid.setBorderWidth(1);
pearsonGrid.setText(0, 00, "1.0");
pearsonGrid.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
com.google.gwt.user.client.ui.HTMLTable.Cell clickedCell = pearsonGrid.getCellForEvent(e);
if(clickedCell != null){
String styleNames = pearsonGrid.getStyleName();
String OriginalprimaryStyle = pearsonGrid.getStylePrimaryName();
int cellIndex = clickedCell.getCellIndex();
int rowIndex = clickedCell.getRowIndex();
String primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
pearsonGrid.getRowFormatter().setStyleName(rowIndex, "selected");
pearsonGrid.getCellFormatter().setStyleName(0, 0, "columnHeader");
primaryStyle = pearsonGrid.getRowFormatter().getStylePrimaryName(rowIndex);
primaryStyle = pearsonGrid.getRowFormatter().getStyleName(rowIndex);
int psIndex= new Integer(pearsonGrid.getHTML(rowIndex, cellIndex)).intValue();
int j = 0;
int k = 0;
for(CheckBox cb: checkBoxList){
if(((psIndex&(1<<j)) != 0)){
String name = cb.getText();
subsetGrid.setText(k++, 0, name);
}
j += 1;
}
}
}
});
final ScrollPanel marginalScrollPanel = new ScrollPanel(marginalGrid);
marginalScrollPanel.setHeight("200px");
marginalScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel jointScrollPanel = new ScrollPanel(pearsonGrid);
jointScrollPanel.setHeight("200px");
jointScrollPanel.setAlwaysShowScrollBars(true);
final ScrollPanel subsetScrollPanel = new ScrollPanel(subsetGrid);
subsetScrollPanel.setHeight("200px");
subsetScrollPanel.setAlwaysShowScrollBars(true);
// We can add style names to widgets
// RootPanel.setStyleName("outerFrame");
doneButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e){
EPTService.MMCALCReset(// will create a new EPT object on the server
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] result){
marginalGrid.clear(true);
pearsonGrid.clear(true);
checkBoxList.clear();
corTable.clear(true); //has the buttons which determine events to correlate
correlationListOK.setEnabled(false);
correlationListOK.setVisible(false);
correlationListOK.setFocus(false);
}
});
;
return;
}
});
RootPanel.get("currentStepContainer").add(currentStep);
RootPanel.get("correlationListContainer").add(corTable);
RootPanel.get("extendButtonContainer").add(extendButton);
RootPanel.get("addEventContainer").add(addEventButton);
RootPanel.get("doneContainer").add(doneButton);
RootPanel.get("marginalEventContainer").add(marginalEvent);
RootPanel.get("currentValueContainer").add(currentValue);
RootPanel.get("lowerBoundContainer").add(lowerBound);
RootPanel.get("newValueContainer").add(newValue);
RootPanel.get("upperBoundContainer").add(upperBound);
RootPanel.get("setValueContainer").add(setValueButton);
RootPanel.get("marginalGridContainer").add(marginalScrollPanel);
RootPanel.get("jointGridContainer").add(jointScrollPanel);
RootPanel.get("powerSubsetContainer").add(subsetScrollPanel);
RootPanel.get("showMarginalButtonContainer").add(showMarginalButton);
RootPanel.get("correlationListOKContainer").add(correlationListOK);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box for adding a new event (name)
final DialogBox addEventDialogBox = new DialogBox();
addEventDialogBox.setText("Name New Event");
addEventDialogBox.setAnimationEnabled(true);
final TextBox eventField = new TextBox();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("Enter Name"));
dialogVPanel.add(eventField);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(extendButton);
addEventDialogBox.setWidget(dialogVPanel);
//Add a handler for "show marginal"
class ShowMarginal implements ClickHandler{
public void onClick(ClickEvent event){
getMarginal();
}
private void getMarginal() {
//EPTService.getPearsonCorrelations(
EPTService.getPearsonCorrelations(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] pearsonCors){
int j = 0;
pearsonGrid.setText(j, 0, "Power Set Index");
pearsonGrid.setText(j, 1, "Pearson Correlation");
j += 1;
for(String cor: pearsonCors){
pearsonGrid.setText(j, 0, Integer.toString(j-1));
pearsonGrid.setText(j, 1, cor);
j++;
}
}
});
EPTService.getMarginalDistribution(
new AsyncCallback<String[]>(){
public void onFailure(Throwable caught){
}
public void onSuccess(String[] marginalDistribution){
int j = 0;
marginalGrid.setText(j, 0, "Power Set Index");
marginalGrid.setText(j, 1, "Marginal Probability");
j += 1;
for(String prob: marginalDistribution){
marginalGrid.setText(j, 0, Integer.toString(j-1));
marginalGrid.setText(j, 1, prob);
j++;
}
}
});
}
}
final ShowMarginal showMarginal = new ShowMarginal();
showMarginalButton.addClickHandler(showMarginal);
class Extender implements ClickHandler, KeyUpHandler{
Extender(){};
/* private void coreCorrelationListOK(){
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
*/ public void onClick(ClickEvent event){
getCorrelatesAndExtend();
}
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
getCorrelatesAndExtend();
}
}
private void getCorrelatesAndExtend(){
nameField.setText(eventField.getText());
eventField.setText("");
addEventDialogBox.hide();
CheckBox nextCB = new CheckBox(nameField.getText());
nextCB.setEnabled(false);
nextCB.setValue(true);
int oldCorCount = corTable.getRowCount();
corTable.setWidget(oldCorCount, 0, nextCB);
checkBoxList.add(nextCB);
if(oldCorCount > 0){
correlationListOK.setVisible(true);
correlationListOK.setFocus(true);
correlationListOK.setEnabled(true);
extendButton.setEnabled(false);
currentStep.setText("Make sure important correlates (only) are checked; then push 'Correlation List OK' button.");
}else{
correlationListOK.setEnabled(false);
currentStep.setText("Provide probabilities.");
coreExtender();
}
}
private void coreExtender() {
int correlators[] = new int[32];
int cCount = 0; // the number of events to be used as constraints
int cbCount = 0;
extendButton.setEnabled(false);
int cblLen = checkBoxList.size() - 1;// the new CB take out of length
for(int k = 0; k < cblLen; k++){// get the checked boxes (except for the new variable) and put them in the list first
if(checkBoxList.get(k).getValue()){
correlators[cCount++] = k;
}
}
int ncCount = cCount;
cbCount = 0;
for(CheckBox x: checkBoxList){// puts the on checked boxes in the list
if(! x.getValue()){// depends on CB for new value being checked
correlators[ncCount++] = cbCount;
}
cbCount++;
}
correlators[cbCount-1] = cbCount - 1;// this correctly puts the new event in the list last
EPTService.MMCALC(nameField.getText(), correlators, cCount,
new AsyncCallback<String[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
/*
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
*/
}
public void onSuccess(String[]range) {
// range = {cv, down, up, next}
lowerBound.setText(range[1]);
currentValue.setText(range[0]);
upperBound.setText(range[2]);
for(CheckBox x: checkBoxList){
x.setEnabled(true);
}
marginalEvent.setText(nameField.getText());
nameField.setText(null);
extendButton.setEnabled(false);
nameField.setEnabled(false);
nameField.setText("");
setValueButton.setEnabled(true);
correlationListOK.setEnabled(false);
newValue.setFocus(true);
newValue.selectAll();
}
});// end of MMCALC
}
}
|
diff --git a/main/src/com/google/refine/sorting/DateCriterion.java b/main/src/com/google/refine/sorting/DateCriterion.java
index 28e1d8c4..b3e47f46 100644
--- a/main/src/com/google/refine/sorting/DateCriterion.java
+++ b/main/src/com/google/refine/sorting/DateCriterion.java
@@ -1,68 +1,68 @@
/*
Copyright 2010, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.refine.sorting;
import java.util.Calendar;
import java.util.Date;
import com.google.refine.expr.EvalError;
import com.google.refine.expr.ExpressionUtils;
public class DateCriterion extends Criterion {
final static protected EvalError s_error = new EvalError("Not a date");
@Override
public KeyMaker createKeyMaker() {
return new KeyMaker() {
@Override
protected Object makeKey(Object value) {
if (ExpressionUtils.isNonBlankData(value)) {
if (value instanceof Date) {
return value;
} else if (value instanceof Calendar) {
return ((Calendar) value).getTime();
} else {
return s_error;
}
}
- return value;
+ return null;
}
@Override
public int compareKeys(Object key1, Object key2) {
return ((Date) key1).compareTo((Date) key2);
}
};
}
}
| true | true | public KeyMaker createKeyMaker() {
return new KeyMaker() {
@Override
protected Object makeKey(Object value) {
if (ExpressionUtils.isNonBlankData(value)) {
if (value instanceof Date) {
return value;
} else if (value instanceof Calendar) {
return ((Calendar) value).getTime();
} else {
return s_error;
}
}
return value;
}
@Override
public int compareKeys(Object key1, Object key2) {
return ((Date) key1).compareTo((Date) key2);
}
};
}
| public KeyMaker createKeyMaker() {
return new KeyMaker() {
@Override
protected Object makeKey(Object value) {
if (ExpressionUtils.isNonBlankData(value)) {
if (value instanceof Date) {
return value;
} else if (value instanceof Calendar) {
return ((Calendar) value).getTime();
} else {
return s_error;
}
}
return null;
}
@Override
public int compareKeys(Object key1, Object key2) {
return ((Date) key1).compareTo((Date) key2);
}
};
}
|
diff --git a/CubicTestWatirExporter/src/main/java/org/cubictest/exporters/watir/converters/delegates/PageElementAsserterPlain.java b/CubicTestWatirExporter/src/main/java/org/cubictest/exporters/watir/converters/delegates/PageElementAsserterPlain.java
index 4bab3107..b13726db 100644
--- a/CubicTestWatirExporter/src/main/java/org/cubictest/exporters/watir/converters/delegates/PageElementAsserterPlain.java
+++ b/CubicTestWatirExporter/src/main/java/org/cubictest/exporters/watir/converters/delegates/PageElementAsserterPlain.java
@@ -1,145 +1,145 @@
/*******************************************************************************
* Copyright (c) 2005, 2008 Christian Schwarz
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christian Schwarz - initial API and implementation
*******************************************************************************/
package org.cubictest.exporters.watir.converters.delegates;
import static org.cubictest.model.Moderator.*;
import org.cubictest.export.exceptions.ExporterException;
import org.cubictest.exporters.watir.holders.WatirHolder;
import org.cubictest.exporters.watir.utils.WatirUtils;
import org.cubictest.model.IdentifierType;
import org.cubictest.model.Moderator;
import org.cubictest.model.PageElement;
import org.cubictest.model.Text;
import org.cubictest.model.Title;
import org.cubictest.model.formElement.Option;
import org.cubictest.model.formElement.Select;
/**
* Page element converter that uses standard Watir without XPath.
*
* @author Christian Schwarz
*/
public class PageElementAsserterPlain {
public static void handle(WatirHolder watirHolder, PageElement pe) {
String idType = WatirUtils.getMainIdType(pe);
String idValue = WatirUtils.getIdValue(pe.getMainIdentifier());
Moderator moderator = pe.getMainIdentifier().getModerator();
if (pe instanceof Title) {
if (moderator.equals(EQUAL)) {
watirHolder.add("if (ie.title() != " + idValue + ")", 2);
} else {
watirHolder.add("if (ie.title() !~ " + idValue + ")", 2);
}
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 3);
watirHolder.add("end", 2);
}
else if (pe instanceof Option) {
Option option = (Option) pe;
Select select = (Select) option.getParent();
//Check that the parent select list present:
watirHolder.add("if not " + watirHolder.getVariableName(select)
+ ".methods.member?(\"select_value\")", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
if (option.getMainIdentifierType().equals(IdentifierType.LABEL)) {
watirHolder.add(watirHolder.getVariableName(select) + ".getAllContents().each do |optLabel|", 3);
if (moderator.equals(EQUAL)) {
watirHolder.add("if(optLabel == " + idValue + ")", 4);
}
else {
watirHolder.add("if((optLabel =~ " + idValue + ") != nil)", 4);
}
watirHolder.add(watirHolder.getVariableName(option) + " = optLabel", 5);
watirHolder.add("end", 4);
watirHolder.add("end", 3);
}
else if (option.getMainIdentifierType().equals(IdentifierType.VALUE)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".option(:value, " + idValue + ")", 3);
} else if (option.getMainIdentifierType().equals(IdentifierType.INDEX)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".getAllContents()["
+ option.getMainIdentifierValue() + "]", 3);
}
else {
throw new ExporterException(
"Only label, value and index are supported identifierts "
+ "for options in select lists in Watir");
}
watirHolder.add("if (" + watirHolder.getVariableName(option) + " == nil)", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
}
else {
//all other page elements:
if (WatirUtils.hasExternalLabel(pe)) {
//set identifier to "id", the one that the label points to.
watirHolder.add(WatirUtils.getLabelTargetId(pe, watirHolder));
watirHolder.addSeparator();
idValue = watirHolder.getVariableName(pe);
idType = ":id";
}
watirHolder.add("pass = 0", 3);
if (pe instanceof Text) {
String compare = pe.isNot() ? "!=" : "==";
watirHolder.add("while ie.text.index(" + idValue + ") " + compare + " nil do", 3);
}
else {
//all other page elements:
String not = pe.isNot() ? "" : "not ";
IdentifierType mainIdType = pe.getMainIdentifierType();
if ((mainIdType.equals(IdentifierType.SRC) || mainIdType.equals(IdentifierType.HREF))
&& !pe.getMainIdentifierValue().startsWith("http")) {
//SRC or HREF is relative and must be made absolute (add hostname and protocol):
if (pe.getMainIdentifierValue().startsWith("/")) {
//we want to extract protocol and hostname for IE current page, and append our value
idValue = "ie.url[0, ie.url.split('//')[1].index('/') + ie.url.split('//')[0].length + 2] + \"" + pe.getMainIdentifierValue() + "\"";
}
else {
//we want to extract the whole path except last file, and append our value
idValue = "ie.url[0, ie.url.rindex('/')] + \"/" + pe.getMainIdentifierValue() + "\"";
}
}
//save variable
String prefix = "ie";
- if (watirHolder.isInAFrame(pe)) {
+ if (watirHolder.isPageElementWithinFrame(pe)) {
//set prefix to frame
prefix = watirHolder.getVariableName(watirHolder.getParentFrame(pe));
}
watirHolder.add(watirHolder.getVariableName(pe) + " = " + prefix + "." + WatirUtils.getElementType(pe) + "(" + idType + ", " + idValue + ")", 3);
//assert present
watirHolder.add("while " + not + watirHolder.getVariableName(pe) + "." + WatirUtils.getPresentAssertionMethod(pe) + " do", 3);
}
watirHolder.add("if (pass > 20)", 4);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 5);
watirHolder.add("end", 4);
watirHolder.add("sleep 0.1", 4);
watirHolder.add("pass += 1", 4);
watirHolder.add("end", 3);
}
}
}
| true | true | public static void handle(WatirHolder watirHolder, PageElement pe) {
String idType = WatirUtils.getMainIdType(pe);
String idValue = WatirUtils.getIdValue(pe.getMainIdentifier());
Moderator moderator = pe.getMainIdentifier().getModerator();
if (pe instanceof Title) {
if (moderator.equals(EQUAL)) {
watirHolder.add("if (ie.title() != " + idValue + ")", 2);
} else {
watirHolder.add("if (ie.title() !~ " + idValue + ")", 2);
}
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 3);
watirHolder.add("end", 2);
}
else if (pe instanceof Option) {
Option option = (Option) pe;
Select select = (Select) option.getParent();
//Check that the parent select list present:
watirHolder.add("if not " + watirHolder.getVariableName(select)
+ ".methods.member?(\"select_value\")", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
if (option.getMainIdentifierType().equals(IdentifierType.LABEL)) {
watirHolder.add(watirHolder.getVariableName(select) + ".getAllContents().each do |optLabel|", 3);
if (moderator.equals(EQUAL)) {
watirHolder.add("if(optLabel == " + idValue + ")", 4);
}
else {
watirHolder.add("if((optLabel =~ " + idValue + ") != nil)", 4);
}
watirHolder.add(watirHolder.getVariableName(option) + " = optLabel", 5);
watirHolder.add("end", 4);
watirHolder.add("end", 3);
}
else if (option.getMainIdentifierType().equals(IdentifierType.VALUE)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".option(:value, " + idValue + ")", 3);
} else if (option.getMainIdentifierType().equals(IdentifierType.INDEX)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".getAllContents()["
+ option.getMainIdentifierValue() + "]", 3);
}
else {
throw new ExporterException(
"Only label, value and index are supported identifierts "
+ "for options in select lists in Watir");
}
watirHolder.add("if (" + watirHolder.getVariableName(option) + " == nil)", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
}
else {
//all other page elements:
if (WatirUtils.hasExternalLabel(pe)) {
//set identifier to "id", the one that the label points to.
watirHolder.add(WatirUtils.getLabelTargetId(pe, watirHolder));
watirHolder.addSeparator();
idValue = watirHolder.getVariableName(pe);
idType = ":id";
}
watirHolder.add("pass = 0", 3);
if (pe instanceof Text) {
String compare = pe.isNot() ? "!=" : "==";
watirHolder.add("while ie.text.index(" + idValue + ") " + compare + " nil do", 3);
}
else {
//all other page elements:
String not = pe.isNot() ? "" : "not ";
IdentifierType mainIdType = pe.getMainIdentifierType();
if ((mainIdType.equals(IdentifierType.SRC) || mainIdType.equals(IdentifierType.HREF))
&& !pe.getMainIdentifierValue().startsWith("http")) {
//SRC or HREF is relative and must be made absolute (add hostname and protocol):
if (pe.getMainIdentifierValue().startsWith("/")) {
//we want to extract protocol and hostname for IE current page, and append our value
idValue = "ie.url[0, ie.url.split('//')[1].index('/') + ie.url.split('//')[0].length + 2] + \"" + pe.getMainIdentifierValue() + "\"";
}
else {
//we want to extract the whole path except last file, and append our value
idValue = "ie.url[0, ie.url.rindex('/')] + \"/" + pe.getMainIdentifierValue() + "\"";
}
}
//save variable
String prefix = "ie";
if (watirHolder.isInAFrame(pe)) {
//set prefix to frame
prefix = watirHolder.getVariableName(watirHolder.getParentFrame(pe));
}
watirHolder.add(watirHolder.getVariableName(pe) + " = " + prefix + "." + WatirUtils.getElementType(pe) + "(" + idType + ", " + idValue + ")", 3);
//assert present
watirHolder.add("while " + not + watirHolder.getVariableName(pe) + "." + WatirUtils.getPresentAssertionMethod(pe) + " do", 3);
}
watirHolder.add("if (pass > 20)", 4);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 5);
watirHolder.add("end", 4);
watirHolder.add("sleep 0.1", 4);
watirHolder.add("pass += 1", 4);
watirHolder.add("end", 3);
}
}
| public static void handle(WatirHolder watirHolder, PageElement pe) {
String idType = WatirUtils.getMainIdType(pe);
String idValue = WatirUtils.getIdValue(pe.getMainIdentifier());
Moderator moderator = pe.getMainIdentifier().getModerator();
if (pe instanceof Title) {
if (moderator.equals(EQUAL)) {
watirHolder.add("if (ie.title() != " + idValue + ")", 2);
} else {
watirHolder.add("if (ie.title() !~ " + idValue + ")", 2);
}
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 3);
watirHolder.add("end", 2);
}
else if (pe instanceof Option) {
Option option = (Option) pe;
Select select = (Select) option.getParent();
//Check that the parent select list present:
watirHolder.add("if not " + watirHolder.getVariableName(select)
+ ".methods.member?(\"select_value\")", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
if (option.getMainIdentifierType().equals(IdentifierType.LABEL)) {
watirHolder.add(watirHolder.getVariableName(select) + ".getAllContents().each do |optLabel|", 3);
if (moderator.equals(EQUAL)) {
watirHolder.add("if(optLabel == " + idValue + ")", 4);
}
else {
watirHolder.add("if((optLabel =~ " + idValue + ") != nil)", 4);
}
watirHolder.add(watirHolder.getVariableName(option) + " = optLabel", 5);
watirHolder.add("end", 4);
watirHolder.add("end", 3);
}
else if (option.getMainIdentifierType().equals(IdentifierType.VALUE)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".option(:value, " + idValue + ")", 3);
} else if (option.getMainIdentifierType().equals(IdentifierType.INDEX)) {
watirHolder.add(watirHolder.getVariableName(option) + " = "
+ watirHolder.getVariableName(select)
+ ".getAllContents()["
+ option.getMainIdentifierValue() + "]", 3);
}
else {
throw new ExporterException(
"Only label, value and index are supported identifierts "
+ "for options in select lists in Watir");
}
watirHolder.add("if (" + watirHolder.getVariableName(option) + " == nil)", 3);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 4);
watirHolder.add("end", 3);
}
else {
//all other page elements:
if (WatirUtils.hasExternalLabel(pe)) {
//set identifier to "id", the one that the label points to.
watirHolder.add(WatirUtils.getLabelTargetId(pe, watirHolder));
watirHolder.addSeparator();
idValue = watirHolder.getVariableName(pe);
idType = ":id";
}
watirHolder.add("pass = 0", 3);
if (pe instanceof Text) {
String compare = pe.isNot() ? "!=" : "==";
watirHolder.add("while ie.text.index(" + idValue + ") " + compare + " nil do", 3);
}
else {
//all other page elements:
String not = pe.isNot() ? "" : "not ";
IdentifierType mainIdType = pe.getMainIdentifierType();
if ((mainIdType.equals(IdentifierType.SRC) || mainIdType.equals(IdentifierType.HREF))
&& !pe.getMainIdentifierValue().startsWith("http")) {
//SRC or HREF is relative and must be made absolute (add hostname and protocol):
if (pe.getMainIdentifierValue().startsWith("/")) {
//we want to extract protocol and hostname for IE current page, and append our value
idValue = "ie.url[0, ie.url.split('//')[1].index('/') + ie.url.split('//')[0].length + 2] + \"" + pe.getMainIdentifierValue() + "\"";
}
else {
//we want to extract the whole path except last file, and append our value
idValue = "ie.url[0, ie.url.rindex('/')] + \"/" + pe.getMainIdentifierValue() + "\"";
}
}
//save variable
String prefix = "ie";
if (watirHolder.isPageElementWithinFrame(pe)) {
//set prefix to frame
prefix = watirHolder.getVariableName(watirHolder.getParentFrame(pe));
}
watirHolder.add(watirHolder.getVariableName(pe) + " = " + prefix + "." + WatirUtils.getElementType(pe) + "(" + idType + ", " + idValue + ")", 3);
//assert present
watirHolder.add("while " + not + watirHolder.getVariableName(pe) + "." + WatirUtils.getPresentAssertionMethod(pe) + " do", 3);
}
watirHolder.add("if (pass > 20)", 4);
watirHolder.add("raise " + WatirHolder.TEST_STEP_FAILED, 5);
watirHolder.add("end", 4);
watirHolder.add("sleep 0.1", 4);
watirHolder.add("pass += 1", 4);
watirHolder.add("end", 3);
}
}
|
diff --git a/src/vooga/rts/gamedesign/sprite/gamesprites/interactive/InteractiveEntity.java b/src/vooga/rts/gamedesign/sprite/gamesprites/interactive/InteractiveEntity.java
index d6f0bf4f..fa5e24ce 100644
--- a/src/vooga/rts/gamedesign/sprite/gamesprites/interactive/InteractiveEntity.java
+++ b/src/vooga/rts/gamedesign/sprite/gamesprites/interactive/InteractiveEntity.java
@@ -1,258 +1,258 @@
package vooga.rts.gamedesign.sprite.gamesprites.interactive;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import vooga.rts.gamedesign.action.Action;
import vooga.rts.gamedesign.sprite.gamesprites.GameEntity;
import vooga.rts.gamedesign.sprite.gamesprites.IAttackable;
import vooga.rts.gamedesign.sprite.gamesprites.Projectile;
import vooga.rts.gamedesign.strategy.attackstrategy.AttackStrategy;
import vooga.rts.gamedesign.strategy.attackstrategy.CannotAttack;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.buildings.Building;
import vooga.rts.gamedesign.upgrades.UpgradeNode;
import vooga.rts.gamedesign.upgrades.UpgradeTree;
import vooga.rts.util.Camera;
import vooga.rts.util.Location3D;
import vooga.rts.util.Pixmap;
import vooga.rts.util.Sound;
/**
* This class is the extension of GameEntity. It represents shapes that are
* able to upgrade (to either stat of its current properties or add new
* properties) and attack others.
*
* @author Ryan Fishel
* @author Kevin Oh
* @author Francesco Agosti
* @author Wenshun Liu
*
*/
public abstract class InteractiveEntity extends GameEntity implements IAttackable{
private static final int LOCATION_OFFSET = 20;
//Default speed
private static int DEFAULT_INTERACTIVEENTITY_SPEED = 150;
private boolean isSelected;
private UpgradeTree myUpgradeTree;
private Sound mySound;
private AttackStrategy myAttackStrategy;
private int myArmor;
private List<Action> myActions;
/**
* Creates a new interactive entity.
* @param image is the image of the interactive entity
* @param center is the location of the interactive entity
* @param size is the dimension of the interactive entity
* @param sound is the sound the interactive entity makes
* @param teamID is the ID of the team that the interactive entity is on
* @param health is the health of the interactive entity
*/
public InteractiveEntity (Pixmap image, Location3D center, Dimension size, Sound sound, int playerID, int health) {
super(image, center, size, playerID, health);
//myMakers = new HashMap<String, Factory>(); //WHERE SHOULD THIS GO?
mySound = sound;
myAttackStrategy = new CannotAttack();
myActions = new ArrayList<Action>();
isSelected = false;
}
/*
* Ze clone method
*/
//TODO: Make abstract
public InteractiveEntity copy(){
return null;
}
/**
* Returns the upgrade tree for the interactive entity.
* @return the upgrade tree for the interactive entity
*/
public UpgradeTree getUpgradeTree() {
return myUpgradeTree;
}
public void setUpgradeTree(UpgradeTree upgradeTree, int playerID) {
myUpgradeTree = upgradeTree;
}
public int getSpeed() {
return DEFAULT_INTERACTIVEENTITY_SPEED;
}
/**
* This method specifies that the interactive entity is getting attacked
* so it calls the attack method of the interactive entity on itself.
* @param interactiveEntity is the interactive entity that is attacking this interactive
* entity
*/
public void getAttacked(InteractiveEntity interactiveEntity) {
interactiveEntity.attack(this);
}
/**
* Returns the sound that the interactive entity makes.
* @return the sound of the interactive entity
*/
public Sound getSound() {
return mySound;
}
/**
* Sets the isSelected boolean to the passed in bool value.
*/
public void select(boolean selected) {
isSelected = selected;
}
public List<Action> getActions() {
return myActions;
}
/**
* This method specifies that the interactive entity is attacking an
* IAttackable. It checks to see if the IAttackable is in its range, it
* sets the state of the interactive entity to attacking, and then it
* attacks the IAttackable if the state of the interactive entity lets it
* attack.
* @param attackable is the IAttackable that is being attacked.
*/
public void attack(IAttackable attackable) {
double distance = Math.sqrt(Math.pow(getWorldLocation().getX() - ((InteractiveEntity) attackable).getWorldLocation().getX(), 2) + Math.pow(getWorldLocation().getY() - ((InteractiveEntity) attackable).getWorldLocation().getY(), 2));
if(!this.isDead()) {
//getEntityState().setAttackingState(AttackingState.ATTACKING);
getEntityState().attack();
//setVelocity(getVelocity().getAngle(), 0);
//getGameState().setMovementState(MovementState.STATIONARY);
if(getEntityState().canAttack()) {
myAttackStrategy.attack(attackable, distance);
}
}
}
//below are the recognize methods to handle different input parameters from controller
/**
* If the passed in parameter is type Location3D, moves the InteractiveEntity to that
* location
* @param location - the location to move to
*/
public void recognize (Location3D location) {
move(location);
}
/**
* If the passed in parameter is another InteractiveEntity, checks to see if it is a
* Building and can be occupied, checks to see if it is an enemy, and if so, switches
* to attack state.
* Defaults to move to the center of the other InteractiveEntity
* @param other - the other InteractiveEntity
*/
public void recognize (InteractiveEntity other) {
if(other instanceof Building) {
//occupy or do something
}
if(isEnemy(other)) {
//switch to attack state
}
move(other.getWorldLocation());
}
/**
* Sets the attack strategy for an interactive. Can set the interactive
* to CanAttack or to CannotAttack and then can specify how it would
* attack.
*
* @param newStrategy is the new attack strategy that the interactive
* will have
*/
public void setAttackStrategy(AttackStrategy newStrategy){
myAttackStrategy = newStrategy;
}
/**
* Returns the current attack strategy of the interactive
*
* @return the current attack strategy
*/
public AttackStrategy getAttackStrategy () {
return myAttackStrategy;
}
public int calculateDamage(int damage) {
return damage * (1-(myArmor/(myArmor+100)));
}
/**
* upgrades the interactive based on the selected upgrade
* @param upgradeNode is the upgrade that the interactive will get
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public void upgrade (UpgradeNode upgradeNode) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
//upgradeNode.apply(upgradeNode.getUpgradeTree().getUsers());
}
public UpgradeTree getTree(){
return myUpgradeTree;
}
/**
* Sees whether the passed in InteractiveEntity is an enemy by checking if player IDs do
* not match
* @param InteractiveEntity other - the other InteractiveEntity to compare
* @return whether the other InteractiveEntity is an enemy
*/
public boolean isEnemy(InteractiveEntity other) {
return getPlayerID() != other.getPlayerID();
}
public Action findAction(String name) {
for (Action a: myActions) {
if (a.getName().equals(name)) {
return a;
}
}
return null;
}
@Override
public void update(double elapsedTime){
super.update(elapsedTime);
if(myAttackStrategy.getCanAttack() && !getAttackStrategy().getWeapons().isEmpty()){
myAttackStrategy.getWeapons().get(myAttackStrategy.getWeaponIndex()).update(elapsedTime);
}
}
@Override
public void paint(Graphics2D pen) {
//pen.rotate(getVelocity().getAngle());
//should probably use the getBottom, getHeight etc...implement them
Point2D selectLocation = Camera.instance().worldToView(getWorldLocation());
- Rectangle2D healthBar = new Rectangle2D.Double((int)selectLocation.getX()-LOCATION_OFFSET, (int)(selectLocation.getY()-3*LOCATION_OFFSET), getHealth()/2, 10);
+ Rectangle2D healthBar = new Rectangle2D.Double((int)selectLocation.getX()-LOCATION_OFFSET, (int)(selectLocation.getY()-3*LOCATION_OFFSET), 50 * getHealth()/getMaxHealth(), 5);
pen.setColor(Color.GREEN);
pen.fill(healthBar);
pen.setColor(Color.black);
if(isSelected) {
Ellipse2D.Double selectedCircle = new Ellipse2D.Double(selectLocation.getX()-LOCATION_OFFSET, selectLocation.getY()+LOCATION_OFFSET , 50, 30);
pen.fill(selectedCircle);
}
super.paint(pen);
if(myAttackStrategy.getCanAttack() && !getAttackStrategy().getWeapons().isEmpty()){
for(Projectile p : myAttackStrategy.getWeapons().get(myAttackStrategy.getWeaponIndex()).getProjectiles()) {
p.paint(pen);
}
}
}
}
| true | true | public void paint(Graphics2D pen) {
//pen.rotate(getVelocity().getAngle());
//should probably use the getBottom, getHeight etc...implement them
Point2D selectLocation = Camera.instance().worldToView(getWorldLocation());
Rectangle2D healthBar = new Rectangle2D.Double((int)selectLocation.getX()-LOCATION_OFFSET, (int)(selectLocation.getY()-3*LOCATION_OFFSET), getHealth()/2, 10);
pen.setColor(Color.GREEN);
pen.fill(healthBar);
pen.setColor(Color.black);
if(isSelected) {
Ellipse2D.Double selectedCircle = new Ellipse2D.Double(selectLocation.getX()-LOCATION_OFFSET, selectLocation.getY()+LOCATION_OFFSET , 50, 30);
pen.fill(selectedCircle);
}
super.paint(pen);
if(myAttackStrategy.getCanAttack() && !getAttackStrategy().getWeapons().isEmpty()){
for(Projectile p : myAttackStrategy.getWeapons().get(myAttackStrategy.getWeaponIndex()).getProjectiles()) {
p.paint(pen);
}
}
}
| public void paint(Graphics2D pen) {
//pen.rotate(getVelocity().getAngle());
//should probably use the getBottom, getHeight etc...implement them
Point2D selectLocation = Camera.instance().worldToView(getWorldLocation());
Rectangle2D healthBar = new Rectangle2D.Double((int)selectLocation.getX()-LOCATION_OFFSET, (int)(selectLocation.getY()-3*LOCATION_OFFSET), 50 * getHealth()/getMaxHealth(), 5);
pen.setColor(Color.GREEN);
pen.fill(healthBar);
pen.setColor(Color.black);
if(isSelected) {
Ellipse2D.Double selectedCircle = new Ellipse2D.Double(selectLocation.getX()-LOCATION_OFFSET, selectLocation.getY()+LOCATION_OFFSET , 50, 30);
pen.fill(selectedCircle);
}
super.paint(pen);
if(myAttackStrategy.getCanAttack() && !getAttackStrategy().getWeapons().isEmpty()){
for(Projectile p : myAttackStrategy.getWeapons().get(myAttackStrategy.getWeaponIndex()).getProjectiles()) {
p.paint(pen);
}
}
}
|
diff --git a/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/basic/calendar/layout/MonthCellLayout.java b/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/basic/calendar/layout/MonthCellLayout.java
index 209e3e832b..f1f92a4848 100644
--- a/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/basic/calendar/layout/MonthCellLayout.java
+++ b/org.eclipse.scout.rt.ui.swt/src/org/eclipse/scout/rt/ui/swt/basic/calendar/layout/MonthCellLayout.java
@@ -1,132 +1,132 @@
/*******************************************************************************
* Copyright (c) 2010 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipse.scout.rt.ui.swt.basic.calendar.layout;
import org.eclipse.scout.commons.logger.IScoutLogger;
import org.eclipse.scout.commons.logger.ScoutLogManager;
import org.eclipse.scout.rt.ui.swt.basic.calendar.widgets.SwtCalendar;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
/**
* Layouting calendar month cells.
*
* @author Michael Rudolf, Andreas Hoegger
*/
public class MonthCellLayout extends Layout {
protected static final IScoutLogger LOG = ScoutLogManager.getLogger(SwtCalendar.class);
private int numColumns = 1;
private int numLines = 1;
public int getNumColumns() {
return numColumns;
}
public void setNumColumns(int numColumns) {
this.numColumns = numColumns;
}
public int getNumLines() {
return numLines;
}
public void setNumLines(int numLines) {
this.numLines = numLines;
}
@Override
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
// return a dummy size
return new Point(0, 0);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
// get children (items)
Control[] children = composite.getChildren();
// clipRect of parent composite
Rectangle clipRect = composite.getClientArea();
//logger.debug("size: " + clipRect.width + " w, " + clipRect.height + " h.");
float cellWidth = ((float) clipRect.width) / numColumns;
float cellHeight = ((float) clipRect.height) / numLines;
// init pos array
int[][] ary = new int[numColumns][numLines];
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
ary[h][v] = -1;
}
}
// 1st pass
int colIndex = 0;
int lineIndex = 0;
for (int i = 0; i < children.length;) {
// cell still free?
if (ary[colIndex][lineIndex] == -1) {
Control child = children[i];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int hSpan = Math.max(1, Math.min(dat.getHorizontalSpan(), numColumns - colIndex));
- int vSpan = Math.max(1, Math.min(dat.getHorizontalSpan(), numLines - lineIndex));
+ int vSpan = Math.max(1, Math.min(dat.getVerticalSpan(), numLines - lineIndex));
for (int v = 0; v < vSpan; v++) {
for (int h = 0; h < hSpan; h++) {
// assign cell i
ary[colIndex + h][lineIndex + v] = i;
}
}
// next elem
i++;
}
colIndex = (colIndex + 1) % numColumns;
if (colIndex % numColumns == 0) {
lineIndex++;
}
}
int lastId = -1;
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
int index = ary[h][v];
// new cell?
if (index > lastId) {
Control child = children[index];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int x = Math.round(h * cellWidth);
int y = Math.round(v * cellHeight);
int width = Math.round(dat.getHorizontalSpan() * cellWidth);
int height = Math.round(dat.getVerticalSpan() * cellHeight);
// inset not (yet) done
Rectangle bounds = new Rectangle(x, y, width, height);
child.setBounds(bounds);
lastId = index;
}
}
}
}
}
| true | true | protected void layout(Composite composite, boolean flushCache) {
// get children (items)
Control[] children = composite.getChildren();
// clipRect of parent composite
Rectangle clipRect = composite.getClientArea();
//logger.debug("size: " + clipRect.width + " w, " + clipRect.height + " h.");
float cellWidth = ((float) clipRect.width) / numColumns;
float cellHeight = ((float) clipRect.height) / numLines;
// init pos array
int[][] ary = new int[numColumns][numLines];
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
ary[h][v] = -1;
}
}
// 1st pass
int colIndex = 0;
int lineIndex = 0;
for (int i = 0; i < children.length;) {
// cell still free?
if (ary[colIndex][lineIndex] == -1) {
Control child = children[i];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int hSpan = Math.max(1, Math.min(dat.getHorizontalSpan(), numColumns - colIndex));
int vSpan = Math.max(1, Math.min(dat.getHorizontalSpan(), numLines - lineIndex));
for (int v = 0; v < vSpan; v++) {
for (int h = 0; h < hSpan; h++) {
// assign cell i
ary[colIndex + h][lineIndex + v] = i;
}
}
// next elem
i++;
}
colIndex = (colIndex + 1) % numColumns;
if (colIndex % numColumns == 0) {
lineIndex++;
}
}
int lastId = -1;
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
int index = ary[h][v];
// new cell?
if (index > lastId) {
Control child = children[index];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int x = Math.round(h * cellWidth);
int y = Math.round(v * cellHeight);
int width = Math.round(dat.getHorizontalSpan() * cellWidth);
int height = Math.round(dat.getVerticalSpan() * cellHeight);
// inset not (yet) done
Rectangle bounds = new Rectangle(x, y, width, height);
child.setBounds(bounds);
lastId = index;
}
}
}
}
| protected void layout(Composite composite, boolean flushCache) {
// get children (items)
Control[] children = composite.getChildren();
// clipRect of parent composite
Rectangle clipRect = composite.getClientArea();
//logger.debug("size: " + clipRect.width + " w, " + clipRect.height + " h.");
float cellWidth = ((float) clipRect.width) / numColumns;
float cellHeight = ((float) clipRect.height) / numLines;
// init pos array
int[][] ary = new int[numColumns][numLines];
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
ary[h][v] = -1;
}
}
// 1st pass
int colIndex = 0;
int lineIndex = 0;
for (int i = 0; i < children.length;) {
// cell still free?
if (ary[colIndex][lineIndex] == -1) {
Control child = children[i];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int hSpan = Math.max(1, Math.min(dat.getHorizontalSpan(), numColumns - colIndex));
int vSpan = Math.max(1, Math.min(dat.getVerticalSpan(), numLines - lineIndex));
for (int v = 0; v < vSpan; v++) {
for (int h = 0; h < hSpan; h++) {
// assign cell i
ary[colIndex + h][lineIndex + v] = i;
}
}
// next elem
i++;
}
colIndex = (colIndex + 1) % numColumns;
if (colIndex % numColumns == 0) {
lineIndex++;
}
}
int lastId = -1;
for (int v = 0; v < numLines; v++) {
for (int h = 0; h < numColumns; h++) {
int index = ary[h][v];
// new cell?
if (index > lastId) {
Control child = children[index];
MonthCellData dat = (MonthCellData) child.getLayoutData();
int x = Math.round(h * cellWidth);
int y = Math.round(v * cellHeight);
int width = Math.round(dat.getHorizontalSpan() * cellWidth);
int height = Math.round(dat.getVerticalSpan() * cellHeight);
// inset not (yet) done
Rectangle bounds = new Rectangle(x, y, width, height);
child.setBounds(bounds);
lastId = index;
}
}
}
}
|
diff --git a/src/com/android/exchange/provider/ExchangeDirectoryProvider.java b/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
index 11b7230..b267da9 100644
--- a/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
+++ b/src/com/android/exchange/provider/ExchangeDirectoryProvider.java
@@ -1,421 +1,421 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.provider;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.VendorPolicyLoader;
import com.android.email.mail.PackedString;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import com.android.exchange.EasSyncService;
import com.android.exchange.provider.GalResult.GalData;
import android.accounts.AccountManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Binder;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.List;
/**
* ExchangeDirectoryProvider provides real-time data from the Exchange server; at the moment, it is
* used solely to provide GAL (Global Address Lookup) service to email address adapters
*/
public class ExchangeDirectoryProvider extends ContentProvider {
public static final String EXCHANGE_GAL_AUTHORITY = "com.android.exchange.directory.provider";
private static final int DEFAULT_CONTACT_ID = 1;
private static final int DEFAULT_LOOKUP_LIMIT = 20;
private static final int GAL_BASE = 0;
private static final int GAL_DIRECTORIES = GAL_BASE;
private static final int GAL_FILTER = GAL_BASE + 1;
private static final int GAL_CONTACT = GAL_BASE + 2;
private static final int GAL_CONTACT_WITH_ID = GAL_BASE + 3;
private static final int GAL_EMAIL_FILTER = GAL_BASE + 4;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/*package*/ final HashMap<String, Long> mAccountIdMap = new HashMap<String, Long>();
static {
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "directories", GAL_DIRECTORIES);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/filter/*", GAL_FILTER);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/lookup/*/entities", GAL_CONTACT);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "contacts/lookup/*/#/entities",
GAL_CONTACT_WITH_ID);
sURIMatcher.addURI(EXCHANGE_GAL_AUTHORITY, "data/emails/filter/*", GAL_EMAIL_FILTER);
}
@Override
public boolean onCreate() {
return true;
}
static class GalProjection {
final int size;
final HashMap<String, Integer> columnMap = new HashMap<String, Integer>();
GalProjection(String[] projection) {
size = projection.length;
for (int i = 0; i < projection.length; i++) {
columnMap.put(projection[i], i);
}
}
}
static class GalContactRow {
private final GalProjection mProjection;
private Object[] row;
static long dataId = 1;
GalContactRow(GalProjection projection, long contactId, String lookupKey,
String accountName, String displayName) {
this.mProjection = projection;
row = new Object[projection.size];
put(Contacts.Entity.CONTACT_ID, contactId);
// We only have one raw contact per aggregate, so they can have the same ID
put(Contacts.Entity.RAW_CONTACT_ID, contactId);
put(Contacts.Entity.DATA_ID, dataId++);
put(Contacts.DISPLAY_NAME, displayName);
// TODO alternative display name
put(Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
put(RawContacts.ACCOUNT_TYPE, com.android.email.Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
put(RawContacts.ACCOUNT_NAME, accountName);
put(RawContacts.RAW_CONTACT_IS_READ_ONLY, 1);
put(Data.IS_READ_ONLY, 1);
}
Object[] getRow () {
return row;
}
void put(String columnName, Object value) {
Integer integer = mProjection.columnMap.get(columnName);
if (integer != null) {
row[integer] = value;
} else {
System.out.println("Unsupported column: " + columnName);
}
}
static void addEmailAddress(MatrixCursor cursor, GalProjection galProjection,
long contactId, String lookupKey, String accountName, String displayName,
String address) {
if (!TextUtils.isEmpty(address)) {
GalContactRow r = new GalContactRow(
galProjection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
r.put(Email.TYPE, Email.TYPE_WORK);
r.put(Email.ADDRESS, address);
cursor.addRow(r.getRow());
}
}
static void addPhoneRow(MatrixCursor cursor, GalProjection projection, long contactId,
String lookupKey, String accountName, String displayName, int type, String number) {
if (!TextUtils.isEmpty(number)) {
GalContactRow r = new GalContactRow(
projection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
r.put(Phone.TYPE, type);
r.put(Phone.NUMBER, number);
cursor.addRow(r.getRow());
}
}
public static void addNameRow(MatrixCursor cursor, GalProjection galProjection,
long contactId, String lookupKey, String accountName, String displayName,
String firstName, String lastName) {
GalContactRow r = new GalContactRow(
galProjection, contactId, lookupKey, accountName, displayName);
r.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
r.put(StructuredName.GIVEN_NAME, firstName);
r.put(StructuredName.FAMILY_NAME, lastName);
r.put(StructuredName.DISPLAY_NAME, displayName);
cursor.addRow(r.getRow());
}
}
/**
* Find the record id of an Account, given its name (email address)
* @param accountName the name of the account
* @return the record id of the Account, or -1 if not found
*/
/*package*/ long getAccountIdByName(Context context, String accountName) {
Long accountId = mAccountIdMap.get(accountName);
if (accountId == null) {
accountId = Utility.getFirstRowLong(context, Account.CONTENT_URI,
EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
new String[] {accountName}, null, EmailContent.ID_PROJECTION_COLUMN , -1L);
if (accountId != -1) {
mAccountIdMap.put(accountName, accountId);
}
}
return accountId;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(com.android.email.Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
if (VendorPolicyLoader.getInstance(getContext())
.useAlternateExchangeStrings()) {
row[i] = R.string.exchange_name_alternate;
} else {
row[i] = R.string.exchange_name;
}
} else if (column.equals(Directory.DISPLAY_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
- row[i] = Directory.SHORTCUT_SUPPORT_FULL;
+ row[i] = Directory.SHORTCUT_SUPPORT_NONE;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
GalContactRow.addNameRow(cursor, galProjection, contactId, accountName, displayName,
ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME), displayName);
return cursor;
}
}
return null;
}
/*package*/ Cursor buildGalResultCursor(String[] projection, GalResult galResult) {
int displayNameIndex = -1;
int alternateDisplayNameIndex = -1;;
int emailIndex = -1;
int idIndex = -1;
int lookupIndex = -1;
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (Contacts.DISPLAY_NAME.equals(column) ||
Contacts.DISPLAY_NAME_PRIMARY.equals(column)) {
displayNameIndex = i;
} else if (Contacts.DISPLAY_NAME_ALTERNATIVE.equals(column)) {
alternateDisplayNameIndex = i;
} else if (CommonDataKinds.Email.ADDRESS.equals(column)) {
emailIndex = i;
} else if (Contacts._ID.equals(column)) {
idIndex = i;
} else if (Contacts.LOOKUP_KEY.equals(column)) {
lookupIndex = i;
}
}
Object[] row = new Object[projection.length];
/*
* ContactsProvider will ensure that every request has a non-null projection.
*/
MatrixCursor cursor = new MatrixCursor(projection);
int count = galResult.galData.size();
for (int i = 0; i < count; i++) {
GalData galDataRow = galResult.galData.get(i);
String firstName = galDataRow.get(GalData.FIRST_NAME);
String lastName = galDataRow.get(GalData.LAST_NAME);
String displayName = galDataRow.get(GalData.DISPLAY_NAME);
// If we don't have a display name, try to create one using first and last name
if (displayName == null) {
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
}
galDataRow.put(GalData.DISPLAY_NAME, displayName);
if (displayNameIndex != -1) {
row[displayNameIndex] = displayName;
}
if (alternateDisplayNameIndex != -1) {
// Try to create an alternate display name, using first and last name
// TODO: Check with Contacts team to make sure we're using this properly
if (firstName != null && lastName != null) {
row[alternateDisplayNameIndex] = lastName + " " + firstName;
} else {
row[alternateDisplayNameIndex] = displayName;
}
}
if (emailIndex != -1) {
row[emailIndex] = galDataRow.get(GalData.EMAIL_ADDRESS);
}
if (idIndex != -1) {
row[idIndex] = i + 1; // Let's be 1 based
}
if (lookupIndex != -1) {
// We use the packed string as our lookup key; it contains ALL of the gal data
// We do this because we are not able to provide a stable id to ContactsProvider
row[lookupIndex] = Uri.encode(galDataRow.toPackedString());
}
cursor.addRow(row);
}
return cursor;
}
@Override
public String getType(Uri uri) {
int match = sURIMatcher.match(uri);
switch (match) {
case GAL_FILTER:
return Contacts.CONTENT_ITEM_TYPE;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
}
| true | true | public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(com.android.email.Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
if (VendorPolicyLoader.getInstance(getContext())
.useAlternateExchangeStrings()) {
row[i] = R.string.exchange_name_alternate;
} else {
row[i] = R.string.exchange_name;
}
} else if (column.equals(Directory.DISPLAY_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
row[i] = Directory.SHORTCUT_SUPPORT_FULL;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
GalContactRow.addNameRow(cursor, galProjection, contactId, accountName, displayName,
ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME), displayName);
return cursor;
}
}
return null;
}
| public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
int match = sURIMatcher.match(uri);
MatrixCursor cursor;
Object[] row;
PackedString ps;
String lookupKey;
switch (match) {
case GAL_DIRECTORIES: {
// Assuming that GAL can be used with all exchange accounts
android.accounts.Account[] accounts = AccountManager.get(getContext())
.getAccountsByType(com.android.email.Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cursor = new MatrixCursor(projection);
if (accounts != null) {
for (android.accounts.Account account : accounts) {
row = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
String column = projection[i];
if (column.equals(Directory.ACCOUNT_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.ACCOUNT_TYPE)) {
row[i] = account.type;
} else if (column.equals(Directory.TYPE_RESOURCE_ID)) {
if (VendorPolicyLoader.getInstance(getContext())
.useAlternateExchangeStrings()) {
row[i] = R.string.exchange_name_alternate;
} else {
row[i] = R.string.exchange_name;
}
} else if (column.equals(Directory.DISPLAY_NAME)) {
row[i] = account.name;
} else if (column.equals(Directory.EXPORT_SUPPORT)) {
row[i] = Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY;
} else if (column.equals(Directory.SHORTCUT_SUPPORT)) {
row[i] = Directory.SHORTCUT_SUPPORT_NONE;
}
}
cursor.addRow(row);
}
}
return cursor;
}
case GAL_FILTER:
case GAL_EMAIL_FILTER: {
String filter = uri.getLastPathSegment();
// We should have at least two characters before doing a GAL search
if (filter == null || filter.length() < 2) {
return null;
}
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
// Enforce a limit on the number of lookup responses
String limitString = uri.getQueryParameter(ContactsContract.LIMIT_PARAM_KEY);
int limit = DEFAULT_LOOKUP_LIMIT;
if (limitString != null) {
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
limit = 0;
}
if (limit <= 0) {
throw new IllegalArgumentException("Limit not valid: " + limitString);
}
}
long callingId = Binder.clearCallingIdentity();
try {
// Find the account id to pass along to EasSyncService
long accountId = getAccountIdByName(getContext(), accountName);
if (accountId == -1) {
// The account was deleted?
return null;
}
// Get results from the Exchange account
GalResult galResult = EasSyncService.searchGal(getContext(), accountId,
filter, limit);
if (galResult != null) {
return buildGalResultCursor(projection, galResult);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
break;
}
case GAL_CONTACT:
case GAL_CONTACT_WITH_ID: {
String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
if (accountName == null) {
return null;
}
GalProjection galProjection = new GalProjection(projection);
cursor = new MatrixCursor(projection);
// Handle the decomposition of the key into rows suitable for CP2
List<String> pathSegments = uri.getPathSegments();
lookupKey = pathSegments.get(2);
long contactId = (match == GAL_CONTACT_WITH_ID)
? Long.parseLong(pathSegments.get(3))
: DEFAULT_CONTACT_ID;
ps = new PackedString(lookupKey);
String displayName = ps.get(GalData.DISPLAY_NAME);
GalContactRow.addEmailAddress(cursor, galProjection, contactId, lookupKey,
accountName, displayName, ps.get(GalData.EMAIL_ADDRESS));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_HOME, ps.get(GalData.HOME_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_WORK, ps.get(GalData.WORK_PHONE));
GalContactRow.addPhoneRow(cursor, galProjection, contactId, accountName,
displayName, displayName, Phone.TYPE_MOBILE, ps.get(GalData.MOBILE_PHONE));
GalContactRow.addNameRow(cursor, galProjection, contactId, accountName, displayName,
ps.get(GalData.FIRST_NAME), ps.get(GalData.LAST_NAME), displayName);
return cursor;
}
}
return null;
}
|
diff --git a/pmd/src/net/sourceforge/pmd/rules/UnusedModifier.java b/pmd/src/net/sourceforge/pmd/rules/UnusedModifier.java
index 58d9c718d..d657f5b80 100644
--- a/pmd/src/net/sourceforge/pmd/rules/UnusedModifier.java
+++ b/pmd/src/net/sourceforge/pmd/rules/UnusedModifier.java
@@ -1,50 +1,50 @@
package net.sourceforge.pmd.rules;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.ast.Node;
import net.sourceforge.pmd.ast.SimpleNode;
public class UnusedModifier extends AbstractRule {
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (!node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
- if (parent.isInterface()) {
+ if (parent != null && parent.isInterface()) {
addViolation(data, node, getMessage());
}
} else if (node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
if (parent.isInterface() || (!parent.isInterface() && node.isStatic())) {
addViolation(data, node, getMessage());
}
}
return super.visit(node, data);
}
public Object visit(ASTMethodDeclaration node, Object data) {
if (node.isSyntacticallyPublic() || node.isSyntacticallyAbstract()) {
check(node, data);
}
return super.visit(node, data);
}
public Object visit(ASTFieldDeclaration node, Object data) {
if (node.isSyntacticallyPublic() || node.isSyntacticallyStatic() || node.isSyntacticallyFinal()) {
check(node, data);
}
return super.visit(node, data);
}
private void check(SimpleNode fieldOrMethod, Object data) {
// third ancestor could be an AllocationExpression
// if this is a method in an anonymous inner class
Node parent = fieldOrMethod.jjtGetParent().jjtGetParent().jjtGetParent();
if (parent instanceof ASTClassOrInterfaceDeclaration && ((ASTClassOrInterfaceDeclaration) parent).isInterface()) {
addViolation(data, fieldOrMethod);
}
}
}
| true | true | public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (!node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
if (parent.isInterface()) {
addViolation(data, node, getMessage());
}
} else if (node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
if (parent.isInterface() || (!parent.isInterface() && node.isStatic())) {
addViolation(data, node, getMessage());
}
}
return super.visit(node, data);
}
| public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (!node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
if (parent != null && parent.isInterface()) {
addViolation(data, node, getMessage());
}
} else if (node.isInterface() && node.isNested() && (node.isPublic() || node.isStatic())) {
ASTClassOrInterfaceDeclaration parent = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
if (parent.isInterface() || (!parent.isInterface() && node.isStatic())) {
addViolation(data, node, getMessage());
}
}
return super.visit(node, data);
}
|
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
index 19974f4..01f0e2f 100644
--- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
+++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java
@@ -1,429 +1,429 @@
package com.runetooncraft.plugins.EasyMobArmory;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import net.minecraft.server.v1_6_R2.Item;
import net.minecraft.server.v1_6_R2.NBTTagCompound;
import net.minecraft.server.v1_6_R2.TileEntityChest;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_6_R2.inventory.CraftInventory;
import org.bukkit.craftbukkit.v1_6_R2.inventory.CraftItemStack;
import org.bukkit.entity.Chicken;
import org.bukkit.entity.Cow;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Pig;
import org.bukkit.entity.PigZombie;
import org.bukkit.entity.Player;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Spider;
import org.bukkit.entity.Zombie;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import com.bergerkiller.bukkit.common.entity.CommonEntity;
import com.runetooncraft.plugins.EasyMobArmory.SpawnerHandler.SpawnerCache;
import com.runetooncraft.plugins.EasyMobArmory.SpawnerHandler.SpawnerHandler;
import com.runetooncraft.plugins.EasyMobArmory.core.Config;
import com.runetooncraft.plugins.EasyMobArmory.core.InventorySerializer;
import com.runetooncraft.plugins.EasyMobArmory.core.Messenger;
import com.runetooncraft.plugins.EasyMobArmory.egghandler.EggHandler;
public class EMAListener implements Listener {
Config config;
public static HashMap<Player, Entity> PlayerMobDataMap = new HashMap<Player, Entity>();
public static HashMap<Player, Boolean> Armoryenabled = new HashMap<Player, Boolean>();
public static HashMap<Player, SpawnerCache> SpawnerSelected = new HashMap<Player, SpawnerCache>();
public EMAListener(Config config) {
this.config = config;
}
@EventHandler
public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) {
Entity e = event.getRightClicked();
Player p = event.getPlayer();
if(Armoryenabled.get(p) != null){ if(Armoryenabled.get(p)) {
if(e.getType().equals(EntityType.ZOMBIE)) {
ItemStack i = p.getItemInHand();
Zombie z = (Zombie) e;
if(EMA.Helmets.contains(i)) {
z.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
z.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
z.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
z.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
Inventory inv = Bukkit.createInventory(p, 9, "zombieinv");
ItemStack[] zombieinv = z.getEquipment().getArmorContents();
inv.setContents(zombieinv);
inv.setItem(4, z.getEquipment().getItemInHand());
if(z.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, z);
}else{
z.getEquipment().setItemInHand(i);
}
}else if(e.getType().equals(EntityType.SKELETON)) {
ItemStack i = p.getItemInHand();
Skeleton s = (Skeleton) e;
if(EMA.Helmets.contains(i)) {
s.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
s.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
s.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
s.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
Inventory inv = Bukkit.createInventory(p, 9, "skeletoninv");
ItemStack[] skeletoninv = s.getEquipment().getArmorContents();
inv.setContents(skeletoninv);
inv.setItem(4, s.getEquipment().getItemInHand());
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, s);
}else{
s.getEquipment().setItemInHand(i);
}
}else if(e.getType().equals(EntityType.PIG_ZOMBIE)) {
ItemStack i = p.getItemInHand();
PigZombie pz = (PigZombie) e;
if(EMA.Helmets.contains(i)) {
pz.getEquipment().setHelmet(i);
}else if(EMA.Chestplates.contains(i)) {
pz.getEquipment().setChestplate(i);
}else if(EMA.Leggings.contains(i)) {
pz.getEquipment().setLeggings(i);
}else if(EMA.Boots.contains(i)) {
pz.getEquipment().setBoots(i);
}else if(i.getType().equals(Material.BONE)){
Inventory inv = Bukkit.createInventory(p, 9, "pigzombieinv");
ItemStack[] pigzombieinv = pz.getEquipment().getArmorContents();
inv.setContents(pigzombieinv);
inv.setItem(4, pz.getEquipment().getItemInHand());
if(pz.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, pz);
}else{
pz.getEquipment().setItemInHand(i);
}
}else if(e.getType().equals(EntityType.SHEEP)) {
ItemStack i = p.getItemInHand();
Sheep sh = (Sheep) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "sheepinv");
if(!sh.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE));
if(sh.isSheared()) inv.setItem(6, new ItemStack(Material.SHEARS));
if(sh.getAgeLock()) inv.setItem(7, new ItemStack(Material.GLOWSTONE_DUST));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, sh);
}
}else if(e.getType().equals(EntityType.PIG)) {
ItemStack i = p.getItemInHand();
Pig pig = (Pig) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "piginv");
if(!pig.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE));
if(pig.hasSaddle()) inv.setItem(6, new ItemStack(Material.SADDLE));
if(pig.getAgeLock()) inv.setItem(7, new ItemStack(Material.GLOWSTONE_DUST));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, pig);
}
}else if(e.getType().equals(EntityType.CHICKEN)) {
ItemStack i = p.getItemInHand();
Chicken c = (Chicken) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "chickeninv");
if(!c.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE));
if(c.getAgeLock()) inv.setItem(7, new ItemStack(Material.GLOWSTONE_DUST));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, c);
}
}else if(e.getType().equals(EntityType.COW)) {
ItemStack i = p.getItemInHand();
Cow cow = (Cow) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "cowinv");
if(!cow.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE));
if(cow.getAgeLock()) inv.setItem(7, new ItemStack(Material.GLOWSTONE_DUST));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, cow);
}
}else if(e.getType().equals(EntityType.CREEPER)) {
ItemStack i = p.getItemInHand();
Creeper c = (Creeper) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "creeperinv");
if(c.isPowered()) inv.setItem(0, new ItemStack(Material.REDSTONE));
inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, c);
}
}else if(e.getType().equals(EntityType.HORSE)) {
ItemStack i = p.getItemInHand();
Horse h = (Horse) e;
if(i.getType().equals(Material.BONE)) {
Inventory inv = Bukkit.createInventory(p, 9, "horseinv");
if(!h.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE));
if(h.isTamed()) inv.setItem(6, new ItemStack(Material.HAY_BLOCK));
if(h.isTamed()) {
Player owner = (Player) h.getOwner();
inv.setItem(7, setOwner(new ItemStack(Material.SKULL_ITEM, 1, (short)3), p.getName()));
}
if(h.isCarryingChest()) inv.setItem(7, new ItemStack(Material.CHEST));
// inv.setItem(8, EggHandler.GetEggitem(e,ChatColor.GOLD + "Get Mob Egg",ChatColor.AQUA + e.getType().getName()));
p.openInventory(inv);
PlayerMobDataMap.put(p, h);
}
}
}}
}
@EventHandler
public void OnInventoryCloseEvent(InventoryCloseEvent event) {
if(Armoryenabled.get(event.getPlayer()) != null){ if(Armoryenabled.get(event.getPlayer())) {
if(event.getInventory().getName().equals("zombieinv")) {
Inventory i = event.getInventory();
Zombie z = (Zombie) PlayerMobDataMap.get(event.getPlayer());
z.getEquipment().setHelmet(i.getItem(3));
z.getEquipment().setChestplate(i.getItem(2));
z.getEquipment().setLeggings(i.getItem(1));
z.getEquipment().setBoots(i.getItem(0));
z.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
z.setBaby(true);
}else{
z.setBaby(false);
}
}
else if(event.getInventory().getName().equals("skeletoninv")) {
Inventory i = event.getInventory();
Skeleton s = (Skeleton) PlayerMobDataMap.get(event.getPlayer());
s.getEquipment().setHelmet(i.getItem(3));
s.getEquipment().setChestplate(i.getItem(2));
s.getEquipment().setLeggings(i.getItem(1));
s.getEquipment().setBoots(i.getItem(0));
s.getEquipment().setItemInHand(i.getItem(4));
}
else if(event.getInventory().getName().equals("pigzombieinv")) {
Inventory i = event.getInventory();
PigZombie pz = (PigZombie) PlayerMobDataMap.get(event.getPlayer());
pz.getEquipment().setHelmet(i.getItem(3));
pz.getEquipment().setChestplate(i.getItem(2));
pz.getEquipment().setLeggings(i.getItem(1));
pz.getEquipment().setBoots(i.getItem(0));
pz.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
pz.setBaby(true);
}else{
pz.setBaby(false);
}
}
else if(event.getInventory().getName().equals("sheepinv")) {
Inventory i = event.getInventory();
Sheep sh = (Sheep) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
sh.setBaby();
}else{
sh.setAdult();
}
if(i.contains(Material.SHEARS)) {
sh.setSheared(true);
}else{
sh.setSheared(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
sh.setAgeLock(true);
}else{
sh.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("piginv")) {
Inventory i = event.getInventory();
Pig pig = (Pig) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
pig.setBaby();
}else{
pig.setAdult();
}
if(i.contains(Material.SADDLE)) {
pig.setSaddle(true);
}else{
pig.setSaddle(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
pig.setAgeLock(true);
}else{
pig.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("cowinv")) {
Inventory i = event.getInventory();
Cow cow = (Cow) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
cow.setBaby();
}else{
cow.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
cow.setAgeLock(true);
}else{
cow.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("chickeninv")) {
Inventory i = event.getInventory();
Chicken c = (Chicken) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setBaby();
}else{
c.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
c.setAgeLock(true);
}else{
c.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("creeperinv")) {
Inventory i = event.getInventory();
Creeper c = (Creeper) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setPowered(true);
}else{
c.setPowered(false);
}
}
else if(event.getInventory().getName().equals("horseinv")) {
Inventory i = event.getInventory();
Horse h = (Horse) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
h.setBaby();
}else{
h.setAdult();
}
if(i.contains(Material.HAY_BLOCK)) {
h.setTamed(true);
if(i.contains(Material.SKULL_ITEM)) {
ItemStack head = i.getItem(i.first(Material.SKULL_ITEM));
Player owner = getOwner(head);
if(owner == null) {
h.setOwner(event.getPlayer());
}else{
h.setOwner(owner);
}
}else{
h.setOwner(event.getPlayer());
}
}else{
h.setTamed(false);
}
}
else if(event.getInventory().getName().equals("Spawnerinv")) {
Inventory i = event.getInventory();
SpawnerCache sc = SpawnerSelected.get(event.getPlayer());
ItemStack[] InvItems = i.getContents();
Inventory NewInv = Bukkit.createInventory(event.getPlayer(), 54, "Spawnerinv");
for(ItemStack is : InvItems) {
- if(is.getTypeId() != 0 && is.getType().equals(Material.MONSTER_EGG) && is.hasItemMeta()) {
+ if(is.hasItemMeta() && is.getType().equals(Material.MONSTER_EGG)) {
if(is.getItemMeta().hasDisplayName() && is.getItemMeta().getDisplayName().contains(":")) {
NewInv.addItem(is);
}
}
}
}
}}
}
public ItemStack setOwner(ItemStack item, String owner) {
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setOwner(owner);
item.setItemMeta(meta);
return item;
}
public Player getOwner(ItemStack item) {
SkullMeta meta = (SkullMeta) item.getItemMeta();
if(meta.getOwner() !=null) {
return (Player) Bukkit.getOfflinePlayer(meta.getOwner());
}else{
return null;
}
}
@EventHandler
public void OnInventoryClick(InventoryClickEvent event) {
String name = event.getInventory().getName();
if(name.equals("zombieinv") || name.equals("skeletoninv") || name.equals("pigzombieinv") || name.equals("sheepinv") || name.equals("piginv") || name.equals("cowinv") || name.equals("horseinv") || name.equals("chickeninv") || name.equals("creeperinv")) {
if(event.getSlot() == 8 && event.getCurrentItem().getType() == Material.MONSTER_EGG && event.getCurrentItem().getItemMeta().hasDisplayName() && event.getInventory().getItem(8).equals(event.getCurrentItem())){
Player p = (Player) event.getWhoClicked();
Entity e = PlayerMobDataMap.get(p);
EggHandler.addegg(e);
ItemStack eggitem = EggHandler.GetEggitem(e, "EMA Egg id: " + e.getEntityId(),ChatColor.AQUA + e.getType().getName());
event.getCurrentItem().setItemMeta(eggitem.getItemMeta());
}
}
}
@EventHandler
public void OnPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
if(Armoryenabled.get(p) != null && Armoryenabled.get(p)) {
if(event.getPlayer().getItemInHand().getType().equals(Material.MONSTER_EGG) && event.hasBlock()) {
ItemStack egg = p.getItemInHand();
ItemMeta eggmeta = egg.getItemMeta();
if(eggmeta.hasDisplayName() && eggmeta.getDisplayName().contains(": ")) {
String[] name = eggmeta.getDisplayName().split(": ");
if(name.length == 2) {
if(EggHandler.GetEggList().contains(name[1])) {
Location loc = event.getClickedBlock().getLocation();
loc.setY(loc.getY() + 1);
Entity entity = EggHandler.Loadentity(name[1],loc);
}else{
}
}
}
}else if(event.getPlayer().getItemInHand().getType().equals(Material.BONE) && event.hasBlock() && event.getClickedBlock().getTypeId() == 52) {
Block b = event.getClickedBlock();
Location BlockLocation = b.getLocation();
if(SpawnerHandler.IsEMASpawner(BlockLocation).equals(false)) {
Messenger.playermessage("EMASpawer created", p);
SpawnerHandler.NewEMASpawner(b, p);
SpawnerHandler.OpenSpawnerInventory(b, p);
}else{
SpawnerHandler.OpenSpawnerInventory(b, p);
}
SpawnerSelected.put(p, SpawnerHandler.getSpawner(b.getLocation()));
}
}
}
}
| true | true | public void OnInventoryCloseEvent(InventoryCloseEvent event) {
if(Armoryenabled.get(event.getPlayer()) != null){ if(Armoryenabled.get(event.getPlayer())) {
if(event.getInventory().getName().equals("zombieinv")) {
Inventory i = event.getInventory();
Zombie z = (Zombie) PlayerMobDataMap.get(event.getPlayer());
z.getEquipment().setHelmet(i.getItem(3));
z.getEquipment().setChestplate(i.getItem(2));
z.getEquipment().setLeggings(i.getItem(1));
z.getEquipment().setBoots(i.getItem(0));
z.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
z.setBaby(true);
}else{
z.setBaby(false);
}
}
else if(event.getInventory().getName().equals("skeletoninv")) {
Inventory i = event.getInventory();
Skeleton s = (Skeleton) PlayerMobDataMap.get(event.getPlayer());
s.getEquipment().setHelmet(i.getItem(3));
s.getEquipment().setChestplate(i.getItem(2));
s.getEquipment().setLeggings(i.getItem(1));
s.getEquipment().setBoots(i.getItem(0));
s.getEquipment().setItemInHand(i.getItem(4));
}
else if(event.getInventory().getName().equals("pigzombieinv")) {
Inventory i = event.getInventory();
PigZombie pz = (PigZombie) PlayerMobDataMap.get(event.getPlayer());
pz.getEquipment().setHelmet(i.getItem(3));
pz.getEquipment().setChestplate(i.getItem(2));
pz.getEquipment().setLeggings(i.getItem(1));
pz.getEquipment().setBoots(i.getItem(0));
pz.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
pz.setBaby(true);
}else{
pz.setBaby(false);
}
}
else if(event.getInventory().getName().equals("sheepinv")) {
Inventory i = event.getInventory();
Sheep sh = (Sheep) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
sh.setBaby();
}else{
sh.setAdult();
}
if(i.contains(Material.SHEARS)) {
sh.setSheared(true);
}else{
sh.setSheared(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
sh.setAgeLock(true);
}else{
sh.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("piginv")) {
Inventory i = event.getInventory();
Pig pig = (Pig) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
pig.setBaby();
}else{
pig.setAdult();
}
if(i.contains(Material.SADDLE)) {
pig.setSaddle(true);
}else{
pig.setSaddle(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
pig.setAgeLock(true);
}else{
pig.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("cowinv")) {
Inventory i = event.getInventory();
Cow cow = (Cow) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
cow.setBaby();
}else{
cow.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
cow.setAgeLock(true);
}else{
cow.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("chickeninv")) {
Inventory i = event.getInventory();
Chicken c = (Chicken) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setBaby();
}else{
c.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
c.setAgeLock(true);
}else{
c.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("creeperinv")) {
Inventory i = event.getInventory();
Creeper c = (Creeper) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setPowered(true);
}else{
c.setPowered(false);
}
}
else if(event.getInventory().getName().equals("horseinv")) {
Inventory i = event.getInventory();
Horse h = (Horse) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
h.setBaby();
}else{
h.setAdult();
}
if(i.contains(Material.HAY_BLOCK)) {
h.setTamed(true);
if(i.contains(Material.SKULL_ITEM)) {
ItemStack head = i.getItem(i.first(Material.SKULL_ITEM));
Player owner = getOwner(head);
if(owner == null) {
h.setOwner(event.getPlayer());
}else{
h.setOwner(owner);
}
}else{
h.setOwner(event.getPlayer());
}
}else{
h.setTamed(false);
}
}
else if(event.getInventory().getName().equals("Spawnerinv")) {
Inventory i = event.getInventory();
SpawnerCache sc = SpawnerSelected.get(event.getPlayer());
ItemStack[] InvItems = i.getContents();
Inventory NewInv = Bukkit.createInventory(event.getPlayer(), 54, "Spawnerinv");
for(ItemStack is : InvItems) {
if(is.getTypeId() != 0 && is.getType().equals(Material.MONSTER_EGG) && is.hasItemMeta()) {
if(is.getItemMeta().hasDisplayName() && is.getItemMeta().getDisplayName().contains(":")) {
NewInv.addItem(is);
}
}
}
}
}}
}
| public void OnInventoryCloseEvent(InventoryCloseEvent event) {
if(Armoryenabled.get(event.getPlayer()) != null){ if(Armoryenabled.get(event.getPlayer())) {
if(event.getInventory().getName().equals("zombieinv")) {
Inventory i = event.getInventory();
Zombie z = (Zombie) PlayerMobDataMap.get(event.getPlayer());
z.getEquipment().setHelmet(i.getItem(3));
z.getEquipment().setChestplate(i.getItem(2));
z.getEquipment().setLeggings(i.getItem(1));
z.getEquipment().setBoots(i.getItem(0));
z.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
z.setBaby(true);
}else{
z.setBaby(false);
}
}
else if(event.getInventory().getName().equals("skeletoninv")) {
Inventory i = event.getInventory();
Skeleton s = (Skeleton) PlayerMobDataMap.get(event.getPlayer());
s.getEquipment().setHelmet(i.getItem(3));
s.getEquipment().setChestplate(i.getItem(2));
s.getEquipment().setLeggings(i.getItem(1));
s.getEquipment().setBoots(i.getItem(0));
s.getEquipment().setItemInHand(i.getItem(4));
}
else if(event.getInventory().getName().equals("pigzombieinv")) {
Inventory i = event.getInventory();
PigZombie pz = (PigZombie) PlayerMobDataMap.get(event.getPlayer());
pz.getEquipment().setHelmet(i.getItem(3));
pz.getEquipment().setChestplate(i.getItem(2));
pz.getEquipment().setLeggings(i.getItem(1));
pz.getEquipment().setBoots(i.getItem(0));
pz.getEquipment().setItemInHand(i.getItem(4));
if(i.contains(Material.REDSTONE)) {
pz.setBaby(true);
}else{
pz.setBaby(false);
}
}
else if(event.getInventory().getName().equals("sheepinv")) {
Inventory i = event.getInventory();
Sheep sh = (Sheep) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
sh.setBaby();
}else{
sh.setAdult();
}
if(i.contains(Material.SHEARS)) {
sh.setSheared(true);
}else{
sh.setSheared(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
sh.setAgeLock(true);
}else{
sh.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("piginv")) {
Inventory i = event.getInventory();
Pig pig = (Pig) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
pig.setBaby();
}else{
pig.setAdult();
}
if(i.contains(Material.SADDLE)) {
pig.setSaddle(true);
}else{
pig.setSaddle(false);
}
if(i.contains(Material.GLOWSTONE_DUST)) {
pig.setAgeLock(true);
}else{
pig.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("cowinv")) {
Inventory i = event.getInventory();
Cow cow = (Cow) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
cow.setBaby();
}else{
cow.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
cow.setAgeLock(true);
}else{
cow.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("chickeninv")) {
Inventory i = event.getInventory();
Chicken c = (Chicken) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setBaby();
}else{
c.setAdult();
}
if(i.contains(Material.GLOWSTONE_DUST)) {
c.setAgeLock(true);
}else{
c.setAgeLock(false);
}
}
else if(event.getInventory().getName().equals("creeperinv")) {
Inventory i = event.getInventory();
Creeper c = (Creeper) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
c.setPowered(true);
}else{
c.setPowered(false);
}
}
else if(event.getInventory().getName().equals("horseinv")) {
Inventory i = event.getInventory();
Horse h = (Horse) PlayerMobDataMap.get(event.getPlayer());
if(i.contains(Material.REDSTONE)) {
h.setBaby();
}else{
h.setAdult();
}
if(i.contains(Material.HAY_BLOCK)) {
h.setTamed(true);
if(i.contains(Material.SKULL_ITEM)) {
ItemStack head = i.getItem(i.first(Material.SKULL_ITEM));
Player owner = getOwner(head);
if(owner == null) {
h.setOwner(event.getPlayer());
}else{
h.setOwner(owner);
}
}else{
h.setOwner(event.getPlayer());
}
}else{
h.setTamed(false);
}
}
else if(event.getInventory().getName().equals("Spawnerinv")) {
Inventory i = event.getInventory();
SpawnerCache sc = SpawnerSelected.get(event.getPlayer());
ItemStack[] InvItems = i.getContents();
Inventory NewInv = Bukkit.createInventory(event.getPlayer(), 54, "Spawnerinv");
for(ItemStack is : InvItems) {
if(is.hasItemMeta() && is.getType().equals(Material.MONSTER_EGG)) {
if(is.getItemMeta().hasDisplayName() && is.getItemMeta().getDisplayName().contains(":")) {
NewInv.addItem(is);
}
}
}
}
}}
}
|
diff --git a/src/com/wolvencraft/prison/mines/MineTask.java b/src/com/wolvencraft/prison/mines/MineTask.java
index 2bc707a..148b626 100644
--- a/src/com/wolvencraft/prison/mines/MineTask.java
+++ b/src/com/wolvencraft/prison/mines/MineTask.java
@@ -1,42 +1,42 @@
package com.wolvencraft.prison.mines;
import java.util.List;
import com.wolvencraft.prison.hooks.TimedTask;
import com.wolvencraft.prison.mines.mine.DisplaySign;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
public class MineTask extends TimedTask {
long period;
public MineTask(long ticks) {
super(ticks);
period = ticks;
}
public void run() {
for(Mine curMine : PrisonMine.getMines()) {
if(curMine.getAutomatic() && Mine.get(curMine.getParent()) == null) {
int nextReset = curMine.getResetsInSafe();
List<Integer> warnTimes = curMine.getWarningTimes();
if(!curMine.getSilent() && curMine.getWarned() && warnTimes.indexOf(new Integer(nextReset)) != -1)
- Message.broadcast(Util.parseVars(PrisonMine.getLanguage().RESET_AUTOMATIC, curMine));
+ Message.broadcast(Util.parseVars(PrisonMine.getLanguage().RESET_WARNING, curMine));
if(nextReset <= 0) {
MineCommand.RESET.run(curMine.getName());
}
curMine.updateTimer(PrisonMine.getSettings().TICKRATE);
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0)
curMine.updateCooldown(PrisonMine.getSettings().TICKRATE);
}
DisplaySign.updateAll();
}
public String getName() { return "MineTask"; }
}
| true | true | public void run() {
for(Mine curMine : PrisonMine.getMines()) {
if(curMine.getAutomatic() && Mine.get(curMine.getParent()) == null) {
int nextReset = curMine.getResetsInSafe();
List<Integer> warnTimes = curMine.getWarningTimes();
if(!curMine.getSilent() && curMine.getWarned() && warnTimes.indexOf(new Integer(nextReset)) != -1)
Message.broadcast(Util.parseVars(PrisonMine.getLanguage().RESET_AUTOMATIC, curMine));
if(nextReset <= 0) {
MineCommand.RESET.run(curMine.getName());
}
curMine.updateTimer(PrisonMine.getSettings().TICKRATE);
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0)
curMine.updateCooldown(PrisonMine.getSettings().TICKRATE);
}
DisplaySign.updateAll();
}
| public void run() {
for(Mine curMine : PrisonMine.getMines()) {
if(curMine.getAutomatic() && Mine.get(curMine.getParent()) == null) {
int nextReset = curMine.getResetsInSafe();
List<Integer> warnTimes = curMine.getWarningTimes();
if(!curMine.getSilent() && curMine.getWarned() && warnTimes.indexOf(new Integer(nextReset)) != -1)
Message.broadcast(Util.parseVars(PrisonMine.getLanguage().RESET_WARNING, curMine));
if(nextReset <= 0) {
MineCommand.RESET.run(curMine.getName());
}
curMine.updateTimer(PrisonMine.getSettings().TICKRATE);
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0)
curMine.updateCooldown(PrisonMine.getSettings().TICKRATE);
}
DisplaySign.updateAll();
}
|
diff --git a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/apimodel/APIMethodParameter.java b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/apimodel/APIMethodParameter.java
index bed9943..aa003d0 100644
--- a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/apimodel/APIMethodParameter.java
+++ b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/apimodel/APIMethodParameter.java
@@ -1,96 +1,97 @@
package cz.cvut.fit.hybljan2.apitestingcg.apimodel;
import com.sun.tools.javac.tree.JCTree;
import java.lang.reflect.Type;
/**
* Class represents one parameter of method or constructor.
*/
public class APIMethodParameter {
/**
* Name of parameter
*/
private String name;
/**
* Full name of class.
*/
private APIType type;
public APIMethodParameter(String name, APIType type) {
this.name = name;
this.type = type;
}
public APIMethodParameter(String name, String type) {
this.name = name;
this.type = new APIType(type);
}
public APIMethodParameter(String name, JCTree.JCVariableDecl jcvd) {
if (name == null) {
this.name = jcvd.name.toString();
} else {
this.name = name;
}
type = new APIType(jcvd.type);
}
public APIMethodParameter(String name, Type type) {
this.name = name;
this.type = new APIType(type);
}
public String getName() {
return name;
}
public APIType getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof APIMethodParameter)) return false;
APIMethodParameter that = (APIMethodParameter) o;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
return true;
}
@Override
public int hashCode() {
return type != null ? type.hashCode() : 0;
}
@Override
public String toString() {
return type + " " + name;
}
public boolean isPrimitive() {
+ if(getType().isArray()) return false;
switch (getType().getName()) {
case "byte":
case "short":
case "int":
case "long":
case "float":
case "double":
case "boolean":
case "char":
return true;
default:
return false;
}
}
public void setType(APIType type) {
this.type = type;
}
}
| true | true | public boolean isPrimitive() {
switch (getType().getName()) {
case "byte":
case "short":
case "int":
case "long":
case "float":
case "double":
case "boolean":
case "char":
return true;
default:
return false;
}
}
| public boolean isPrimitive() {
if(getType().isArray()) return false;
switch (getType().getName()) {
case "byte":
case "short":
case "int":
case "long":
case "float":
case "double":
case "boolean":
case "char":
return true;
default:
return false;
}
}
|
diff --git a/loci/formats/in/DeltavisionReader.java b/loci/formats/in/DeltavisionReader.java
index e7d71afb5..5a1ee4193 100644
--- a/loci/formats/in/DeltavisionReader.java
+++ b/loci/formats/in/DeltavisionReader.java
@@ -1,777 +1,778 @@
//
// DeltavisionReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.awt.image.BufferedImage;
import java.io.IOException;
import loci.formats.*;
/**
* DeltavisionReader is the file format reader for Deltavision files.
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class DeltavisionReader extends FormatReader {
// -- Constants --
private static final short LITTLE_ENDIAN = -16224;
// -- Fields --
/** Current file. */
protected RandomAccessStream in;
/** Number of images in the current file. */
protected int numImages;
/** Flag indicating whether current file is little endian. */
protected boolean little;
/** Byte array containing basic image header data. */
protected byte[] header;
/** Byte array containing extended header data. */
protected byte[] extHeader;
/** Image width. */
private int width;
/** Image height. */
private int height;
/** Bytes per pixel. */
private int bytesPerPixel;
/** Offset where the ExtHdr starts. */
protected int initExtHdrOffset = 1024;
/** Dimension order. */
private String order;
/** Size of one wave in the extended header. */
protected int wSize;
/** Size of one z section in the extended header. */
protected int zSize;
/** Size of one time element in the extended header. */
protected int tSize;
protected int numT;
protected int numW;
protected int numZ;
/**
* the Number of ints in each extended header section. These fields appear
* to be all blank but need to be skipped to get to the floats afterwards
*/
protected int numIntsPerSection;
protected int numFloatsPerSection;
/** Initialize an array of Extended Header Field structures. */
protected DVExtHdrFields[][][] extHdrFields = null;
// -- Constructor --
/** Constructs a new Deltavision reader. */
public DeltavisionReader() {
super("Deltavision", new String[] {"dv", "r3d", "r3d_d3d"});
}
// -- FormatReader API methods --
/** Checks if the given block is a valid header for a Deltavision file. */
public boolean isThisType(byte[] block) {
return (DataTools.bytesToShort(block, 0, 2, little) == LITTLE_ENDIAN);
}
/** Determines the number of images in the given Deltavision file. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return numImages;
}
/** Checks if the images in the file are RGB. */
public boolean isRGB(String id) throws FormatException, IOException {
return false;
}
/** Get the size of the X dimension. */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return width;
}
/** Get the size of the Y dimension. */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return height;
}
/** Get the size of the Z dimension. */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return numZ;
}
/** Get the size of the C dimension. */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return numW;
}
/** Get the size of the T dimension. */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return numT;
}
/* @see loci.formats.IFormatReader#getChannelGlobalMinimum(int) */
public Double getChannelGlobalMinimum(String id, int theC)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
Float v = (Float) getMeta("Wavelength " + theC + " min. intensity");
return new Double(v.floatValue());
}
/* @see loci.formats.IFormatReader#getChannelGlobalMaximum(int) */
public Double getChannelGlobalMaximum(String id, int theC)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
Float v = (Float) getMeta("Wavelength " + theC + " max. intensity");
return new Double(v.floatValue());
}
/** Return true if the data is in little-endian format. */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return little;
}
/** Returns whether or not the channels are interleaved. */
public boolean isInterleaved(String id) throws FormatException, IOException {
return false;
}
/** Obtains the specified image from the given file as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
byte[] buf = new byte[width * height * bytesPerPixel];
return openBytes(id, no, buf);
}
/* @see loci.formats.IFormatReader#openBytes(String, int, byte[]) */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
if (no < 0 || no >= numImages) {
throw new FormatException("Invalid image number: " + no);
}
// read the image plane's pixel data
int offset = header.length + extHeader.length;
offset += width * height * bytesPerPixel * no;
in.seek(offset);
in.read(buf);
return buf;
}
/** Obtains the specified image from the given Deltavision file. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
return ImageTools.makeImage(openBytes(id, no), width, height, 1,
false, bytesPerPixel, little);
}
/** Closes any open files. */
public void close() throws FormatException, IOException {
if (in != null) in.close();
in = null;
currentId = null;
}
/** Initializes the given Deltavision file. */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("DeltavisionReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
// read in the image header data
header = new byte[1024];
in.read(header);
int endian = DataTools.bytesToShort(header, 96, 2, true);
little = endian == LITTLE_ENDIAN;
numImages = DataTools.bytesToInt(header, 8, 4, little);
int extSize = DataTools.bytesToInt(header, 92, 4, little);
extHeader = new byte[extSize];
in.read(extHeader);
width = DataTools.bytesToInt(header, 0, 4, little);
height = DataTools.bytesToInt(header, 4, 4, little);
Integer xSize = new Integer(width);
Integer ySize = new Integer(height);
addMeta("ImageWidth", xSize);
addMeta("ImageHeight", ySize);
addMeta("NumberOfImages", new Integer(DataTools.bytesToInt(header,
8, 4, little)));
int filePixelType = DataTools.bytesToInt(header, 12, 4, little);
String pixel;
switch (filePixelType) {
case 0:
pixel = "8 bit unsigned integer";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
break;
case 1:
pixel = "16 bit signed integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
case 2:
pixel = "32 bit floating point";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 4;
break;
case 3:
pixel = "32 bit complex";
pixelType[0] = FormatReader.UINT32;
bytesPerPixel = 4;
break;
case 4:
pixel = "64 bit complex";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 8;
break;
case 6:
pixel = "16 bit unsigned integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
default:
pixel = "unknown";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
}
addMeta("PixelType", pixel);
addMeta("Sub-image starting point (X)", new Integer(
DataTools.bytesToInt(header, 16, 4, little)));
addMeta("Sub-image starting point (Y)", new Integer(
DataTools.bytesToInt(header, 20, 4, little)));
addMeta("Sub-image starting point (Z)", new Integer(
DataTools.bytesToInt(header, 24, 4, little)));
addMeta("Pixel sampling size (X)", new Integer(
DataTools.bytesToInt(header, 28, 4, little)));
addMeta("Pixel sampling size (Y)", new Integer(
DataTools.bytesToInt(header, 32, 4, little)));
addMeta("Pixel sampling size (Z)", new Integer(
DataTools.bytesToInt(header, 36, 4, little)));
addMeta("X element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 40, 4, little))));
addMeta("Y element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 44, 4, little))));
addMeta("Z element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 48, 4, little))));
addMeta("X axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 52, 4, little))));
addMeta("Y axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 56, 4, little))));
addMeta("Z axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 60, 4, little))));
addMeta("Column axis sequence", new Integer(
DataTools.bytesToInt(header, 64, 4, little)));
addMeta("Row axis sequence", new Integer(
DataTools.bytesToInt(header, 68, 4, little)));
addMeta("Section axis sequence", new Integer(
DataTools.bytesToInt(header, 72, 4, little)));
Float wave1Min = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 76, 4, little)));
addMeta("Wavelength 1 min. intensity", wave1Min);
Float wave1Max = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 80, 4, little)));
addMeta("Wavelength 1 max. intensity", wave1Max);
addMeta("Wavelength 1 mean intensity", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 84, 4, little))));
addMeta("Space group number", new Integer(
DataTools.bytesToInt(header, 88, 4, little)));
addMeta("Number of Sub-resolution sets", new Integer(
DataTools.bytesToInt(header, 132, 2, little)));
addMeta("Z axis reduction quotient", new Integer(
DataTools.bytesToInt(header, 134, 2, little)));
Float wave2Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 136, 4, little)));
addMeta("Wavelength 2 min. intensity", wave2Min);
Float wave2Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 140, 4, little)));
addMeta("Wavelength 2 max. intensity", wave2Max);
Float wave3Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 144, 4, little)));
addMeta("Wavelength 3 min. intensity", wave3Min);
Float wave3Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 148, 4, little)));
addMeta("Wavelength 3 max. intensity", wave3Max);
Float wave4Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 152, 4, little)));
addMeta("Wavelength 4 min. intensity", wave4Min);
Float wave4Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 156, 4, little)));
addMeta("Wavelength 4 max. intensity", wave4Max);
int type = DataTools.bytesToShort(header, 160, 2, little);
String imageType;
switch (type) {
case 0:
imageType = "normal";
break;
case 1:
imageType = "Tilt-series";
break;
case 2:
imageType = "Stereo tilt-series";
break;
case 3:
imageType = "Averaged images";
break;
case 4:
imageType = "Averaged stereo pairs";
break;
default:
imageType = "unknown";
}
addMeta("Image Type", imageType);
addMeta("Lens ID Number", new Integer(DataTools.bytesToShort(
header, 162, 2, little)));
Float wave5Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 172, 4, little)));
addMeta("Wavelength 5 min. intensity", wave5Min);
Float wave5Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 176, 4, little)));
addMeta("Wavelength 5 max. intensity", wave5Max);
numT = DataTools.bytesToShort(header, 180, 2, little);
addMeta("Number of timepoints", new Integer(numT));
int sequence = DataTools.bytesToInt(header, 182, 4, little);
String imageSequence;
String dimOrder;
switch (sequence) {
case 0:
imageSequence = "ZTW"; dimOrder = "XYZTC";
break;
case 1:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
case 2:
imageSequence = "ZWT"; dimOrder = "XYZCT";
break;
case 65536:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
default:
imageSequence = "unknown"; dimOrder = "XYZTC";
}
addMeta("Image sequence", imageSequence);
addMeta("X axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 184, 4, little))));
addMeta("Y axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 188, 4, little))));
addMeta("Z axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 192, 4, little))));
numW = DataTools.bytesToShort(header, 196, 2, little);
addMeta("Number of wavelengths", new Integer(numW));
numZ = numImages / (numW * numT);
addMeta("Number of focal planes", new Integer(numZ));
addMeta("Wavelength 1 (in nm)", new Integer(DataTools.bytesToShort(
header, 198, 2, little)));
addMeta("Wavelength 2 (in nm)", new Integer(DataTools.bytesToShort(
header, 200, 2, little)));
addMeta("Wavelength 3 (in nm)", new Integer(DataTools.bytesToShort(
header, 202, 2, little)));
addMeta("Wavelength 4 (in nm)", new Integer(DataTools.bytesToShort(
header, 204, 2, little)));
addMeta("Wavelength 5 (in nm)", new Integer(DataTools.bytesToShort(
header, 206, 2, little)));
addMeta("X origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 208, 4, little))));
addMeta("Y origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 212, 4, little))));
addMeta("Z origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 216, 4, little))));
order = dimOrder;
// The metadata store we're working with.
MetadataStore store = getMetadataStore(id);
String title;
for (int i=1; i<=10; i++) {
// Make sure that "null" characters are stripped out
title = new String(header, 224 + 80*(i-1), 80).replaceAll("\0", "");
addMeta("Title " + i, title);
}
sizeX[0] = width;
sizeY[0] = height;
sizeZ[0] = numZ;
sizeC[0] = numW;
sizeT[0] = numT;
currentOrder[0] = order;
// ----- The Extended Header data handler begins here ------
numIntsPerSection = DataTools.bytesToInt(header, 128, 2, little);
numFloatsPerSection = DataTools.bytesToInt(header, 130, 2, little);
setOffsetInfo(sequence, numZ, numW, numT);
extHdrFields = new DVExtHdrFields[numZ][numW][numT];
store.setPixels(new Integer(width), new Integer(height), new Integer(numZ),
new Integer(numW), new Integer(numT), new Integer(pixelType[0]),
new Boolean(!little), dimOrder, null);
store.setDimensions(
(Float) getMeta("X element length (in um)"),
(Float) getMeta("Y element length (in um)"),
(Float) getMeta("Z element length (in um)"),
null, null, null);
String description = (String) getMeta("Title 1");
+ if (description == null) description = "";
description = description.length() == 0 ? null : description;
store.setImage(id, null, description, null);
// Run through every timeslice, for each wavelength, for each z section
// and fill in the Extended Header information array for that image
for (int z = 0; z < numZ; z++) {
for (int t = 0; t < numT; t++) {
for (int w = 0; w < numW; w++) {
extHdrFields[z][w][t] = new DVExtHdrFields(getTotalOffset(z, w, t),
numIntsPerSection, extHeader, little);
store.setPlaneInfo(z, w, t,
new Float(extHdrFields[z][w][t].getTimeStampSeconds()),
new Float(extHdrFields[z][w][t].getExpTime()), null);
}
}
}
for (int w=0; w<numW; w++) {
store.setLogicalChannel(w, null,
new Float(extHdrFields[0][w][0].getNdFilter()),
(Integer) getMeta("Wavelength " + (w+1) + " (in nm)"),
new Integer((int) extHdrFields[0][w][0].getExFilter()),
"Monochrome", "Wide-field", null);
}
store.setStageLabel("ome",
new Float(extHdrFields[0][0][0].getStageXCoord()),
new Float(extHdrFields[0][0][0].getStageYCoord()),
new Float(extHdrFields[0][0][0].getStageZCoord()), null);
if (numW > 0) {
store.setChannelGlobalMinMax(0, new Double(wave1Min.floatValue()),
new Double(wave1Max.floatValue()), null);
}
if (numW > 1) {
store.setChannelGlobalMinMax(1, new Double(wave2Min.floatValue()),
new Double(wave2Max.floatValue()), null);
}
if (numW > 2) {
store.setChannelGlobalMinMax(2, new Double(wave3Min.floatValue()),
new Double(wave3Max.floatValue()), null);
}
if (numW > 3) {
store.setChannelGlobalMinMax(3, new Double(wave4Min.floatValue()),
new Double(wave4Max.floatValue()), null);
}
if (numW > 4) {
store.setChannelGlobalMinMax(4, new Double(wave5Min.floatValue()),
new Double(wave5Max.floatValue()), null);
}
store.setDefaultDisplaySettings(null);
}
/**
* This method calculates the size of a w, t, z section depending on which
* sequence is being used (either ZTW, WZT, or ZWT)
* @param imgSequence
* @param numZSections
* @param numWaves
* @param numTimes
*/
private void setOffsetInfo(int imgSequence, int numZSections,
int numWaves, int numTimes)
{
int smallOffset = (numIntsPerSection + numFloatsPerSection) * 4;
switch (imgSequence) {
// ZTW sequence
case 0:
zSize = smallOffset;
tSize = zSize * numZSections;
wSize = tSize * numTimes;
break;
// WZT sequence
case 1:
wSize = smallOffset;
zSize = wSize * numWaves;
tSize = zSize * numZSections;
break;
// ZWT sequence
case 2:
zSize = smallOffset;
wSize = zSize * numZSections;
tSize = wSize * numWaves;
break;
}
}
/**
* Given any specific Z, W, and T of a plane, determine the totalOffset from
* the start of the extended header.
* @param currentZ
* @param currentW
* @param currentT
*/
public int getTotalOffset(int currentZ, int currentW, int currentT) {
return (zSize * currentZ) + (wSize * currentW) + (tSize * currentT);
}
/**
* This method returns the a plane number from when given a Z, W
* and T offsets.
* @param currentZ
* @param currentW
* @param currentT
*/
public int getPlaneNumber(int currentZ, int currentW, int currentT) {
int smallOffset = (numIntsPerSection + numFloatsPerSection) * 4;
return getTotalOffset(currentZ, currentW, currentT) / smallOffset;
}
/**
* This private class structure holds the details for the extended header
* @author Brian W. Loranger
*/
private class DVExtHdrFields {
private int offsetWithInts;
private float oDFilter;
/** Photosensor reading. Typically in mV. */
private float photosensorReading;
/** Time stamp in seconds since the experiment began. */
private float timeStampSeconds;
/** X stage coordinates. */
private float stageXCoord;
/** Y stage coordinates. */
private float stageYCoord;
/** Z stage coordinates. */
private float stageZCoord;
/** Minimum intensity */
private float minInten;
/** Maxiumum intensity. */
private float maxInten;
/** Mean intesity. */
private float meanInten;
/** Exposure time in seconds. */
private float expTime;
/** Neutral density value. */
private float ndFilter;
/** Excitation filter number. */
private float exFilter;
/** Emiision filter number. */
private float emFilter;
/** Excitation filter wavelength. */
private float exWavelen;
/** Emission filter wavelength. */
private float emWavelen;
/** Intensity scaling factor. Usually 1. */
private float intenScaling;
/** Energy conversion factor. Usually 1. */
private float energyConvFactor;
/**
* Helper function which overrides toString, printing out the values in
* the header section.
*/
public String toString() {
String s = new String();
s += "photosensorReading: " + photosensorReading + "\n";
s += "timeStampSeconds: " + timeStampSeconds + "\n";
s += "stageXCoord: " + stageXCoord + "\n";
s += "stageYCoord: " + stageYCoord + "\n";
s += "stageZCoord: " + stageZCoord + "\n";
s += "minInten: " + minInten + "\n";
s += "maxInten: " + maxInten + "\n";
s += "meanInten: " + meanInten + "\n";
s += "expTime: " + expTime + "\n";
s += "ndFilter: " + ndFilter + "\n";
s += "exFilter: " + exFilter + "\n";
s += "emFilter: " + emFilter + "\n";
s += "exWavelen: " + exWavelen + "\n";
s += "emWavelen: " + emWavelen + "\n";
s += "intenScaling: " + intenScaling + "\n";
s += "energyConvFactor: " + energyConvFactor + "\n";
return s;
}
/**
* Given the starting offset of a specific entry in the extended header
* this method will go through each element in the entry and fill each
* element's variable with its extended header value.
* @param startingOffset
* @param numIntsPerSection
* @param extHeader
* @param little
*/
protected DVExtHdrFields(int startingOffset, int numIntsPerSection,
byte[] extHeader, boolean little)
{
// skip over the int values that have nothing in them
offsetWithInts = startingOffset + (numIntsPerSection * 4);
// DV files store the ND (neuatral density) Filter (normally expressed as
// a %T (transmittance)) as an OD (optical density) rating.
// To convert from one to the other the formula is %T = 10^(-OD) X 100.
oDFilter = Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 36, 4, little));
// fill in the extended header information for the floats
photosensorReading =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts, 4, little));
timeStampSeconds =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 4, 4, little));
stageXCoord =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 8, 4, little));
stageYCoord =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 12, 4, little));
stageZCoord =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 16, 4, little));
minInten =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 20, 4, little));
maxInten =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 24, 4, little));
meanInten =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 28, 4, little));
expTime =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 32, 4, little));
ndFilter = (float) Math.pow(10.0, -oDFilter);
exFilter =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 40, 4, little));
emFilter =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 44, 4, little));
exWavelen =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 48, 4, little));
emWavelen =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 52, 4, little));
intenScaling =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 56, 4, little));
energyConvFactor =
Float.intBitsToFloat(
DataTools.bytesToInt(extHeader, offsetWithInts + 60, 4, little));
}
/** Various getters for the Extended header fields. */
public float getPhotosensorReading() { return photosensorReading; }
public float getTimeStampSeconds() { return timeStampSeconds; }
public float getStageXCoord() { return stageXCoord; }
public float getStageYCoord() { return stageYCoord; }
public float getStageZCoord() { return stageZCoord; }
public float getMinInten() { return minInten; }
public float getMaxInten() { return maxInten; }
public float getMeanInten() { return meanInten; }
public float getExpTime() { return expTime; }
public float getNdFilter() { return ndFilter; }
public float getExFilter() { return exFilter; }
public float getEmFilter() { return emFilter; }
public float getExWavelen() { return exWavelen; }
public float getEmWavelen() { return emWavelen; }
public float getIntenScaling() { return intenScaling; }
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new DeltavisionReader().testRead(args);
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("DeltavisionReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
// read in the image header data
header = new byte[1024];
in.read(header);
int endian = DataTools.bytesToShort(header, 96, 2, true);
little = endian == LITTLE_ENDIAN;
numImages = DataTools.bytesToInt(header, 8, 4, little);
int extSize = DataTools.bytesToInt(header, 92, 4, little);
extHeader = new byte[extSize];
in.read(extHeader);
width = DataTools.bytesToInt(header, 0, 4, little);
height = DataTools.bytesToInt(header, 4, 4, little);
Integer xSize = new Integer(width);
Integer ySize = new Integer(height);
addMeta("ImageWidth", xSize);
addMeta("ImageHeight", ySize);
addMeta("NumberOfImages", new Integer(DataTools.bytesToInt(header,
8, 4, little)));
int filePixelType = DataTools.bytesToInt(header, 12, 4, little);
String pixel;
switch (filePixelType) {
case 0:
pixel = "8 bit unsigned integer";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
break;
case 1:
pixel = "16 bit signed integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
case 2:
pixel = "32 bit floating point";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 4;
break;
case 3:
pixel = "32 bit complex";
pixelType[0] = FormatReader.UINT32;
bytesPerPixel = 4;
break;
case 4:
pixel = "64 bit complex";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 8;
break;
case 6:
pixel = "16 bit unsigned integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
default:
pixel = "unknown";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
}
addMeta("PixelType", pixel);
addMeta("Sub-image starting point (X)", new Integer(
DataTools.bytesToInt(header, 16, 4, little)));
addMeta("Sub-image starting point (Y)", new Integer(
DataTools.bytesToInt(header, 20, 4, little)));
addMeta("Sub-image starting point (Z)", new Integer(
DataTools.bytesToInt(header, 24, 4, little)));
addMeta("Pixel sampling size (X)", new Integer(
DataTools.bytesToInt(header, 28, 4, little)));
addMeta("Pixel sampling size (Y)", new Integer(
DataTools.bytesToInt(header, 32, 4, little)));
addMeta("Pixel sampling size (Z)", new Integer(
DataTools.bytesToInt(header, 36, 4, little)));
addMeta("X element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 40, 4, little))));
addMeta("Y element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 44, 4, little))));
addMeta("Z element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 48, 4, little))));
addMeta("X axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 52, 4, little))));
addMeta("Y axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 56, 4, little))));
addMeta("Z axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 60, 4, little))));
addMeta("Column axis sequence", new Integer(
DataTools.bytesToInt(header, 64, 4, little)));
addMeta("Row axis sequence", new Integer(
DataTools.bytesToInt(header, 68, 4, little)));
addMeta("Section axis sequence", new Integer(
DataTools.bytesToInt(header, 72, 4, little)));
Float wave1Min = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 76, 4, little)));
addMeta("Wavelength 1 min. intensity", wave1Min);
Float wave1Max = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 80, 4, little)));
addMeta("Wavelength 1 max. intensity", wave1Max);
addMeta("Wavelength 1 mean intensity", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 84, 4, little))));
addMeta("Space group number", new Integer(
DataTools.bytesToInt(header, 88, 4, little)));
addMeta("Number of Sub-resolution sets", new Integer(
DataTools.bytesToInt(header, 132, 2, little)));
addMeta("Z axis reduction quotient", new Integer(
DataTools.bytesToInt(header, 134, 2, little)));
Float wave2Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 136, 4, little)));
addMeta("Wavelength 2 min. intensity", wave2Min);
Float wave2Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 140, 4, little)));
addMeta("Wavelength 2 max. intensity", wave2Max);
Float wave3Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 144, 4, little)));
addMeta("Wavelength 3 min. intensity", wave3Min);
Float wave3Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 148, 4, little)));
addMeta("Wavelength 3 max. intensity", wave3Max);
Float wave4Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 152, 4, little)));
addMeta("Wavelength 4 min. intensity", wave4Min);
Float wave4Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 156, 4, little)));
addMeta("Wavelength 4 max. intensity", wave4Max);
int type = DataTools.bytesToShort(header, 160, 2, little);
String imageType;
switch (type) {
case 0:
imageType = "normal";
break;
case 1:
imageType = "Tilt-series";
break;
case 2:
imageType = "Stereo tilt-series";
break;
case 3:
imageType = "Averaged images";
break;
case 4:
imageType = "Averaged stereo pairs";
break;
default:
imageType = "unknown";
}
addMeta("Image Type", imageType);
addMeta("Lens ID Number", new Integer(DataTools.bytesToShort(
header, 162, 2, little)));
Float wave5Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 172, 4, little)));
addMeta("Wavelength 5 min. intensity", wave5Min);
Float wave5Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 176, 4, little)));
addMeta("Wavelength 5 max. intensity", wave5Max);
numT = DataTools.bytesToShort(header, 180, 2, little);
addMeta("Number of timepoints", new Integer(numT));
int sequence = DataTools.bytesToInt(header, 182, 4, little);
String imageSequence;
String dimOrder;
switch (sequence) {
case 0:
imageSequence = "ZTW"; dimOrder = "XYZTC";
break;
case 1:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
case 2:
imageSequence = "ZWT"; dimOrder = "XYZCT";
break;
case 65536:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
default:
imageSequence = "unknown"; dimOrder = "XYZTC";
}
addMeta("Image sequence", imageSequence);
addMeta("X axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 184, 4, little))));
addMeta("Y axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 188, 4, little))));
addMeta("Z axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 192, 4, little))));
numW = DataTools.bytesToShort(header, 196, 2, little);
addMeta("Number of wavelengths", new Integer(numW));
numZ = numImages / (numW * numT);
addMeta("Number of focal planes", new Integer(numZ));
addMeta("Wavelength 1 (in nm)", new Integer(DataTools.bytesToShort(
header, 198, 2, little)));
addMeta("Wavelength 2 (in nm)", new Integer(DataTools.bytesToShort(
header, 200, 2, little)));
addMeta("Wavelength 3 (in nm)", new Integer(DataTools.bytesToShort(
header, 202, 2, little)));
addMeta("Wavelength 4 (in nm)", new Integer(DataTools.bytesToShort(
header, 204, 2, little)));
addMeta("Wavelength 5 (in nm)", new Integer(DataTools.bytesToShort(
header, 206, 2, little)));
addMeta("X origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 208, 4, little))));
addMeta("Y origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 212, 4, little))));
addMeta("Z origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 216, 4, little))));
order = dimOrder;
// The metadata store we're working with.
MetadataStore store = getMetadataStore(id);
String title;
for (int i=1; i<=10; i++) {
// Make sure that "null" characters are stripped out
title = new String(header, 224 + 80*(i-1), 80).replaceAll("\0", "");
addMeta("Title " + i, title);
}
sizeX[0] = width;
sizeY[0] = height;
sizeZ[0] = numZ;
sizeC[0] = numW;
sizeT[0] = numT;
currentOrder[0] = order;
// ----- The Extended Header data handler begins here ------
numIntsPerSection = DataTools.bytesToInt(header, 128, 2, little);
numFloatsPerSection = DataTools.bytesToInt(header, 130, 2, little);
setOffsetInfo(sequence, numZ, numW, numT);
extHdrFields = new DVExtHdrFields[numZ][numW][numT];
store.setPixels(new Integer(width), new Integer(height), new Integer(numZ),
new Integer(numW), new Integer(numT), new Integer(pixelType[0]),
new Boolean(!little), dimOrder, null);
store.setDimensions(
(Float) getMeta("X element length (in um)"),
(Float) getMeta("Y element length (in um)"),
(Float) getMeta("Z element length (in um)"),
null, null, null);
String description = (String) getMeta("Title 1");
description = description.length() == 0 ? null : description;
store.setImage(id, null, description, null);
// Run through every timeslice, for each wavelength, for each z section
// and fill in the Extended Header information array for that image
for (int z = 0; z < numZ; z++) {
for (int t = 0; t < numT; t++) {
for (int w = 0; w < numW; w++) {
extHdrFields[z][w][t] = new DVExtHdrFields(getTotalOffset(z, w, t),
numIntsPerSection, extHeader, little);
store.setPlaneInfo(z, w, t,
new Float(extHdrFields[z][w][t].getTimeStampSeconds()),
new Float(extHdrFields[z][w][t].getExpTime()), null);
}
}
}
for (int w=0; w<numW; w++) {
store.setLogicalChannel(w, null,
new Float(extHdrFields[0][w][0].getNdFilter()),
(Integer) getMeta("Wavelength " + (w+1) + " (in nm)"),
new Integer((int) extHdrFields[0][w][0].getExFilter()),
"Monochrome", "Wide-field", null);
}
store.setStageLabel("ome",
new Float(extHdrFields[0][0][0].getStageXCoord()),
new Float(extHdrFields[0][0][0].getStageYCoord()),
new Float(extHdrFields[0][0][0].getStageZCoord()), null);
if (numW > 0) {
store.setChannelGlobalMinMax(0, new Double(wave1Min.floatValue()),
new Double(wave1Max.floatValue()), null);
}
if (numW > 1) {
store.setChannelGlobalMinMax(1, new Double(wave2Min.floatValue()),
new Double(wave2Max.floatValue()), null);
}
if (numW > 2) {
store.setChannelGlobalMinMax(2, new Double(wave3Min.floatValue()),
new Double(wave3Max.floatValue()), null);
}
if (numW > 3) {
store.setChannelGlobalMinMax(3, new Double(wave4Min.floatValue()),
new Double(wave4Max.floatValue()), null);
}
if (numW > 4) {
store.setChannelGlobalMinMax(4, new Double(wave5Min.floatValue()),
new Double(wave5Max.floatValue()), null);
}
store.setDefaultDisplaySettings(null);
}
| protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("DeltavisionReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
// read in the image header data
header = new byte[1024];
in.read(header);
int endian = DataTools.bytesToShort(header, 96, 2, true);
little = endian == LITTLE_ENDIAN;
numImages = DataTools.bytesToInt(header, 8, 4, little);
int extSize = DataTools.bytesToInt(header, 92, 4, little);
extHeader = new byte[extSize];
in.read(extHeader);
width = DataTools.bytesToInt(header, 0, 4, little);
height = DataTools.bytesToInt(header, 4, 4, little);
Integer xSize = new Integer(width);
Integer ySize = new Integer(height);
addMeta("ImageWidth", xSize);
addMeta("ImageHeight", ySize);
addMeta("NumberOfImages", new Integer(DataTools.bytesToInt(header,
8, 4, little)));
int filePixelType = DataTools.bytesToInt(header, 12, 4, little);
String pixel;
switch (filePixelType) {
case 0:
pixel = "8 bit unsigned integer";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
break;
case 1:
pixel = "16 bit signed integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
case 2:
pixel = "32 bit floating point";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 4;
break;
case 3:
pixel = "32 bit complex";
pixelType[0] = FormatReader.UINT32;
bytesPerPixel = 4;
break;
case 4:
pixel = "64 bit complex";
pixelType[0] = FormatReader.FLOAT;
bytesPerPixel = 8;
break;
case 6:
pixel = "16 bit unsigned integer";
pixelType[0] = FormatReader.UINT16;
bytesPerPixel = 2;
break;
default:
pixel = "unknown";
pixelType[0] = FormatReader.UINT8;
bytesPerPixel = 1;
}
addMeta("PixelType", pixel);
addMeta("Sub-image starting point (X)", new Integer(
DataTools.bytesToInt(header, 16, 4, little)));
addMeta("Sub-image starting point (Y)", new Integer(
DataTools.bytesToInt(header, 20, 4, little)));
addMeta("Sub-image starting point (Z)", new Integer(
DataTools.bytesToInt(header, 24, 4, little)));
addMeta("Pixel sampling size (X)", new Integer(
DataTools.bytesToInt(header, 28, 4, little)));
addMeta("Pixel sampling size (Y)", new Integer(
DataTools.bytesToInt(header, 32, 4, little)));
addMeta("Pixel sampling size (Z)", new Integer(
DataTools.bytesToInt(header, 36, 4, little)));
addMeta("X element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 40, 4, little))));
addMeta("Y element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 44, 4, little))));
addMeta("Z element length (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 48, 4, little))));
addMeta("X axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 52, 4, little))));
addMeta("Y axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 56, 4, little))));
addMeta("Z axis angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 60, 4, little))));
addMeta("Column axis sequence", new Integer(
DataTools.bytesToInt(header, 64, 4, little)));
addMeta("Row axis sequence", new Integer(
DataTools.bytesToInt(header, 68, 4, little)));
addMeta("Section axis sequence", new Integer(
DataTools.bytesToInt(header, 72, 4, little)));
Float wave1Min = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 76, 4, little)));
addMeta("Wavelength 1 min. intensity", wave1Min);
Float wave1Max = new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 80, 4, little)));
addMeta("Wavelength 1 max. intensity", wave1Max);
addMeta("Wavelength 1 mean intensity", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 84, 4, little))));
addMeta("Space group number", new Integer(
DataTools.bytesToInt(header, 88, 4, little)));
addMeta("Number of Sub-resolution sets", new Integer(
DataTools.bytesToInt(header, 132, 2, little)));
addMeta("Z axis reduction quotient", new Integer(
DataTools.bytesToInt(header, 134, 2, little)));
Float wave2Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 136, 4, little)));
addMeta("Wavelength 2 min. intensity", wave2Min);
Float wave2Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 140, 4, little)));
addMeta("Wavelength 2 max. intensity", wave2Max);
Float wave3Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 144, 4, little)));
addMeta("Wavelength 3 min. intensity", wave3Min);
Float wave3Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 148, 4, little)));
addMeta("Wavelength 3 max. intensity", wave3Max);
Float wave4Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 152, 4, little)));
addMeta("Wavelength 4 min. intensity", wave4Min);
Float wave4Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 156, 4, little)));
addMeta("Wavelength 4 max. intensity", wave4Max);
int type = DataTools.bytesToShort(header, 160, 2, little);
String imageType;
switch (type) {
case 0:
imageType = "normal";
break;
case 1:
imageType = "Tilt-series";
break;
case 2:
imageType = "Stereo tilt-series";
break;
case 3:
imageType = "Averaged images";
break;
case 4:
imageType = "Averaged stereo pairs";
break;
default:
imageType = "unknown";
}
addMeta("Image Type", imageType);
addMeta("Lens ID Number", new Integer(DataTools.bytesToShort(
header, 162, 2, little)));
Float wave5Min = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 172, 4, little)));
addMeta("Wavelength 5 min. intensity", wave5Min);
Float wave5Max = new Float(
Float.intBitsToFloat(DataTools.bytesToInt(header, 176, 4, little)));
addMeta("Wavelength 5 max. intensity", wave5Max);
numT = DataTools.bytesToShort(header, 180, 2, little);
addMeta("Number of timepoints", new Integer(numT));
int sequence = DataTools.bytesToInt(header, 182, 4, little);
String imageSequence;
String dimOrder;
switch (sequence) {
case 0:
imageSequence = "ZTW"; dimOrder = "XYZTC";
break;
case 1:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
case 2:
imageSequence = "ZWT"; dimOrder = "XYZCT";
break;
case 65536:
imageSequence = "WZT"; dimOrder = "XYCZT";
break;
default:
imageSequence = "unknown"; dimOrder = "XYZTC";
}
addMeta("Image sequence", imageSequence);
addMeta("X axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 184, 4, little))));
addMeta("Y axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 188, 4, little))));
addMeta("Z axis tilt angle", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 192, 4, little))));
numW = DataTools.bytesToShort(header, 196, 2, little);
addMeta("Number of wavelengths", new Integer(numW));
numZ = numImages / (numW * numT);
addMeta("Number of focal planes", new Integer(numZ));
addMeta("Wavelength 1 (in nm)", new Integer(DataTools.bytesToShort(
header, 198, 2, little)));
addMeta("Wavelength 2 (in nm)", new Integer(DataTools.bytesToShort(
header, 200, 2, little)));
addMeta("Wavelength 3 (in nm)", new Integer(DataTools.bytesToShort(
header, 202, 2, little)));
addMeta("Wavelength 4 (in nm)", new Integer(DataTools.bytesToShort(
header, 204, 2, little)));
addMeta("Wavelength 5 (in nm)", new Integer(DataTools.bytesToShort(
header, 206, 2, little)));
addMeta("X origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 208, 4, little))));
addMeta("Y origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 212, 4, little))));
addMeta("Z origin (in um)", new Float(Float.intBitsToFloat(
DataTools.bytesToInt(header, 216, 4, little))));
order = dimOrder;
// The metadata store we're working with.
MetadataStore store = getMetadataStore(id);
String title;
for (int i=1; i<=10; i++) {
// Make sure that "null" characters are stripped out
title = new String(header, 224 + 80*(i-1), 80).replaceAll("\0", "");
addMeta("Title " + i, title);
}
sizeX[0] = width;
sizeY[0] = height;
sizeZ[0] = numZ;
sizeC[0] = numW;
sizeT[0] = numT;
currentOrder[0] = order;
// ----- The Extended Header data handler begins here ------
numIntsPerSection = DataTools.bytesToInt(header, 128, 2, little);
numFloatsPerSection = DataTools.bytesToInt(header, 130, 2, little);
setOffsetInfo(sequence, numZ, numW, numT);
extHdrFields = new DVExtHdrFields[numZ][numW][numT];
store.setPixels(new Integer(width), new Integer(height), new Integer(numZ),
new Integer(numW), new Integer(numT), new Integer(pixelType[0]),
new Boolean(!little), dimOrder, null);
store.setDimensions(
(Float) getMeta("X element length (in um)"),
(Float) getMeta("Y element length (in um)"),
(Float) getMeta("Z element length (in um)"),
null, null, null);
String description = (String) getMeta("Title 1");
if (description == null) description = "";
description = description.length() == 0 ? null : description;
store.setImage(id, null, description, null);
// Run through every timeslice, for each wavelength, for each z section
// and fill in the Extended Header information array for that image
for (int z = 0; z < numZ; z++) {
for (int t = 0; t < numT; t++) {
for (int w = 0; w < numW; w++) {
extHdrFields[z][w][t] = new DVExtHdrFields(getTotalOffset(z, w, t),
numIntsPerSection, extHeader, little);
store.setPlaneInfo(z, w, t,
new Float(extHdrFields[z][w][t].getTimeStampSeconds()),
new Float(extHdrFields[z][w][t].getExpTime()), null);
}
}
}
for (int w=0; w<numW; w++) {
store.setLogicalChannel(w, null,
new Float(extHdrFields[0][w][0].getNdFilter()),
(Integer) getMeta("Wavelength " + (w+1) + " (in nm)"),
new Integer((int) extHdrFields[0][w][0].getExFilter()),
"Monochrome", "Wide-field", null);
}
store.setStageLabel("ome",
new Float(extHdrFields[0][0][0].getStageXCoord()),
new Float(extHdrFields[0][0][0].getStageYCoord()),
new Float(extHdrFields[0][0][0].getStageZCoord()), null);
if (numW > 0) {
store.setChannelGlobalMinMax(0, new Double(wave1Min.floatValue()),
new Double(wave1Max.floatValue()), null);
}
if (numW > 1) {
store.setChannelGlobalMinMax(1, new Double(wave2Min.floatValue()),
new Double(wave2Max.floatValue()), null);
}
if (numW > 2) {
store.setChannelGlobalMinMax(2, new Double(wave3Min.floatValue()),
new Double(wave3Max.floatValue()), null);
}
if (numW > 3) {
store.setChannelGlobalMinMax(3, new Double(wave4Min.floatValue()),
new Double(wave4Max.floatValue()), null);
}
if (numW > 4) {
store.setChannelGlobalMinMax(4, new Double(wave5Min.floatValue()),
new Double(wave5Max.floatValue()), null);
}
store.setDefaultDisplaySettings(null);
}
|
diff --git a/orbisgis-core/src/main/java/org/orbisgis/javaManager/autocompletion/Completion.java b/orbisgis-core/src/main/java/org/orbisgis/javaManager/autocompletion/Completion.java
index 9d851a206..7c59beb72 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/javaManager/autocompletion/Completion.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/javaManager/autocompletion/Completion.java
@@ -1,118 +1,119 @@
package org.orbisgis.javaManager.autocompletion;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import org.orbisgis.javaManager.parser.JavaParser;
import org.orbisgis.javaManager.parser.JavaParserConstants;
import org.orbisgis.javaManager.parser.ParseException;
import org.orbisgis.javaManager.parser.SimpleNode;
public class Completion {
private static final int MAX_ITERATIONS = 10;
private AutoCompletionVisitor acVisitor;
public Completion() throws LinkageError {
acVisitor = new AutoCompletionVisitor();
}
public Option[] getOptions(String text, int caretPosition, boolean script) {
ArrayList<String> versions = new ArrayList<String>();
versions.add(text);
int count = 0;
while ((count < MAX_ITERATIONS) && (versions.size() > 0)) {
String currentText = versions.remove(0);
int[] pos = NodeUtils.getPosition(currentText, caretPosition);
NodeUtils nu = new NodeUtils(currentText, pos[0], pos[1]);
ByteArrayInputStream bis = new ByteArrayInputStream(currentText
.getBytes());
try {
JavaParser parser = new JavaParser(bis);
parser.prepareParser(nu, caretPosition);
if (script) {
parser.Script();
} else {
parser.CompilationUnit();
}
SimpleNode node = (SimpleNode) parser.getRootNode();
acVisitor.setCompletionCase(text, node, pos[0], pos[1]);
acVisitor.visit(node, null);
System.out.println(currentText);
return acVisitor.getOptions();
} catch (ParseException e) {
ArrayList<String> validTexts = getValidText(currentText,
caretPosition, e);
for (String validText : validTexts) {
versions.add(validText);
}
}
count++;
}
return new Option[0];
}
private ArrayList<String> getValidText(String text, int caretPosition,
ParseException e) {
ArrayList<String> options = new ArrayList<String>();
- if ((text.charAt(caretPosition - 1) == '.')
+ if ((caretPosition > 0)
+ && (text.charAt(caretPosition - 1) == '.')
&& ((caretPosition >= text.length()) || (text
.charAt(caretPosition) != 'a'))) {
String newText = text.substring(0, caretPosition) + "a"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else if ((e.currentToken != null) && (e.currentToken.next != null)
&& (e.currentToken.next.kind == JavaParserConstants.LT)) {
String newText = text.substring(0, caretPosition) + "> a;"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else {
// Try to add from the expected token sequences
int line = e.currentToken.endLine;
int column = e.currentToken.endColumn + 1;
int pos = NodeUtils.getPosition(text, line, column);
if (canAdd(e, JavaParserConstants.RPAREN)) {
String newText = text.substring(0, pos) + ")"
+ text.substring(pos);
System.err.println("Inserting )\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.RBRACE)) {
String newText = text.substring(0, pos) + "}"
+ text.substring(pos);
System.err.println("Inserting }\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.LPAREN)) {
String newText = text.substring(0, pos) + "("
+ text.substring(pos);
System.err.println("Inserting (\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.SEMICOLON)
|| (options.size() == 0)) {
// Add a semicolon by default
String newText = text.substring(0, pos) + ";"
+ text.substring(pos);
System.err.println("Inserting ;\n" + newText);
options.add(newText);
}
}
return options;
}
private boolean canAdd(ParseException e, int wantedToken) {
int[][] seq = e.expectedTokenSequences;
for (int[] token : seq) {
if (token[0] == wantedToken) {
return true;
}
}
return false;
}
}
| true | true | private ArrayList<String> getValidText(String text, int caretPosition,
ParseException e) {
ArrayList<String> options = new ArrayList<String>();
if ((text.charAt(caretPosition - 1) == '.')
&& ((caretPosition >= text.length()) || (text
.charAt(caretPosition) != 'a'))) {
String newText = text.substring(0, caretPosition) + "a"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else if ((e.currentToken != null) && (e.currentToken.next != null)
&& (e.currentToken.next.kind == JavaParserConstants.LT)) {
String newText = text.substring(0, caretPosition) + "> a;"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else {
// Try to add from the expected token sequences
int line = e.currentToken.endLine;
int column = e.currentToken.endColumn + 1;
int pos = NodeUtils.getPosition(text, line, column);
if (canAdd(e, JavaParserConstants.RPAREN)) {
String newText = text.substring(0, pos) + ")"
+ text.substring(pos);
System.err.println("Inserting )\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.RBRACE)) {
String newText = text.substring(0, pos) + "}"
+ text.substring(pos);
System.err.println("Inserting }\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.LPAREN)) {
String newText = text.substring(0, pos) + "("
+ text.substring(pos);
System.err.println("Inserting (\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.SEMICOLON)
|| (options.size() == 0)) {
// Add a semicolon by default
String newText = text.substring(0, pos) + ";"
+ text.substring(pos);
System.err.println("Inserting ;\n" + newText);
options.add(newText);
}
}
return options;
}
| private ArrayList<String> getValidText(String text, int caretPosition,
ParseException e) {
ArrayList<String> options = new ArrayList<String>();
if ((caretPosition > 0)
&& (text.charAt(caretPosition - 1) == '.')
&& ((caretPosition >= text.length()) || (text
.charAt(caretPosition) != 'a'))) {
String newText = text.substring(0, caretPosition) + "a"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else if ((e.currentToken != null) && (e.currentToken.next != null)
&& (e.currentToken.next.kind == JavaParserConstants.LT)) {
String newText = text.substring(0, caretPosition) + "> a;"
+ text.substring(caretPosition);
System.err.println(newText);
options.add(newText);
} else {
// Try to add from the expected token sequences
int line = e.currentToken.endLine;
int column = e.currentToken.endColumn + 1;
int pos = NodeUtils.getPosition(text, line, column);
if (canAdd(e, JavaParserConstants.RPAREN)) {
String newText = text.substring(0, pos) + ")"
+ text.substring(pos);
System.err.println("Inserting )\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.RBRACE)) {
String newText = text.substring(0, pos) + "}"
+ text.substring(pos);
System.err.println("Inserting }\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.LPAREN)) {
String newText = text.substring(0, pos) + "("
+ text.substring(pos);
System.err.println("Inserting (\n" + newText);
options.add(newText);
}
if (canAdd(e, JavaParserConstants.SEMICOLON)
|| (options.size() == 0)) {
// Add a semicolon by default
String newText = text.substring(0, pos) + ";"
+ text.substring(pos);
System.err.println("Inserting ;\n" + newText);
options.add(newText);
}
}
return options;
}
|
diff --git a/modules/management/src/main/java/org/mortbay/management/ObjectMBean.java b/modules/management/src/main/java/org/mortbay/management/ObjectMBean.java
index 516a6f942..1f31d6b3b 100644
--- a/modules/management/src/main/java/org/mortbay/management/ObjectMBean.java
+++ b/modules/management/src/main/java/org/mortbay/management/ObjectMBean.java
@@ -1,679 +1,679 @@
//========================================================================
//Copyright 2004 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package org.mortbay.management;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.modelmbean.ModelMBean;
import org.mortbay.log.Log;
import org.mortbay.util.LazyList;
import org.mortbay.util.Loader;
import org.mortbay.util.TypeUtil;
/* ------------------------------------------------------------ */
/** ObjectMBean.
* A dynamic MBean that can wrap an arbitary Object instance.
* the attributes and methods exposed by this bean are controlled by
* the merge of property bundles discovered by names related to all
* superclasses and all superinterfaces.
*
* Attributes and methods exported may be "Object" and must exist on the
* wrapped object, or "MBean" and must exist on a subclass of OBjectMBean
* or "MObject" which exists on the wrapped object, but whose values are
* converted to MBean object names.
*
*/
public class ObjectMBean implements DynamicMBean
{
private static Class[] OBJ_ARG = new Class[]{Object.class};
private Object _managed;
private MBeanInfo _info;
private Map _getters=new HashMap();
private Map _setters=new HashMap();
private Map _methods=new HashMap();
private Set _convert=new HashSet();
private ClassLoader _loader;
private MBeanContainer _mbeanContainer;
private static String OBJECT_NAME_CLASS = ObjectName.class.getName();
private static String OBJECT_NAME_ARRAY_CLASS = ObjectName[].class.getName();
/* ------------------------------------------------------------ */
/**
* Create MBean for Object. Attempts to create an MBean for the object by searching the package
* and class name space. For example an object of the type
*
* <PRE>
* class com.acme.MyClass extends com.acme.util.BaseClass implements com.acme.Iface
* </PRE>
*
* Then this method would look for the following classes:
* <UL>
* <LI>com.acme.management.MyClassMBean
* <LI>com.acme.util.management.BaseClassMBean
* <LI>org.mortbay.management.ObjectMBean
* </UL>
*
* @param o The object
* @return A new instance of an MBean for the object or null.
*/
public static Object mbeanFor(Object o)
{
try
{
Class oClass = o.getClass();
Object mbean = null;
while (mbean == null && oClass != null)
{
String pName = oClass.getPackage().getName();
String cName = oClass.getName().substring(pName.length() + 1);
String mName = pName + ".management." + cName + "MBean";
try
{
Class mClass = (Object.class.equals(oClass))?oClass=ObjectMBean.class:Loader.loadClass(oClass,mName,true);
if (Log.isDebugEnabled())
Log.debug("mbeanFor " + o + " mClass=" + mClass);
try
{
Constructor constructor = mClass.getConstructor(OBJ_ARG);
mbean=constructor.newInstance(new Object[]{o});
}
catch(Exception e)
{
Log.ignore(e);
if (ModelMBean.class.isAssignableFrom(mClass))
{
mbean=mClass.newInstance();
((ModelMBean)mbean).setManagedResource(o, "objectReference");
}
}
if (Log.isDebugEnabled())
Log.debug("mbeanFor " + o + " is " + mbean);
return mbean;
}
catch (ClassNotFoundException e)
{
if (e.toString().endsWith("MBean"))
Log.ignore(e);
else
Log.warn(e);
}
catch (Error e)
{
Log.warn(e);
mbean = null;
}
catch (Exception e)
{
Log.warn(e);
mbean = null;
}
oClass = oClass.getSuperclass();
}
}
catch (Exception e)
{
Log.ignore(e);
}
return null;
}
public ObjectMBean(Object managedObject)
{
_managed = managedObject;
_loader = Thread.currentThread().getContextClassLoader();
}
protected void setMBeanContainer(MBeanContainer container)
{
this._mbeanContainer = container;
}
public MBeanInfo getMBeanInfo()
{
try
{
if (_info==null)
{
// Start with blank lazy lists attributes etc.
String desc=null;
Object attributes=null;
Object constructors=null;
Object operations=null;
Object notifications=null;
// Find list of classes that can influence the mbean
Class o_class=_managed.getClass();
Object influences = findInfluences(null, _managed.getClass());
// Set to record defined items
Set defined=new HashSet();
// For each influence
for (int i=0;i<LazyList.size(influences);i++)
{
Class oClass = (Class)LazyList.get(influences, i);
// look for a bundle defining methods
if (Object.class.equals(oClass))
oClass=ObjectMBean.class;
String pName = oClass.getPackage().getName();
String cName = oClass.getName().substring(pName.length() + 1);
String rName = pName.replace('.', '/') + "/management/" + cName+"-mbean";
try
{
Log.debug(rName);
ResourceBundle bundle = Loader.getResourceBundle(o_class, rName,true,Locale.getDefault());
// Extract meta data from bundle
Enumeration e = bundle.getKeys();
while (e.hasMoreElements())
{
String key = (String)e.nextElement();
String value = bundle.getString(key);
// Determin if key is for mbean , attribute or for operation
if (key.equals(cName))
{
// set the mbean description
if (desc==null)
desc=value;
}
else if (key.indexOf('(')>0)
{
// define an operation
if (!defined.contains(key) && key.indexOf('[')<0)
{
defined.add(key);
operations=LazyList.add(operations,defineOperation(key, value, bundle));
}
}
else
{
// define an attribute
if (!defined.contains(key))
{
defined.add(key);
attributes=LazyList.add(attributes,defineAttribute(key, value));
}
}
}
}
catch(MissingResourceException e)
{
Log.ignore(e);
}
}
_info = new MBeanInfo(o_class.getName(),
desc,
(MBeanAttributeInfo[])LazyList.toArray(attributes, MBeanAttributeInfo.class),
(MBeanConstructorInfo[])LazyList.toArray(constructors, MBeanConstructorInfo.class),
(MBeanOperationInfo[])LazyList.toArray(operations, MBeanOperationInfo.class),
(MBeanNotificationInfo[])LazyList.toArray(notifications, MBeanNotificationInfo.class));
}
}
catch(RuntimeException e)
{
Log.warn(e);
throw e;
}
return _info;
}
/* ------------------------------------------------------------ */
public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException
{
if (Log.isDebugEnabled())
Log.debug("getAttribute " + name);
Method getter = (Method) _getters.get(name);
if (getter == null)
throw new AttributeNotFoundException(name);
try
{
Object o = _managed;
if (getter.getDeclaringClass().isInstance(this))
o = this; // mbean method
// get the attribute
Object r=getter.invoke(o, (java.lang.Object[]) null);
// convert to ObjectName if need be.
if (r!=null && _convert.contains(name))
{
if (r.getClass().isArray())
{
ObjectName[] on = new ObjectName[Array.getLength(r)];
for (int i=0;i<on.length;i++)
on[i]=_mbeanContainer.findMBean(Array.get(r, i));
r=on;
}
else
{
ObjectName mbean = _mbeanContainer.findMBean(r);
if (mbean==null)
return null;
r=mbean;
}
}
return r;
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new AttributeNotFoundException(e.toString());
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
}
/* ------------------------------------------------------------ */
public AttributeList getAttributes(String[] names)
{
Log.debug("getAttributes");
AttributeList results = new AttributeList(names.length);
for (int i = 0; i < names.length; i++)
{
try
{
results.add(new Attribute(names[i], getAttribute(names[i])));
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
}
}
return results;
}
/* ------------------------------------------------------------ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
if (attr == null)
return;
if (Log.isDebugEnabled())
Log.debug("setAttribute " + attr.getName() + "=" + attr.getValue());
Method setter = (Method) _setters.get(attr.getName());
if (setter == null)
throw new AttributeNotFoundException(attr.getName());
try
{
Object o = _managed;
if (setter.getDeclaringClass().isInstance(this))
o = this;
// get the value
Object value = attr.getValue();
// convert from ObjectName if need be
if (value!=null && _convert.contains(attr.getName()))
{
if (value.getClass().isArray())
{
Class t=setter.getParameterTypes()[0].getComponentType();
Object na = Array.newInstance(t,Array.getLength(value));
for (int i=Array.getLength(value);i-->0;)
Array.set(na, i, _mbeanContainer.findBean((ObjectName)Array.get(value, i)));
value=na;
}
else
value=_mbeanContainer.findBean((ObjectName)value);
}
// do the setting
setter.invoke(o, new Object[]{ value });
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new AttributeNotFoundException(e.toString());
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
}
/* ------------------------------------------------------------ */
public AttributeList setAttributes(AttributeList attrs)
{
Log.debug("setAttributes");
AttributeList results = new AttributeList(attrs.size());
Iterator iter = attrs.iterator();
while (iter.hasNext())
{
try
{
Attribute attr = (Attribute) iter.next();
setAttribute(attr);
results.add(new Attribute(attr.getName(), getAttribute(attr.getName())));
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
}
}
return results;
}
/* ------------------------------------------------------------ */
public Object invoke(String name, Object[] params, String[] signature) throws MBeanException, ReflectionException
{
if (Log.isDebugEnabled())
Log.debug("invoke " + name);
String methodKey = name + "(";
if (signature != null)
for (int i = 0; i < signature.length; i++)
methodKey += (i > 0 ? "," : "") + signature[i];
methodKey += ")";
ClassLoader old_loader=Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(_loader);
Method method = (Method) _methods.get(methodKey);
if (method == null)
throw new NoSuchMethodException(methodKey);
Object o = _managed;
if (method.getDeclaringClass().isInstance(this))
o = this;
return method.invoke(o, params);
}
catch (NoSuchMethodException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException(e);
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new MBeanException(e);
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
finally
{
Thread.currentThread().setContextClassLoader(old_loader);
}
}
private static Object findInfluences(Object influences, Class aClass)
{
if (aClass!=null)
{
// This class is an influence
influences=LazyList.add(influences,aClass);
// So are the super classes
influences=findInfluences(influences,aClass.getSuperclass());
// So are the interfaces
Class[] ifs = aClass.getInterfaces();
for (int i=0;ifs!=null && i<ifs.length;i++)
influences=findInfluences(influences,ifs[i]);
}
return influences;
}
/* ------------------------------------------------------------ */
/**
* Define an attribute on the managed object. The meta data is defined by looking for standard
* getter and setter methods. Descriptions are obtained with a call to findDescription with the
* attribute name.
*
* @param name
* @param metaData "description" or "access:description" or "type:access:description" where type is
* the "Object","MBean" or "MObject" to indicate the method is on the object, the MBean or on the object but converted to an MBean, access
* is either "RW" or "RO".
*/
public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
- throw new IllegalArgumentException("Multiple getters for attr " + name);
+ throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
- throw new IllegalArgumentException("Multiple getters for attr " + name);
+ throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
- throw new IllegalArgumentException("Multiple setters for attr " + name);
+ throw new IllegalArgumentException("Multiple setters for attr " + name+ " in "+oClass);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
- throw new IllegalArgumentException("No getter or setters found for " + name);
+ throw new IllegalArgumentException("No getter or setters found for " + name+ " in "+oClass);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
/* ------------------------------------------------------------ */
/**
* Define an operation on the managed object. Defines an operation with parameters. Refection is
* used to determine find the method and it's return type. The description of the method is
* found with a call to findDescription on "name(signature)". The name and description of each
* parameter is found with a call to findDescription with "name(partialSignature", the returned
* description is for the last parameter of the partial signature and is assumed to start with
* the parameter name, followed by a colon.
*
* @param metaData "description" or "impact:description" or "type:impact:description", type is
* the "Object","MBean" or "MObject" to indicate the method is on the object, the MBean or on the
* object but converted to an MBean, and impact is either "ACTION","INFO","ACTION_INFO" or "UNKNOWN".
*/
private MBeanOperationInfo defineOperation(String signature, String metaData, ResourceBundle bundle)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
String impact_name = i<0?"UNKNOWN":tokens[i--];
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
if (Log.isDebugEnabled())
Log.debug("defineOperation "+signature+" "+onMBean+":"+impact_name+":"+description);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
try
{
// Resolve the impact
int impact=MBeanOperationInfo.UNKNOWN;
if (impact_name==null || impact_name.equals("UNKNOWN"))
impact=MBeanOperationInfo.UNKNOWN;
else if (impact_name.equals("ACTION"))
impact=MBeanOperationInfo.ACTION;
else if (impact_name.equals("INFO"))
impact=MBeanOperationInfo.INFO;
else if (impact_name.equals("ACTION_INFO"))
impact=MBeanOperationInfo.ACTION_INFO;
else
Log.warn("Unknown impact '"+impact_name+"' for "+signature);
// split the signature
String[] parts=signature.split("[\\(\\)]");
String method_name=parts[0];
String arguments=parts.length==2?parts[1]:null;
String[] args=arguments==null?new String[0]:arguments.split(" *, *");
// Check types and normalize signature.
Class[] types = new Class[args.length];
MBeanParameterInfo[] pInfo = new MBeanParameterInfo[args.length];
signature=method_name;
for (i = 0; i < args.length; i++)
{
Class type = TypeUtil.fromName(args[i]);
if (type == null)
type = Thread.currentThread().getContextClassLoader().loadClass(args[i]);
types[i] = type;
args[i] = type.isPrimitive() ? TypeUtil.toName(type) : args[i];
signature+=(i>0?",":"(")+args[i];
}
signature+=(i>0?")":"()");
// Build param infos
for (i = 0; i < args.length; i++)
{
String param_desc = bundle.getString(signature + "[" + i + "]");
parts=param_desc.split(" *: *",2);
if (Log.isDebugEnabled())
Log.debug(parts[0]+": "+parts[1]);
pInfo[i] = new MBeanParameterInfo(parts[0].trim(), args[i], parts[1].trim());
}
// build the operation info
Method method = oClass.getMethod(method_name, types);
Class returnClass = method.getReturnType();
_methods.put(signature, method);
if (convert)
_convert.add(signature);
return new MBeanOperationInfo(method_name, description, pInfo, returnClass.isPrimitive() ? TypeUtil.toName(returnClass) : (returnClass.getName()), impact);
}
catch (Exception e)
{
Log.warn("Operation '"+signature+"'", e);
throw new IllegalArgumentException(e.toString());
}
}
}
| false | true | public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
throw new IllegalArgumentException("Multiple setters for attr " + name);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
throw new IllegalArgumentException("No getter or setters found for " + name);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
| public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
throw new IllegalArgumentException("Multiple setters for attr " + name+ " in "+oClass);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
throw new IllegalArgumentException("No getter or setters found for " + name+ " in "+oClass);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
|
diff --git a/fabric/fabric-commands/src/main/java/org/fusesource/fabric/commands/MQCreate.java b/fabric/fabric-commands/src/main/java/org/fusesource/fabric/commands/MQCreate.java
index 45c81fba8..299d7e6b5 100644
--- a/fabric/fabric-commands/src/main/java/org/fusesource/fabric/commands/MQCreate.java
+++ b/fabric/fabric-commands/src/main/java/org/fusesource/fabric/commands/MQCreate.java
@@ -1,158 +1,158 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.commands;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.CreateContainerMetadata;
import org.fusesource.fabric.api.CreateContainerOptions;
import org.fusesource.fabric.api.CreateContainerOptionsBuilder;
import org.fusesource.fabric.api.MQService;
import org.fusesource.fabric.api.Profile;
import org.fusesource.fabric.boot.commands.support.FabricCommand;
import org.fusesource.fabric.service.MQServiceImpl;
import org.fusesource.fabric.zookeeper.ZkDefs;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
@Command(name = "mq-create", scope = "fabric", description = "Create a new broker")
public class MQCreate extends FabricCommand {
@Argument(index=0, required = true, description = "Broker name")
protected String name = null;
@Option(name = "--config", description = "Configuration to use")
protected String config;
@Option(name = "--data", description = "Data directory for the broker")
protected String data;
@Option(name = "--group", description = "Broker group")
protected String group;
@Option(name = "--networks", description = "Broker networks")
protected String networks;
@Option(name = "--version", description = "The version id in the registry")
protected String version = ZkDefs.DEFAULT_VERSION;
@Option(name = "--create-container", multiValued = false, required = false, description = "Comma separated list of containers to create with mq profile")
protected String create;
@Option(name = "--assign-container", multiValued = false, required = false, description = "Assign this mq profile to the following containers")
protected String assign;
@Override
protected Object doExecute() throws Exception {
// create profile
MQService service = new MQServiceImpl(fabricService);
HashMap<String, String> configuration = new HashMap<String, String>();
if (data == null) {
data = System.getProperty("karaf.base") + System.getProperty("file.separator")+ "data" + System.getProperty("file.separator") + name;
}
configuration.put("data", data);
if (config != null) {
configuration.put("config", service.getConfig(version, config));
}
if (group != null) {
configuration.put("group", group);
}
if (networks != null) {
configuration.put("network", networks);
}
Profile profile = service.createMQProfile(version, name, configuration);
System.out.println("MQ profile " + profile.getId() + " ready");
// assign profile to existing containers
if (assign != null) {
String[] assignContainers = assign.split(",");
for (String containerName : assignContainers) {
try {
Container container = fabricService.getContainer(containerName);
if (container == null) {
System.out.println("Failed to assign profile to " + containerName + ": profile doesn't exists");
} else {
HashSet<Profile> profiles = new HashSet<Profile>(Arrays.asList(container.getProfiles()));
profiles.add(profile);
container.setProfiles(profiles.toArray(new Profile[profiles.size()]));
System.out.println("Profile successfully assigned to " + containerName);
}
} catch (Exception e) {
System.out.println("Failed to assign profile to " + containerName + ": " + e.getMessage());
}
}
}
// create new containers
if (create != null) {
String[] createContainers = create.split(",");
for (String url : createContainers) {
String type = null;
- String parent = "root";
+ String parent = fabricService.getCurrentContainerName();
String name = url;
if (url.contains("://")) {
URI uri = new URI(url);
type = uri.getScheme();
parent = null;
name = uri.getHost();
} else {
type = "child";
- url = "child://root";
+ url = "child://" + parent;
}
CreateContainerOptions args = CreateContainerOptionsBuilder.type(type)
.name(name)
.parent(parent)
.number(1)
.ensembleServer(false)
.providerUri(url)
.proxyUri(fabricService.getMavenRepoURI())
.zookeeperUrl(fabricService.getZookeeperUrl());
CreateContainerMetadata[] metadatas = fabricService.createContainers(args);
for (CreateContainerMetadata metadata : metadatas) {
if (metadata.isSuccess()) {
Container child = metadata.getContainer();
child.setProfiles(new Profile[]{profile});
System.out.println("Successfully created container " + metadata.getContainerName());
} else {
System.out.println("Failed to create container " + metadata.getContainerName() + ": " + metadata.getFailure().getMessage());
}
}
}
}
return null;
}
}
| false | true | protected Object doExecute() throws Exception {
// create profile
MQService service = new MQServiceImpl(fabricService);
HashMap<String, String> configuration = new HashMap<String, String>();
if (data == null) {
data = System.getProperty("karaf.base") + System.getProperty("file.separator")+ "data" + System.getProperty("file.separator") + name;
}
configuration.put("data", data);
if (config != null) {
configuration.put("config", service.getConfig(version, config));
}
if (group != null) {
configuration.put("group", group);
}
if (networks != null) {
configuration.put("network", networks);
}
Profile profile = service.createMQProfile(version, name, configuration);
System.out.println("MQ profile " + profile.getId() + " ready");
// assign profile to existing containers
if (assign != null) {
String[] assignContainers = assign.split(",");
for (String containerName : assignContainers) {
try {
Container container = fabricService.getContainer(containerName);
if (container == null) {
System.out.println("Failed to assign profile to " + containerName + ": profile doesn't exists");
} else {
HashSet<Profile> profiles = new HashSet<Profile>(Arrays.asList(container.getProfiles()));
profiles.add(profile);
container.setProfiles(profiles.toArray(new Profile[profiles.size()]));
System.out.println("Profile successfully assigned to " + containerName);
}
} catch (Exception e) {
System.out.println("Failed to assign profile to " + containerName + ": " + e.getMessage());
}
}
}
// create new containers
if (create != null) {
String[] createContainers = create.split(",");
for (String url : createContainers) {
String type = null;
String parent = "root";
String name = url;
if (url.contains("://")) {
URI uri = new URI(url);
type = uri.getScheme();
parent = null;
name = uri.getHost();
} else {
type = "child";
url = "child://root";
}
CreateContainerOptions args = CreateContainerOptionsBuilder.type(type)
.name(name)
.parent(parent)
.number(1)
.ensembleServer(false)
.providerUri(url)
.proxyUri(fabricService.getMavenRepoURI())
.zookeeperUrl(fabricService.getZookeeperUrl());
CreateContainerMetadata[] metadatas = fabricService.createContainers(args);
for (CreateContainerMetadata metadata : metadatas) {
if (metadata.isSuccess()) {
Container child = metadata.getContainer();
child.setProfiles(new Profile[]{profile});
System.out.println("Successfully created container " + metadata.getContainerName());
} else {
System.out.println("Failed to create container " + metadata.getContainerName() + ": " + metadata.getFailure().getMessage());
}
}
}
}
return null;
}
| protected Object doExecute() throws Exception {
// create profile
MQService service = new MQServiceImpl(fabricService);
HashMap<String, String> configuration = new HashMap<String, String>();
if (data == null) {
data = System.getProperty("karaf.base") + System.getProperty("file.separator")+ "data" + System.getProperty("file.separator") + name;
}
configuration.put("data", data);
if (config != null) {
configuration.put("config", service.getConfig(version, config));
}
if (group != null) {
configuration.put("group", group);
}
if (networks != null) {
configuration.put("network", networks);
}
Profile profile = service.createMQProfile(version, name, configuration);
System.out.println("MQ profile " + profile.getId() + " ready");
// assign profile to existing containers
if (assign != null) {
String[] assignContainers = assign.split(",");
for (String containerName : assignContainers) {
try {
Container container = fabricService.getContainer(containerName);
if (container == null) {
System.out.println("Failed to assign profile to " + containerName + ": profile doesn't exists");
} else {
HashSet<Profile> profiles = new HashSet<Profile>(Arrays.asList(container.getProfiles()));
profiles.add(profile);
container.setProfiles(profiles.toArray(new Profile[profiles.size()]));
System.out.println("Profile successfully assigned to " + containerName);
}
} catch (Exception e) {
System.out.println("Failed to assign profile to " + containerName + ": " + e.getMessage());
}
}
}
// create new containers
if (create != null) {
String[] createContainers = create.split(",");
for (String url : createContainers) {
String type = null;
String parent = fabricService.getCurrentContainerName();
String name = url;
if (url.contains("://")) {
URI uri = new URI(url);
type = uri.getScheme();
parent = null;
name = uri.getHost();
} else {
type = "child";
url = "child://" + parent;
}
CreateContainerOptions args = CreateContainerOptionsBuilder.type(type)
.name(name)
.parent(parent)
.number(1)
.ensembleServer(false)
.providerUri(url)
.proxyUri(fabricService.getMavenRepoURI())
.zookeeperUrl(fabricService.getZookeeperUrl());
CreateContainerMetadata[] metadatas = fabricService.createContainers(args);
for (CreateContainerMetadata metadata : metadatas) {
if (metadata.isSuccess()) {
Container child = metadata.getContainer();
child.setProfiles(new Profile[]{profile});
System.out.println("Successfully created container " + metadata.getContainerName());
} else {
System.out.println("Failed to create container " + metadata.getContainerName() + ": " + metadata.getFailure().getMessage());
}
}
}
}
return null;
}
|
diff --git a/src/org/reprap/geometry/polygons/RrPolygonList.java b/src/org/reprap/geometry/polygons/RrPolygonList.java
index 61bca52..19e0a6d 100644
--- a/src/org/reprap/geometry/polygons/RrPolygonList.java
+++ b/src/org/reprap/geometry/polygons/RrPolygonList.java
@@ -1,914 +1,915 @@
/*
RepRap
------
The Replicating Rapid Prototyper Project
Copyright (C) 2005
Adrian Bowyer & The University of Bath
http://reprap.org
Principal author:
Adrian Bowyer
Department of Mechanical Engineering
Faculty of Engineering and Design
University of Bath
Bath BA2 7AY
U.K.
e-mail: [email protected]
RepRap is free; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
Licence as published by the Free Software Foundation; either
version 2 of the Licence, or (at your option) any later version.
RepRap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public Licence for more details.
For this purpose the words "software" and "library" in the GNU Library
General Public Licence are taken to mean any and all computer programs
computer files data results documents and other copyright information
available from the RepRap project.
You should have received a copy of the GNU Library General Public
Licence along with RepRap; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA,
or see
http://www.gnu.org/
=====================================================================
RrPolygonList: A collection of 2D polygons
First version 20 May 2005
This version: 1 May 2006 (Now in CVS - no more comments here)
*/
package org.reprap.geometry.polygons;
import java.io.*;
import java.util.*;
/**
* chPair - small class to hold double pointers for convex hull calculations.
*/
class chPair
{
public int polygon;
public int vertex;
chPair(int p, int v)
{
polygon = p;
vertex = v;
}
}
/**
* RrPolygonList: A collection of 2D polygons
*
* List of polygons class. This too maintains a maximum enclosing rectangle.
* Each polygon has an associated type that can be used to record any attribute
* of the polygon.
*/
public class RrPolygonList
{
public List polygons;
public RrBox box;
// Empty constructor
public RrPolygonList()
{
polygons = new ArrayList();
box = new RrBox();
}
// Get the data
public RrPolygon polygon(int i)
{
return (RrPolygon)polygons.get(i);
}
public int size()
{
return polygons.size();
}
/**
* Deep copy
* @param lst
*/
public RrPolygonList(RrPolygonList lst)
{
polygons = new ArrayList();
box = new RrBox(lst.box);
int leng = lst.size();
for(int i = 0; i < leng; i++)
polygons.add(new RrPolygon(lst.polygon(i)));
}
/**
* Put a new list on the end
* @param lst
*/
public void add(RrPolygonList lst)
{
int leng = lst.size();
if(leng == 0)
return;
for(int i = 0; i < leng; i++)
polygons.add(new RrPolygon(lst.polygon(i)));
box.expand(lst.box);
}
/**
* Add one new polygon to the list
* @param p
*/
public void add(RrPolygon p)
{
//add(p.no_cross());
polygons.add(p);
box.expand(p.box);
}
/**
* Negate all the polygons
* @return
*/
public RrPolygonList negate()
{
RrPolygonList result = new RrPolygonList();
int leng = size();
for(int i = 0; i < leng; i++)
{
result.polygons.add(polygon(i).negate());
}
result.box = new RrBox(box);
return result;
}
/**
* Write as an SVG xml to file opf
* @param opf
*/
public void svg(PrintStream opf)
{
opf.println("<?xml version=\"1.0\" standalone=\"no\"?>");
opf.println("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"");
opf.println("\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">");
opf.println("<svg");
opf.println(" width=\"" + Double.toString(box.x().length()) + "mm\"");
opf.println(" height=\"" + Double.toString(box.y().length()) + "mm\"");
opf.print(" viewBox=\"" + Double.toString(box.x().low()));
opf.print(" " + Double.toString(box.y().low()));
opf.print(" " + Double.toString(box.x().high()));
opf.println(" " + Double.toString(box.y().high()) + "\"");
opf.println(" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">");
opf.println(" <desc>RepRap polygon list - http://reprap.org</desc>");
int leng = size();
for(int i = 0; i < leng; i++)
polygon(i).svg(opf);
opf.println("</svg>");
}
/**
* Simplify all polygons by length d
* N.B. this may throw away small ones completely
* @param d
* @return
*/
public RrPolygonList simplify(double d)
{
RrPolygonList r = new RrPolygonList();
int leng = size();
double d2 = d*d;
for(int i = 0; i < leng; i++)
{
RrPolygon p = polygon(i);
if(p.box.d_2() > 2*d2)
r.add(p.simplify(d));
}
return r;
}
// Convex hull code - this uses the QuickHull algorithm
/**
* find a point from a list of polygon/vertex pairs
* @Param i
* @param a
* @return the point
*/
private Rr2Point listPoint(int i, List a)
{
chPair chp = (chPair)a.get(i);
return polygon(chp.polygon).point(chp.vertex);
}
/**
* find a polygon from a list of polygon/vertex pairs
* @Param i
* @param a
* @return the point
*/
private RrPolygon listPolygon(int i, List a)
{
chPair chp = (chPair)a.get(i);
return polygon(chp.polygon);
}
/**
* find a vertex from a list of polygon/vertex pairs
* @Param i
* @param a
* @return the vertex index
*/
private int listVertex(int i, List a)
{
chPair chp = (chPair)a.get(i);
return chp.vertex;
}
/**
* find a list entry from a polygon/vertex pair
* @Param p
* @param v
* @param a
* @return the index of the entry (-1 if not found)
*/
private int listFind(RrPolygon p, int v, List a)
{
int i;
chPair chp;
for(i = 0; i < a.size(); i++)
{
chp = (chPair)a.get(i);
if(chp.vertex == v && polygon(chp.polygon) == p)
return i;
}
return -1;
}
/**
* find a flag from a list of polygon/vertex pairs
* @Param i
* @param a
* @return the point
*/
private int listFlag(int i, List a)
{
chPair chp = (chPair)a.get(i);
return polygon(chp.polygon).flag(chp.vertex);
}
/**
* find the top (+y) point of the polygon list
* @return the index/polygon pair of the point
*/
private int topPoint(List chps)
{
int top = 0;
double yMax = listPoint(top, chps).y();
double y;
for(int i = 1; i < chps.size(); i++)
{
y = listPoint(i, chps).y();
if(y > yMax)
{
yMax = y;
top = i;
}
}
return top;
}
/**
* find the bottom (-y) point of the polygons
* @return the index in the list of the point
*/
private int bottomPoint(List chps)
{
int bot = 0;
double yMin = listPoint(bot, chps).y();
double y;
for(int i = 1; i < chps.size(); i++)
{
y = listPoint(i, chps).y();
if(y < yMin)
{
yMin = y;
bot = i;
}
}
return bot;
}
/**
* Put the points on a triangle in the right order
* @param a
*/
private void clockWise(List a)
{
if(a.size() == 3)
{
Rr2Point q = Rr2Point.sub(listPoint(1, a), listPoint(0, a));
Rr2Point r = Rr2Point.sub(listPoint(2, a), listPoint(0, a));
if(Rr2Point.op(q, r) > 0)
{
Object k = a.get(0);
a.set(0, a.get(1));
a.set(1, k);
}
} else
System.err.println("clockWise(): not called for a triangle!");
}
/**
* Turn the list of hull points into a CSG convex polygon
* @param hullPoints
* @return CSG representation
*/
public RrCSG toCSGHull(List hullPoints)
{
Rr2Point p, q;
RrCSG hull = RrCSG.universe();
int i, iPlus;
for(i = 0; i < hullPoints.size(); i++)
{
iPlus = (i + 1)%hullPoints.size();
p = listPoint(i, hullPoints);
q = listPoint(iPlus, hullPoints);
hull = RrCSG.intersection(hull, new RrCSG(new RrHalfPlane(p, q)));
}
return hull;
}
/**
* Turn a list of hull points into a polygon
* @param hullPoints
* @return the hull as another polygon
*/
public RrPolygon toRrPolygonHull(List hullPoints, int flag)
{
RrPolygon hull = new RrPolygon();
for(int i = 0; i < hullPoints.size(); i++)
hull.add(listPoint(i, hullPoints), flag);
return hull;
}
/**
* Remove all the points in a list that are within or on the hull
* @param inConsideration
* @param hull
*/
private void outsideHull(List inConsideration, RrCSG hull)
{
Rr2Point p;
double v;
int i = inConsideration.size() - 1;
while(i >= 0)
{
p = listPoint(i, inConsideration);
v = hull.value(p);
if(v <= 1.0e-6) // Need an epsilon here?
{
inConsideration.remove(i);
}
i--;
}
}
/**
* Compute the convex hull of all the points in the list
* @param points
* @return list of point index pairs of the points on the hull
*/
private List convexHull(List points)
{
List inConsideration = new ArrayList(points);
int i;
// The top-most and bottom-most points must be on the hull
List result = new ArrayList();
int t = topPoint(inConsideration);
int b = bottomPoint(inConsideration);
result.add(inConsideration.get(t));
result.add(inConsideration.get(b));
if(t > b)
{
inConsideration.remove(t);
inConsideration.remove(b);
} else
{
inConsideration.remove(b);
inConsideration.remove(t);
}
// Repeatedly add the point that's furthest outside the current hull
int corner, after;
RrCSG hull;
double v, vMax;
Rr2Point p, q;
RrHalfPlane hp;
while(inConsideration.size() > 0)
{
vMax = 0; // Need epsilon?
corner = -1;
after = -1;
for(int testPoint = inConsideration.size() - 1; testPoint >= 0; testPoint--)
{
p = listPoint(result.size() - 1, result);
for(i = 0; i < result.size(); i++)
{
q = listPoint(i, result);
hp = new RrHalfPlane(p, q);
v = hp.value(listPoint(testPoint, inConsideration));
if(result.size() == 2)
v = Math.abs(v);
if(v > vMax)
{
after = i;
vMax = v;
corner = testPoint;
}
p = q;
}
}
if(corner >= 0)
{
result.add(after, inConsideration.get(corner));
inConsideration.remove(corner);
} else if(inConsideration.size() > 0)
{
System.err.println("convexHull(): points left, but none included!");
return result;
}
// Get the first triangle in the right order
if(result.size() == 3)
clockWise(result);
// Remove all points within the current hull from further consideration
hull = toCSGHull(result);
outsideHull(inConsideration, hull);
}
return result;
}
/**
* Construct a list of all the points in the polygons
* @return list of point index pairs of the points in the polygons
*/
private List allPoints()
{
List points = new ArrayList();
for(int i = 0; i < size(); i++)
{
for(int j = 0; j < polygon(i).size(); j++)
points.add(new chPair(i, j));
}
return points;
}
/**
* Compute the convex hull of all the polygons in the list
* @return list of point index pairs of the points on the hull
*/
public List convexHull()
{
return convexHull(allPoints());
}
/**
* Set the polygon flag values for the points in a list
* @param a
* @param flag
*/
private boolean flagSet(List a, int flag)
{
RrPolygon pg = listPolygon(0, a);
boolean result = true;
for(int i = 0; i < a.size(); i++)
{
chPair chp = (chPair)a.get(i);
polygon(chp.polygon).flag(chp.vertex, flag);
if(polygon(chp.polygon) != pg)
result = false;
}
return result;
}
/**
* Get the next whole section to consider from list a
* @param a
* @param level
* @return the section (null for none left)
*/
private List polSection(List a, int level)
{
System.out.println("polSection() in - " + a.size());
int flag, oldi;
oldi = a.size() - 1;
RrPolygon oldPg = listPolygon(oldi, a);
int oldFlag = listFlag(oldi, a);
RrPolygon pg = null;
int ptr = -1;
int pgStart = 0;
for(int i = 0; i < a.size(); i++)
{
flag = listFlag(i, a);
pg = listPolygon(i, a);
if(pg != oldPg)
pgStart = i;
if(flag < level && oldFlag >= level && pg == oldPg)
{
ptr = oldi;
break;
}
oldi = i;
oldFlag = flag;
oldPg = pg;
}
if(ptr < 0)
return null;
List result = new ArrayList();
result.add(a.get(ptr));
ptr++;
if(ptr > a.size() - 1)
ptr = pgStart;
while(listFlag(ptr, a) < level)
{
result.add(a.get(ptr));
ptr++;
if(ptr > a.size() - 1)
ptr = pgStart;
}
result.add(a.get(ptr));
System.out.println("polSection() out - " + result.size());
return result;
}
/**
* Find if the polygon for point i in a is in list res
* @param i
* @param a
* @param res
* @return true if it is
*/
private boolean inList(int i, List a, List res)
{
RrPolygon pg = listPolygon(i, a);
for(int j = 0; j < res.size(); j++)
{
if((RrPolygon)res.get(j) == pg)
return true;
}
return false;
}
/**
* Get all whole polygons from list a
* @param a
* @param level
* @return the polygons (null for none left)
*/
private RrPolygonList getComplete(List a, int level)
{
System.out.println("getComplete() in - " + a.size());
List res = new ArrayList();
RrPolygon pg = listPolygon(0, a);
int count = 0;
boolean gotOne = true;
for(int i = 0; i < a.size(); i++)
{
if(listPolygon(i, a) != pg)
{
if(count == pg.size() && gotOne)
res.add(pg);
count = 0;
gotOne = true;
pg = listPolygon(i, a);
}
if(listFlag(i, a) >= level)
gotOne = false;
count++;
}
if(count == pg.size() && gotOne)
res.add(pg);
if(res.size() > 0)
{
for(int i = a.size() - 1; i >= 0; i--)
{
if(inList(i, a, res))
a.remove(i);
}
RrPolygonList result = new RrPolygonList();
for(int i = 0; i < res.size(); i++)
{
pg = (RrPolygon)res.get(i);
double area = pg.area();
if(level%2 == 1)
{
if(area > 0)
pg = pg.negate();
} else
{
if(area < 0)
pg = pg.negate();
}
result.add(pg);
}
System.out.println("getComplete() out - " + result.size());
return result;
}
else
return null;
}
/**
* Find all the polygons that form the convex hull
* @param ch
* @return
*/
private RrPolygonList outerPols(List ch)
{
RrPolygonList result = new RrPolygonList();
RrPolygon pg = null;
for(int i = 0; i < ch.size(); i++)
{
if(listPolygon(i, ch) != pg)
{
pg = listPolygon(i, ch);
result.add(pg);
}
}
return result;
}
/**
* Compute the CSG representation of a (sub)list recursively
* @param a
* @param level
* @return CSG representation
*/
private RrCSG toCSGRecursive(List a, int level, boolean closed)
{
System.out.println("toCSGRecursive() - " + a.size());
flagSet(a, level);
level++;
List ch = convexHull(a);
boolean onePol = flagSet(ch, level);
RrCSG hull;
if(!onePol)
{
RrPolygonList op = outerPols(ch);
hull = RrCSG.nothing();
for(int i = 0; i < op.size(); i++)
{
RrPolygonList pgl = new RrPolygonList();
pgl.add(op.polygon(i));
List all = pgl.allPoints();
hull = RrCSG.union(hull, pgl.toCSGRecursive(all, level - 1, true));
}
+ // remove polygon from a!!
}else
{
if(level%2 == 1)
hull = RrCSG.universe();
else
hull = RrCSG.nothing();
}
// First deal with all the polygons with no points on the hull
// (i.e. they are completely inside).
if(closed)
{
RrPolygonList completePols = getComplete(a, level);
if(completePols != null)
{
List all = completePols.allPoints();
if(level%2 == 1)
hull = RrCSG.intersection(hull,
completePols.toCSGRecursive(all, level, true));
else
hull = RrCSG.union(hull,
completePols.toCSGRecursive(all, level, true));
}
}
// Set-theoretically combine all the real edges on the convex hull
int i, oldi, flag, oldFlag, start;
RrPolygon pg, oldPg;
if(closed)
{
oldi = a.size() - 1;
start = 0;
} else
{
oldi = 0;
start = 1;
}
for(i = start; i < a.size(); i++)
{
oldFlag = listFlag(oldi, a);
oldPg = listPolygon(oldi, a);
flag = listFlag(i, a);
pg = listPolygon(i, a);
if(oldFlag == level && flag == level && pg == oldPg)
{
RrHalfPlane hp = new RrHalfPlane(listPoint(oldi, a), listPoint(i, a));
if(level%2 == 1)
hull = RrCSG.intersection(hull, new RrCSG(hp));
else
hull = RrCSG.union(hull, new RrCSG(hp));
}
oldi = i;
}
// Finally deal with the sections on polygons that form the hull that
// are not themselves on the hull.
List section = polSection(a, level);
while(section != null)
{
if(level%2 == 1)
hull = RrCSG.intersection(hull,
toCSGRecursive(section, level, false));
else
hull = RrCSG.union(hull,
toCSGRecursive(section, level, false));
section = polSection(a, level);
}
return hull;
}
/**
* Compute the CSG representation of all the polygons in the list
* using Kai Tang and Tony Woo's algorithm.
* @return CSG representation
*/
public RrCSGPolygon toCSG()
{
RrPolygonList pgl = new RrPolygonList(this);
List all = pgl.allPoints();
pgl.flagSet(all, -1);
pgl = pgl.getComplete(all, 0);
all = pgl.allPoints();
return new RrCSGPolygon(pgl.toCSGRecursive(all, 0, true), pgl.box.scale(1.1));
}
/**
* Intersect a line with a polygon list, returning an
* unsorted list of the intersection parameters
* @param l0
* @return
*/
public List pl_intersect(RrLine l0)
{
int leng = size();
List t = new ArrayList();
for(int i = 0; i < leng; i++)
{
List t1 = polygon(i).pl_intersect(l0);
int leng1 = t1.size();
for(int j = 0; j < leng1; j++)
t.add(t1.get(j));
}
return t;
}
// /**
// * Offset every polygon in the list
// * @param d
// * @return
// */
// public RrPolygonList offset(double d)
// {
// int leng = size();
// RrPolygonList r = new RrPolygonList();
// for (int i = 0; i < leng; i++)
// r.add(polygon(i).offset(d));
// return r;
// }
/**
* Hatch a polygon list parallel to line l0 with index gap
* Returning a polygon as the result with flag values f
* @param l0
* @param gap The size of the gap between hatching strokes
* @param fg
* @param fs
* @return
*/
public RrPolygon hatch(RrLine l0, double gap, int fg, int fs)
{
RrBox big = box.scale(1.1);
double d = Math.sqrt(big.d_2());
RrPolygon r = new RrPolygon();
Rr2Point orth = new Rr2Point(-l0.direction().y(), l0.direction().x());
orth.norm();
int quad = (int)(2*Math.atan2(orth.y(), orth.x())/Math.PI);
Rr2Point org;
switch(quad)
{
case 0:
org = big.sw();
break;
case 1:
org = big.se();
break;
case 2:
org = big.ne();
break;
case 3:
org = big.nw();
break;
default:
System.err.println("RrPolygon hatch(): The atan2 function doesn't seem to work...");
org = big.sw();
}
double g = 0;
orth = Rr2Point.mul(orth, gap);
RrLine hatcher = new RrLine(org, Rr2Point.add(org, l0.direction()));
while (g < d)
{
hatcher = hatcher.neg();
List t_vals = pl_intersect(hatcher);
if (t_vals.size() > 0)
{
java.util.Collections.sort(t_vals);
r.add(RrPolygon.rr_t_polygon(t_vals, hatcher, fg, fs));
}
hatcher = hatcher.add(orth);
g = g + gap;
}
r.flags.set(0, new Integer(0));
return r;
}
}
| true | true | private RrCSG toCSGRecursive(List a, int level, boolean closed)
{
System.out.println("toCSGRecursive() - " + a.size());
flagSet(a, level);
level++;
List ch = convexHull(a);
boolean onePol = flagSet(ch, level);
RrCSG hull;
if(!onePol)
{
RrPolygonList op = outerPols(ch);
hull = RrCSG.nothing();
for(int i = 0; i < op.size(); i++)
{
RrPolygonList pgl = new RrPolygonList();
pgl.add(op.polygon(i));
List all = pgl.allPoints();
hull = RrCSG.union(hull, pgl.toCSGRecursive(all, level - 1, true));
}
}else
{
if(level%2 == 1)
hull = RrCSG.universe();
else
hull = RrCSG.nothing();
}
// First deal with all the polygons with no points on the hull
// (i.e. they are completely inside).
if(closed)
{
RrPolygonList completePols = getComplete(a, level);
if(completePols != null)
{
List all = completePols.allPoints();
if(level%2 == 1)
hull = RrCSG.intersection(hull,
completePols.toCSGRecursive(all, level, true));
else
hull = RrCSG.union(hull,
completePols.toCSGRecursive(all, level, true));
}
}
// Set-theoretically combine all the real edges on the convex hull
int i, oldi, flag, oldFlag, start;
RrPolygon pg, oldPg;
if(closed)
{
oldi = a.size() - 1;
start = 0;
} else
{
oldi = 0;
start = 1;
}
for(i = start; i < a.size(); i++)
{
oldFlag = listFlag(oldi, a);
oldPg = listPolygon(oldi, a);
flag = listFlag(i, a);
pg = listPolygon(i, a);
if(oldFlag == level && flag == level && pg == oldPg)
{
RrHalfPlane hp = new RrHalfPlane(listPoint(oldi, a), listPoint(i, a));
if(level%2 == 1)
hull = RrCSG.intersection(hull, new RrCSG(hp));
else
hull = RrCSG.union(hull, new RrCSG(hp));
}
oldi = i;
}
// Finally deal with the sections on polygons that form the hull that
// are not themselves on the hull.
List section = polSection(a, level);
while(section != null)
{
if(level%2 == 1)
hull = RrCSG.intersection(hull,
toCSGRecursive(section, level, false));
else
hull = RrCSG.union(hull,
toCSGRecursive(section, level, false));
section = polSection(a, level);
}
return hull;
}
| private RrCSG toCSGRecursive(List a, int level, boolean closed)
{
System.out.println("toCSGRecursive() - " + a.size());
flagSet(a, level);
level++;
List ch = convexHull(a);
boolean onePol = flagSet(ch, level);
RrCSG hull;
if(!onePol)
{
RrPolygonList op = outerPols(ch);
hull = RrCSG.nothing();
for(int i = 0; i < op.size(); i++)
{
RrPolygonList pgl = new RrPolygonList();
pgl.add(op.polygon(i));
List all = pgl.allPoints();
hull = RrCSG.union(hull, pgl.toCSGRecursive(all, level - 1, true));
}
// remove polygon from a!!
}else
{
if(level%2 == 1)
hull = RrCSG.universe();
else
hull = RrCSG.nothing();
}
// First deal with all the polygons with no points on the hull
// (i.e. they are completely inside).
if(closed)
{
RrPolygonList completePols = getComplete(a, level);
if(completePols != null)
{
List all = completePols.allPoints();
if(level%2 == 1)
hull = RrCSG.intersection(hull,
completePols.toCSGRecursive(all, level, true));
else
hull = RrCSG.union(hull,
completePols.toCSGRecursive(all, level, true));
}
}
// Set-theoretically combine all the real edges on the convex hull
int i, oldi, flag, oldFlag, start;
RrPolygon pg, oldPg;
if(closed)
{
oldi = a.size() - 1;
start = 0;
} else
{
oldi = 0;
start = 1;
}
for(i = start; i < a.size(); i++)
{
oldFlag = listFlag(oldi, a);
oldPg = listPolygon(oldi, a);
flag = listFlag(i, a);
pg = listPolygon(i, a);
if(oldFlag == level && flag == level && pg == oldPg)
{
RrHalfPlane hp = new RrHalfPlane(listPoint(oldi, a), listPoint(i, a));
if(level%2 == 1)
hull = RrCSG.intersection(hull, new RrCSG(hp));
else
hull = RrCSG.union(hull, new RrCSG(hp));
}
oldi = i;
}
// Finally deal with the sections on polygons that form the hull that
// are not themselves on the hull.
List section = polSection(a, level);
while(section != null)
{
if(level%2 == 1)
hull = RrCSG.intersection(hull,
toCSGRecursive(section, level, false));
else
hull = RrCSG.union(hull,
toCSGRecursive(section, level, false));
section = polSection(a, level);
}
return hull;
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
index 9cab40dd6..90804fb30 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
@@ -1,199 +1,194 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui.tags;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.core.util.Assert;
import org.eclipse.team.internal.ccvs.ui.*;
import org.eclipse.team.internal.ui.PixelConverter;
import org.eclipse.team.internal.ui.SWTUtils;
import org.eclipse.team.internal.ui.dialogs.DialogArea;
import org.eclipse.ui.PlatformUI;
/**
* An area that displays the Refresh and Configure Tags buttons
*/
public class TagRefreshButtonArea extends DialogArea {
private TagSource tagSource;
private final Shell shell;
private Button refreshButton;
private IRunnableContext context;
private Label fMessageLabel;
private final Listener addDateTagListener;
public TagRefreshButtonArea(Shell shell, TagSource tagSource, Listener addDateTagListener) {
this.addDateTagListener = addDateTagListener;
Assert.isNotNull(shell);
Assert.isNotNull(tagSource);
this.shell = shell;
this.tagSource = tagSource;
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ui.dialogs.DialogArea#createArea(org.eclipse.swt.widgets.Composite)
*/
public void createArea(Composite parent) {
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(4, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
- try {
- fMessageLabel.setLayoutData(SWTUtils.createGridData(converter.convertWidthInCharsToPixels(CVSUIMessages.TagRefreshButtonArea_6.length()), SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false));
- } catch (NullPointerException e) {
- // The message may be missing so just continue
- }
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (CVSUIMessages.TagConfigurationDialog_20);
final Button configureTagsButton = new Button(buttonComp, SWT.PUSH);
configureTagsButton.setText (CVSUIMessages.TagConfigurationDialog_21);
Button addDateTagButton = null;
int buttonWidth;
if (addDateTagListener != null) {
addDateTagButton = new Button(buttonComp, SWT.PUSH);
addDateTagButton.setText (CVSUIMessages.TagConfigurationDialog_AddDateTag);
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addDateTagButton, configureTagsButton, refreshButton });
addDateTagButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addDateTagButton.addListener(SWT.Selection, addDateTagListener);
} else {
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { configureTagsButton, refreshButton });
}
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
configureTagsButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
configureTagsButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
PlatformUI.getWorkbench().getHelpSystem().setHelp(configureTagsButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
public void refresh(final boolean background) {
try {
getRunnableContext().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
setBusy(true);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
fMessageLabel.setText(CVSUIMessages.TagRefreshButtonArea_6); //$NON-NLS-1$
}
});
monitor.beginTask(CVSUIMessages.TagRefreshButtonArea_5, 100); //$NON-NLS-1$
final CVSTag[] tags = tagSource.refresh(false, Policy.subMonitorFor(monitor, 70));
Display.getDefault().asyncExec(new Runnable() {
public void run() {
fMessageLabel.setText(background && tags.length == 0 ? CVSUIMessages.TagRefreshButtonArea_7 : ""); //$NON-NLS-1$ //$NON-NLS-2$
}
});
if (!background && tags.length == 0 && promptForBestEffort()) {
tagSource.refresh(true, Policy.subMonitorFor(monitor, 30));
}
} catch (TeamException e) {
throw new InvocationTargetException(e);
} finally {
setBusy(false);
monitor.done();
}
}
});
} catch (InterruptedException e) {
// operation cancelled
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(shell, CVSUIMessages.TagConfigurationDialog_14, null, e); //$NON-NLS-1$
}
}
private void setBusy(final boolean busy) {
if (shell != null && !shell.isDisposed())
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
refreshButton.setEnabled(!busy);
}
});
}
private boolean promptForBestEffort() {
final boolean[] prompt = new boolean[] { false };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
MessageDialog dialog = new MessageDialog(shell, CVSUIMessages.TagRefreshButtonArea_0, null, //$NON-NLS-1$
getNoTagsFoundMessage(),
MessageDialog.INFORMATION,
new String[] {
CVSUIMessages.TagRefreshButtonArea_1, //$NON-NLS-1$
CVSUIMessages.TagRefreshButtonArea_2, //$NON-NLS-1$
CVSUIMessages.TagRefreshButtonArea_3
}, 1);
int code = dialog.open();
if (code == 0) {
prompt[0] = true;
} else if (code == 1) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
}
});
return prompt[0];
}
private String getNoTagsFoundMessage() {
return NLS.bind(CVSUIMessages.TagRefreshButtonArea_4, new String[] { tagSource.getShortDescription() }); //$NON-NLS-1$
}
public void setTagSource(TagSource tagSource) {
Assert.isNotNull(tagSource);
this.tagSource = tagSource;
}
public IRunnableContext getRunnableContext() {
if (context == null)
return PlatformUI.getWorkbench().getProgressService();
return context;
}
public void setRunnableContext(IRunnableContext context) {
this.context = context;
}
}
| true | true | public void createArea(Composite parent) {
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(4, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
try {
fMessageLabel.setLayoutData(SWTUtils.createGridData(converter.convertWidthInCharsToPixels(CVSUIMessages.TagRefreshButtonArea_6.length()), SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false));
} catch (NullPointerException e) {
// The message may be missing so just continue
}
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (CVSUIMessages.TagConfigurationDialog_20);
final Button configureTagsButton = new Button(buttonComp, SWT.PUSH);
configureTagsButton.setText (CVSUIMessages.TagConfigurationDialog_21);
Button addDateTagButton = null;
int buttonWidth;
if (addDateTagListener != null) {
addDateTagButton = new Button(buttonComp, SWT.PUSH);
addDateTagButton.setText (CVSUIMessages.TagConfigurationDialog_AddDateTag);
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addDateTagButton, configureTagsButton, refreshButton });
addDateTagButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addDateTagButton.addListener(SWT.Selection, addDateTagListener);
} else {
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { configureTagsButton, refreshButton });
}
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
configureTagsButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
configureTagsButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
PlatformUI.getWorkbench().getHelpSystem().setHelp(configureTagsButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
| public void createArea(Composite parent) {
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(4, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (CVSUIMessages.TagConfigurationDialog_20);
final Button configureTagsButton = new Button(buttonComp, SWT.PUSH);
configureTagsButton.setText (CVSUIMessages.TagConfigurationDialog_21);
Button addDateTagButton = null;
int buttonWidth;
if (addDateTagListener != null) {
addDateTagButton = new Button(buttonComp, SWT.PUSH);
addDateTagButton.setText (CVSUIMessages.TagConfigurationDialog_AddDateTag);
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addDateTagButton, configureTagsButton, refreshButton });
addDateTagButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addDateTagButton.addListener(SWT.Selection, addDateTagListener);
} else {
Dialog.applyDialogFont(buttonComp);
buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { configureTagsButton, refreshButton });
}
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
configureTagsButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
configureTagsButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
PlatformUI.getWorkbench().getHelpSystem().setHelp(configureTagsButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
|
diff --git a/src/org/apache/fop/tools/anttasks/Manifest.java b/src/org/apache/fop/tools/anttasks/Manifest.java
index 3e285a7be..f0e7c68a0 100644
--- a/src/org/apache/fop/tools/anttasks/Manifest.java
+++ b/src/org/apache/fop/tools/anttasks/Manifest.java
@@ -1,239 +1,239 @@
/*
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
package org.apache.fop.tools.anttasks;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.net.InetAddress;
import java.util.Date;
import java.util.Properties;
/**
* Creates a manifest file for packing into a jar.
* <P>
* Attributes are as follows:
* <dl>
* <dt>file</dt> <dd>the manifest file to write out to (required)</dd>
* <dt>overwrite</dt> <dd>if set to yes or true, overwrite the given
* manifest file. Default is no</dd>
* <dt>version</dt> <dd>manifest version. Defaults to "1.0"</dd>
* <dt>spectitle</dt> <dd>the specification title</dd>
* <dt>specversion</dt> <dd>the specification version</dd>
* <dt>specvendor</dt> <dd>the specification vendor</dd>
* <dt>impltitle</dt> <dd>the implementation title</dd>
* <dt>implversion</dt> <dd>the implementation version.</dd>
* <dt>implvendor</dt> <dd>the implementation vendor</dd>
* <dt>mainclass</dt> <dd>the class to run when java -jar is invoked</dd>
* <dt>classpath</dt> <dd>the classpath to use when java -jar is invoked</dd>
* <dt>createdby</dt> <dd>the string to set the Created-By field to</dd>
* <dt>buildid</dt> <dd>A build identifier. Defaults to a build identifier
* containing <tt>date + " ("+username+"@"+hostname+" ["+os+" "+version+" "+arch+"]</tt> </dd>
* </dl>
*
* @author Kelly A. Campbell
*/
public class Manifest extends Task
{
public static final String MANIFEST_VERSION = "Manifest-Version: ";
public static final String CREATED_BY = "Created-By: ";
public static final String REQUIRED_VERSION = "Required-Version: ";
public static final String SPECIFICATION_TITLE = "Specification-Title: ";
public static final String SPECIFICATION_VERSION = "Specification-Version: ";
public static final String SPECIFICATION_VENDOR = "Specification-Vendor: ";
public static final String IMPL_TITLE = "Implementation-Title: ";
public static final String IMPL_VERSION = "Implementation-Version: ";
public static final String IMPL_VENDOR = "Implementation-Vendor: ";
public static final String BUILD_ID = "Build-ID: ";
public static final String MAIN_CLASS = "Main-Class: ";
public static final String CLASS_PATH = "Class-Path: ";
private String _manifestVersion = "1.0";
private String _spectitle;
private String _specvers;
private String _specvend;
private String _impltitle;
private String _implvers;
private String _implvend;
private String _mainclass;
private String _classpath;
private String _createdby;
private String _buildid;
private String _manifestFilename;
private Boolean _overwrite = Boolean.FALSE;
public void setFile(String s)
{
_manifestFilename = s;
}
public void setOverwrite(Boolean b)
{
_overwrite = b;
}
public void setSpectitle(String s)
{
_spectitle = s;
}
public void setSpecversion(String s)
{
_specvers = s;
}
public void setSpecvendor(String s)
{
_specvend = s;
}
public void setImpltitle(String s)
{
_impltitle = s;
}
public void setImplversion(String s)
{
_implvers = s;
}
public void setImplvendor(String s)
{
_implvend = s;
}
public void setMainclass(String s)
{
_mainclass = s;
}
public void setClasspath(String s)
{
_classpath = s;
}
public void setCreatedby(String s)
{
_createdby = s;
}
public void setBuildid(String s)
{
_buildid = s;
}
/**
* Main task method which runs this task and creates the manifest file.
* @exception BuildException if one of the required attributes isn't set
*/
public void execute ()
throws BuildException
{
// System.out.println("Executing manifest task");
PrintWriter out;
try {
if (_manifestFilename != null) {
// open the file for writing
File f = new File(_manifestFilename);
if (f.exists()) {
if (_overwrite.booleanValue()) {
f.delete();
}
else {
throw new BuildException("Will not overwrite existing file: "+_manifestFilename+". Use overwrite='yes' if you wish to overwrite the file.");
}
}
System.out.println("creating "+f);
- f.createNewFile();
+ //jdk1.2 -- f.createNewFile();
out = new PrintWriter(new FileOutputStream(f));
}
else {
throw new BuildException("Manifest task requires a 'file' attribute");
}
}
catch (IOException ex) {
throw new BuildException(ex);
}
// setup the implementation versionn (buildID)
if (_buildid == null || _buildid.trim().equals("")) {
_buildid = createBuildID();
}
if (_createdby == null || _createdby.trim().equals("")) {
_createdby = getCreator();
}
print(out, MANIFEST_VERSION, _manifestVersion);
print(out, CREATED_BY, _createdby);
print(out, SPECIFICATION_TITLE, _spectitle);
print(out, SPECIFICATION_VERSION, _specvers);
print(out, SPECIFICATION_VENDOR, _specvend);
print(out, IMPL_TITLE, _impltitle);
print(out, IMPL_VERSION, _implvers);
print(out, IMPL_VENDOR, _implvend);
print(out, BUILD_ID, _buildid);
print(out, MAIN_CLASS, _mainclass);
print(out, CLASS_PATH, _classpath);
out.flush();
out.close();
}
protected void print(PrintWriter out, String header, String value)
{
if (value != null && !value.trim().equals("")) {
out.println(header+value);
// System.out.println("manifest: "+header+value);
}
}
private static String createBuildID()
{
Date d = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd-HHmmss-z");
String date = f.format(d);
String hostname, username, os, version, arch;
try {
hostname = InetAddress.getLocalHost().getHostName();
}
catch (Exception ex) {
hostname = "unknown";
}
username = System.getProperty("user.name");
os = System.getProperty("os.name");
version = System.getProperty("os.version");
arch = System.getProperty("os.arch");
String buildid = date + " ("+username+"@"+hostname+" ["+os+" "+version+" "+arch+"])";
return buildid;
}
private static String getCreator()
{
try {
Properties props = new Properties();
InputStream in = org.apache.tools.ant.Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
if (in != null) {
props.load(in);
in.close();
return "Ant "+props.getProperty("VERSION");
}
else {
return null;
}
}
catch (IOException ex) {
return null;
}
}
}
| true | true | public void execute ()
throws BuildException
{
// System.out.println("Executing manifest task");
PrintWriter out;
try {
if (_manifestFilename != null) {
// open the file for writing
File f = new File(_manifestFilename);
if (f.exists()) {
if (_overwrite.booleanValue()) {
f.delete();
}
else {
throw new BuildException("Will not overwrite existing file: "+_manifestFilename+". Use overwrite='yes' if you wish to overwrite the file.");
}
}
System.out.println("creating "+f);
f.createNewFile();
out = new PrintWriter(new FileOutputStream(f));
}
else {
throw new BuildException("Manifest task requires a 'file' attribute");
}
}
catch (IOException ex) {
throw new BuildException(ex);
}
// setup the implementation versionn (buildID)
if (_buildid == null || _buildid.trim().equals("")) {
_buildid = createBuildID();
}
if (_createdby == null || _createdby.trim().equals("")) {
_createdby = getCreator();
}
print(out, MANIFEST_VERSION, _manifestVersion);
print(out, CREATED_BY, _createdby);
print(out, SPECIFICATION_TITLE, _spectitle);
print(out, SPECIFICATION_VERSION, _specvers);
print(out, SPECIFICATION_VENDOR, _specvend);
print(out, IMPL_TITLE, _impltitle);
print(out, IMPL_VERSION, _implvers);
print(out, IMPL_VENDOR, _implvend);
print(out, BUILD_ID, _buildid);
print(out, MAIN_CLASS, _mainclass);
print(out, CLASS_PATH, _classpath);
out.flush();
out.close();
}
| public void execute ()
throws BuildException
{
// System.out.println("Executing manifest task");
PrintWriter out;
try {
if (_manifestFilename != null) {
// open the file for writing
File f = new File(_manifestFilename);
if (f.exists()) {
if (_overwrite.booleanValue()) {
f.delete();
}
else {
throw new BuildException("Will not overwrite existing file: "+_manifestFilename+". Use overwrite='yes' if you wish to overwrite the file.");
}
}
System.out.println("creating "+f);
//jdk1.2 -- f.createNewFile();
out = new PrintWriter(new FileOutputStream(f));
}
else {
throw new BuildException("Manifest task requires a 'file' attribute");
}
}
catch (IOException ex) {
throw new BuildException(ex);
}
// setup the implementation versionn (buildID)
if (_buildid == null || _buildid.trim().equals("")) {
_buildid = createBuildID();
}
if (_createdby == null || _createdby.trim().equals("")) {
_createdby = getCreator();
}
print(out, MANIFEST_VERSION, _manifestVersion);
print(out, CREATED_BY, _createdby);
print(out, SPECIFICATION_TITLE, _spectitle);
print(out, SPECIFICATION_VERSION, _specvers);
print(out, SPECIFICATION_VENDOR, _specvend);
print(out, IMPL_TITLE, _impltitle);
print(out, IMPL_VERSION, _implvers);
print(out, IMPL_VENDOR, _implvend);
print(out, BUILD_ID, _buildid);
print(out, MAIN_CLASS, _mainclass);
print(out, CLASS_PATH, _classpath);
out.flush();
out.close();
}
|
diff --git a/ScrollingScoreBoardAnnouncer/src/de/MiniDigger/ScrollingScoreBoardAnnouncer/ScrollingScoreBoardAnnoucerCommands.java b/ScrollingScoreBoardAnnouncer/src/de/MiniDigger/ScrollingScoreBoardAnnouncer/ScrollingScoreBoardAnnoucerCommands.java
index c7cbe52..9d8e368 100644
--- a/ScrollingScoreBoardAnnouncer/src/de/MiniDigger/ScrollingScoreBoardAnnouncer/ScrollingScoreBoardAnnoucerCommands.java
+++ b/ScrollingScoreBoardAnnouncer/src/de/MiniDigger/ScrollingScoreBoardAnnouncer/ScrollingScoreBoardAnnoucerCommands.java
@@ -1,233 +1,233 @@
package de.MiniDigger.ScrollingScoreBoardAnnouncer;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.MiniDigger.ScrollingScoreBoardAnnouncer.Updater.UpdateType;
public class ScrollingScoreBoardAnnoucerCommands implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String lable,
String[] args) {
if (cmd.getName().equalsIgnoreCase("announce")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.announce")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (args.length < 3) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ "This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
} else {
ScrollingScoreBoard board = ScrollingScoreBoardAnnouncer.handler
.get(args[0]);
if (board == null) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
}
int slot = 0;
try {
slot = Integer.parseInt(args[1]);
} catch (Exception e) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED + " The slot has to be a number!");
return true;
}
String msg = "";
for (int i = 2; i < args.length; i++) {
msg += " " + args[i];
}
board.annonce(msg, slot);
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN + " Text of board " + args[0]
+ " in slot " + args[1] + " was changed to " + msg);
}
return true;
} else if (cmd.getName().equalsIgnoreCase(
ScrollingScoreBoardAnnouncer.name)) {
if (args.length != 0 && args[0].equalsIgnoreCase("create")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.create")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
- if (args.length < 1) {
+ if (args.length < 2) {
sender.sendMessage(ChatColor.YELLOW
+ ScrollingScoreBoardAnnouncer.prefix
+ " Creates a new command with the name <arg1> ");
return true;
} else {
ScrollingScoreBoardAnnouncer.handler.create(args[1]);
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ "New Board created. You can edit it now");
return true;
}
} else if (args.length != 0 && args[0].equalsIgnoreCase("reload")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.reload")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
ScrollingScoreBoardAnnouncer.handler.loadAll();
ScrollingScoreBoardAnnouncer.config.load();
ScrollingScoreBoardAnnouncer.debug = ScrollingScoreBoardAnnouncer.config
.getBoolean("debug");
ScrollingScoreBoardAnnouncer.update = ScrollingScoreBoardAnnouncer.config
.getBoolean("update");
} else if (args.length != 0 && args[0].equalsIgnoreCase("update")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.update")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (ScrollingScoreBoardAnnouncer.isUpdateAvailable) {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_VERSION_CHECK, true);
// TODO Wait for curse to sync the project to get the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
case SUCCESS:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ " Plugin updated! Please reload your server!");
default:
break;
}
} else {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_DOWNLOAD, true); // TODO Wait for
// curse to
// sync the project
// to get
// the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
default:
break;
}
}
} else {
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This server is using "
+ ScrollingScoreBoardAnnouncer.name
+ " "
+ ScrollingScoreBoardAnnouncer.getInstance()
.getDescription().getVersion());
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " If you want to see more of my plugins check out http://dev.bukkit.org/profiles/MiniDigger/");
return true;
}
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String lable,
String[] args) {
if (cmd.getName().equalsIgnoreCase("announce")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.announce")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (args.length < 3) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ "This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
} else {
ScrollingScoreBoard board = ScrollingScoreBoardAnnouncer.handler
.get(args[0]);
if (board == null) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
}
int slot = 0;
try {
slot = Integer.parseInt(args[1]);
} catch (Exception e) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED + " The slot has to be a number!");
return true;
}
String msg = "";
for (int i = 2; i < args.length; i++) {
msg += " " + args[i];
}
board.annonce(msg, slot);
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN + " Text of board " + args[0]
+ " in slot " + args[1] + " was changed to " + msg);
}
return true;
} else if (cmd.getName().equalsIgnoreCase(
ScrollingScoreBoardAnnouncer.name)) {
if (args.length != 0 && args[0].equalsIgnoreCase("create")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.create")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (args.length < 1) {
sender.sendMessage(ChatColor.YELLOW
+ ScrollingScoreBoardAnnouncer.prefix
+ " Creates a new command with the name <arg1> ");
return true;
} else {
ScrollingScoreBoardAnnouncer.handler.create(args[1]);
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ "New Board created. You can edit it now");
return true;
}
} else if (args.length != 0 && args[0].equalsIgnoreCase("reload")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.reload")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
ScrollingScoreBoardAnnouncer.handler.loadAll();
ScrollingScoreBoardAnnouncer.config.load();
ScrollingScoreBoardAnnouncer.debug = ScrollingScoreBoardAnnouncer.config
.getBoolean("debug");
ScrollingScoreBoardAnnouncer.update = ScrollingScoreBoardAnnouncer.config
.getBoolean("update");
} else if (args.length != 0 && args[0].equalsIgnoreCase("update")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.update")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (ScrollingScoreBoardAnnouncer.isUpdateAvailable) {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_VERSION_CHECK, true);
// TODO Wait for curse to sync the project to get the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
case SUCCESS:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ " Plugin updated! Please reload your server!");
default:
break;
}
} else {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_DOWNLOAD, true); // TODO Wait for
// curse to
// sync the project
// to get
// the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
default:
break;
}
}
} else {
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This server is using "
+ ScrollingScoreBoardAnnouncer.name
+ " "
+ ScrollingScoreBoardAnnouncer.getInstance()
.getDescription().getVersion());
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " If you want to see more of my plugins check out http://dev.bukkit.org/profiles/MiniDigger/");
return true;
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String lable,
String[] args) {
if (cmd.getName().equalsIgnoreCase("announce")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.announce")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (args.length < 3) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ "This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
} else {
ScrollingScoreBoard board = ScrollingScoreBoardAnnouncer.handler
.get(args[0]);
if (board == null) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This command allows you to change the displayed text of a scoreboard");
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " Usage: /announce <board> <slot> <the> <text> <you> <want> <to> <display>");
return true;
}
int slot = 0;
try {
slot = Integer.parseInt(args[1]);
} catch (Exception e) {
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED + " The slot has to be a number!");
return true;
}
String msg = "";
for (int i = 2; i < args.length; i++) {
msg += " " + args[i];
}
board.annonce(msg, slot);
sender.sendMessage(ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN + " Text of board " + args[0]
+ " in slot " + args[1] + " was changed to " + msg);
}
return true;
} else if (cmd.getName().equalsIgnoreCase(
ScrollingScoreBoardAnnouncer.name)) {
if (args.length != 0 && args[0].equalsIgnoreCase("create")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.create")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (args.length < 2) {
sender.sendMessage(ChatColor.YELLOW
+ ScrollingScoreBoardAnnouncer.prefix
+ " Creates a new command with the name <arg1> ");
return true;
} else {
ScrollingScoreBoardAnnouncer.handler.create(args[1]);
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ "New Board created. You can edit it now");
return true;
}
} else if (args.length != 0 && args[0].equalsIgnoreCase("reload")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.reload")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
ScrollingScoreBoardAnnouncer.handler.loadAll();
ScrollingScoreBoardAnnouncer.config.load();
ScrollingScoreBoardAnnouncer.debug = ScrollingScoreBoardAnnouncer.config
.getBoolean("debug");
ScrollingScoreBoardAnnouncer.update = ScrollingScoreBoardAnnouncer.config
.getBoolean("update");
} else if (args.length != 0 && args[0].equalsIgnoreCase("update")) {
if (sender instanceof Player
&& !ScrollingScoreBoardAnnouncer.perms.has(sender,
"ssa.update")) {
sender.sendMessage(ChatColor.RED
+ ScrollingScoreBoardAnnouncer.prefix
+ " You dont have permmsions to use that command!");
return true;
}
if (ScrollingScoreBoardAnnouncer.isUpdateAvailable) {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_VERSION_CHECK, true);
// TODO Wait for curse to sync the project to get the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
case SUCCESS:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.GREEN
+ " Plugin updated! Please reload your server!");
default:
break;
}
} else {
Updater u = new Updater(
ScrollingScoreBoardAnnouncer.getInstance(), 1,
ScrollingScoreBoardAnnouncer.file,
UpdateType.NO_DOWNLOAD, true); // TODO Wait for
// curse to
// sync the project
// to get
// the id :D
switch (u.getResult()) {
case DISABLED:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " You have disabled the updater in its config. I cant check for Updates :(");
break;
case FAIL_APIKEY:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Invalid API Key");
break;
case FAIL_BADID:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Bad ID");
break;
case FAIL_DBO:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.RED
+ " Could not check for updates: Could not reach DBO");
break;
case UPDATE_AVAILABLE:
ScrollingScoreBoardAnnouncer.isUpdateAvailable = true;
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ " There is an Update available. Use '/ssa update' to update the plugin");
break;
case NO_UPDATE:
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " The plugin is up-to-date");
break;
default:
break;
}
}
} else {
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " This server is using "
+ ScrollingScoreBoardAnnouncer.name
+ " "
+ ScrollingScoreBoardAnnouncer.getInstance()
.getDescription().getVersion());
sender.sendMessage(ChatColor.GOLD
+ ScrollingScoreBoardAnnouncer.prefix
+ ChatColor.YELLOW
+ " If you want to see more of my plugins check out http://dev.bukkit.org/profiles/MiniDigger/");
return true;
}
}
return true;
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
index 96363c624..c2b186c2c 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
@@ -1,880 +1,887 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.core.axis2;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.util.PolicyInfo;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
/**
* <proxy-service name="string" [transports="(http |https |jms )+|all"] [trace="enable|disable"]>
* <description>..</description>?
* <target [inSequence="name"] [outSequence="name"] [faultSequence="name"] [endpoint="name"]>
* <endpoint>...</endpoint>
* <inSequence>...</inSequence>
* <outSequence>...</outSequence>
* <faultSequence>...</faultSequence>
* </target>?
* <publishWSDL uri=".." key="string">
* <wsdl:definition>...</wsdl:definition>?
* <wsdl20:description>...</wsdl20:description>?
* <resource location="..." key="..."/>*
* </publishWSDL>?
* <enableSec/>?
* <enableRM/>?
* <policy key="string" [type=("in" |"out")] [operationName="string"]
* [operationNamespace="string"]>?
* // optional service parameters
* <parameter name="string">
* text | xml
* </parameter>?
* </proxy-service>
*/
public class ProxyService {
private static final Log log = LogFactory.getLog(ProxyService.class);
private static final Log trace = LogFactory.getLog(SynapseConstants.TRACE_LOGGER);
private final Log serviceLog;
/**
* The name of the proxy service
*/
private String name;
/**
* The proxy service description. This could be optional informative text about the service
*/
private String description;
/**
* The transport/s over which this service should be exposed, or defaults to all available
*/
private ArrayList transports;
/**
* Server names for which this service should be exposed
*/
private List pinnedServers = new ArrayList();
/**
* The target endpoint key
*/
private String targetEndpoint = null;
/**
* The target inSequence key
*/
private String targetInSequence = null;
/**
* The target outSequence key
*/
private String targetOutSequence = null;
/**
* The target faultSequence key
*/
private String targetFaultSequence = null;
/**
* The inlined definition of the target endpoint, if defined
*/
private Endpoint targetInLineEndpoint = null;
/**
* The inlined definition of the target in-sequence, if defined
*/
private SequenceMediator targetInLineInSequence = null;
/**
* The inlined definition of the target out-sequence, if defined
*/
private SequenceMediator targetInLineOutSequence = null;
/**
* The inlined definition of the target fault-sequence, if defined
*/
private SequenceMediator targetInLineFaultSequence = null;
/**
* A list of any service parameters (e.g. JMS parameters etc)
*/
private Map<String, Object> parameters = new HashMap<String, Object>();
/**
* The key for the base WSDL
*/
private String wsdlKey;
/**
* The URI for the base WSDL, if defined as a URL
*/
private URI wsdlURI;
/**
* The inlined representation of the service WSDL, if defined inline
*/
private Object inLineWSDL;
/**
* A ResourceMap object allowing to locate artifacts (WSDL and XSD) imported
* by the service WSDL to be located in the registry.
*/
private ResourceMap resourceMap;
/**
* Policies to be set to the service, this can include service level, operation level,
* message level or hybrid level policies as well.
*/
private List<PolicyInfo> policies = new ArrayList<PolicyInfo>();
/**
* The keys for any supplied policies that would apply at the service level
*/
private List<String> serviceLevelPolicies = new ArrayList<String>();
/**
* The keys for any supplied policies that would apply at the in message level
*/
private List<String> inMessagePolicies = new ArrayList<String>();
/**
* The keys for any supplied policies that would apply at the out message level
*/
private List<String> outMessagePolicies = new ArrayList<String>();
/**
* Should WS RM be engaged on this service
*/
private boolean wsRMEnabled = false;
/**
* Should WS Sec be engaged on this service
*/
private boolean wsSecEnabled = false;
/**
* Should this service be started by default on initialization?
*/
private boolean startOnLoad = true;
/**
* Is this service running now?
*/
private boolean running = false;
public static final String ALL_TRANSPORTS = "all";
/**
* To decide to whether statistics should have collected or not
*/
private int statisticsState = SynapseConstants.STATISTICS_UNSET;
/**
* The variable that indicate tracing on or off for the current mediator
*/
protected int traceState = SynapseConstants.TRACING_UNSET;
/**
* Constructor
*
* @param name the name of the Proxy service
*/
public ProxyService(String name) {
this.name = name;
serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
}
/**
* Build the underlying Axis2 service from the Proxy service definition
*
* @param synCfg the Synapse configuration
* @param axisCfg the Axis2 configuration
* @return the Axis2 service for the Proxy
*/
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
+ boolean wsdlFound = false;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
+ wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
+ wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
OMNode node = SynapseConfigUtils.getOMElementFromURL(url.toString());
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
+ wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
handleException("Error reading from wsdl URI", e);
}
+ } else {
+ // this is for POX... create a dummy service and an operation for which
+ // our SynapseDispatcher will properly dispatch to
+ if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
+ proxyService = new AxisService();
+ AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
+ proxyService.addOperation(mediateOperation);
}
// if a WSDL was found
- if (wsdlElement != null) {
+ if (wsdlFound && wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
boolean isWSDL11 = false;
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
isWSDL11 = true;
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
System.getProperty(SynapseConstants.SYNAPSE_HOME));
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else {
- // this is for POX... create a dummy service and an operation for which
- // our SynapseDispatcher will properly dispatch to
- if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
- proxyService = new AxisService();
- AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
- proxyService.addOperation(mediateOperation);
+ handleException("Couldn't build the proxy service : " + name
+ + ". Unable to locate the specified WSDL to build the service");
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_SERVICE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicyInclude().addPolicyElement(PolicyInclude.AXIS_OPERATION_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicyInclude().addPolicyElement(
PolicyInclude.MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SANDESHA2_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RAMPART_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
private Policy getPolicyFromKey(String key, SynapseConfiguration synCfg) {
return PolicyEngine.getPolicy(SynapseConfigUtils.getStreamSource(
synCfg.getEntry(key)).getInputStream());
}
/**
* Start the proxy service
* @param synCfg the synapse configuration
*/
public void start(SynapseConfiguration synCfg) {
AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
if (axisConfig != null) {
Parameter param = axisConfig.getParameter(SynapseConstants.SYNAPSE_ENV);
if (param != null && param.getValue() instanceof SynapseEnvironment) {
SynapseEnvironment env = (SynapseEnvironment) param.getValue();
if (targetInLineInSequence != null) {
targetInLineInSequence.init(env);
}
if (targetInLineOutSequence != null) {
targetInLineOutSequence.init(env);
}
if (targetInLineFaultSequence != null) {
targetInLineFaultSequence.init(env);
}
} else {
auditWarn("Unable to find the SynapseEnvironment. " +
"Components of the proxy service may not be initialized");
}
axisConfig.getServiceForActivation(this.getName()).setActive(true);
this.setRunning(true);
auditInfo("Started the proxy service : " + name);
} else {
auditWarn("Unable to start proxy service : " + name +
". Couldn't access Axis configuration");
}
}
/**
* Stop the proxy service
* @param synCfg the synapse configuration
*/
public void stop(SynapseConfiguration synCfg) {
AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
if (axisConfig != null) {
if (targetInLineInSequence != null) {
targetInLineInSequence.destroy();
}
if (targetInLineOutSequence != null) {
targetInLineOutSequence.destroy();
}
if (targetInLineFaultSequence != null) {
targetInLineFaultSequence.destroy();
}
try {
AxisService as = axisConfig.getService(this.getName());
if (as != null) {
as.setActive(false);
}
this.setRunning(false);
auditInfo("Started the proxy service : " + name);
} catch (AxisFault axisFault) {
handleException("Error stopping the proxy service : " + name, axisFault);
}
} else {
auditWarn("Unable to stop proxy service : " + name +
". Couldn't access Axis configuration");
}
}
private void handleException(String msg) {
serviceLog.error(msg);
log.error(msg);
if (trace()) trace.error(msg);
throw new SynapseException(msg);
}
private void handleException(String msg, Exception e) {
serviceLog.error(msg);
log.error(msg, e);
if (trace()) trace.error(msg + " :: " + e.getMessage());
throw new SynapseException(msg, e);
}
/**
* Write to the general log, as well as any service specific logs the audit message at INFO
* @param message the INFO level audit message
*/
private void auditInfo(String message) {
log.info(message);
serviceLog.info(message);
if (trace()) {
trace.info(message);
}
}
/**
* Write to the general log, as well as any service specific logs the audit message at WARN
* @param message the WARN level audit message
*/
private void auditWarn(String message) {
log.warn(message);
serviceLog.warn(message);
if (trace()) {
trace.warn(message);
}
}
/**
* Return true if tracing should be enabled
* @return true if tracing is enabled for this service
*/
private boolean trace() {
return traceState == SynapseConstants.TRACING_ON;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList getTransports() {
return transports;
}
public void addParameter(String name, Object value) {
parameters.put(name, value);
}
public Map<String, Object> getParameterMap() {
return this.parameters;
}
public void setTransports(ArrayList transports) {
this.transports = transports;
}
public String getTargetEndpoint() {
return targetEndpoint;
}
public void setTargetEndpoint(String targetEndpoint) {
this.targetEndpoint = targetEndpoint;
}
public String getTargetInSequence() {
return targetInSequence;
}
public void setTargetInSequence(String targetInSequence) {
this.targetInSequence = targetInSequence;
}
public String getTargetOutSequence() {
return targetOutSequence;
}
public void setTargetOutSequence(String targetOutSequence) {
this.targetOutSequence = targetOutSequence;
}
public String getWSDLKey() {
return wsdlKey;
}
public void setWSDLKey(String wsdlKey) {
this.wsdlKey = wsdlKey;
}
public List<String> getServiceLevelPolicies() {
return serviceLevelPolicies;
}
public void addServiceLevelPolicy(String serviceLevelPolicy) {
this.serviceLevelPolicies.add(serviceLevelPolicy);
}
public boolean isWsRMEnabled() {
return wsRMEnabled;
}
public void setWsRMEnabled(boolean wsRMEnabled) {
this.wsRMEnabled = wsRMEnabled;
}
public boolean isWsSecEnabled() {
return wsSecEnabled;
}
public void setWsSecEnabled(boolean wsSecEnabled) {
this.wsSecEnabled = wsSecEnabled;
}
public boolean isStartOnLoad() {
return startOnLoad;
}
public void setStartOnLoad(boolean startOnLoad) {
this.startOnLoad = startOnLoad;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
/**
* To check whether statistics should have collected or not
*
* @return Returns the int value that indicate statistics is enabled or not.
*/
public int getStatisticsState() {
return statisticsState;
}
/**
* To set the statistics enable variable value
*
* @param statisticsState statistics state
*/
public void setStatisticsState(int statisticsState) {
this.statisticsState = statisticsState;
}
/**
* Returns the int value that indicate the tracing state
*
* @return Returns the int value that indicate the tracing state
*/
public int getTraceState() {
return traceState;
}
/**
* Set the tracing State variable
*
* @param traceState tracing state
*/
public void setTraceState(int traceState) {
this.traceState = traceState;
}
public String getTargetFaultSequence() {
return targetFaultSequence;
}
public void setTargetFaultSequence(String targetFaultSequence) {
this.targetFaultSequence = targetFaultSequence;
}
public Object getInLineWSDL() {
return inLineWSDL;
}
public void setInLineWSDL(Object inLineWSDL) {
this.inLineWSDL = inLineWSDL;
}
public URI getWsdlURI() {
return wsdlURI;
}
public void setWsdlURI(URI wsdlURI) {
this.wsdlURI = wsdlURI;
}
public Endpoint getTargetInLineEndpoint() {
return targetInLineEndpoint;
}
public void setTargetInLineEndpoint(Endpoint targetInLineEndpoint) {
this.targetInLineEndpoint = targetInLineEndpoint;
}
public SequenceMediator getTargetInLineInSequence() {
return targetInLineInSequence;
}
public void setTargetInLineInSequence(SequenceMediator targetInLineInSequence) {
this.targetInLineInSequence = targetInLineInSequence;
}
public SequenceMediator getTargetInLineOutSequence() {
return targetInLineOutSequence;
}
public void setTargetInLineOutSequence(SequenceMediator targetInLineOutSequence) {
this.targetInLineOutSequence = targetInLineOutSequence;
}
public SequenceMediator getTargetInLineFaultSequence() {
return targetInLineFaultSequence;
}
public void setTargetInLineFaultSequence(SequenceMediator targetInLineFaultSequence) {
this.targetInLineFaultSequence = targetInLineFaultSequence;
}
public List getPinnedServers() {
return pinnedServers;
}
public void setPinnedServers(List pinnedServers) {
this.pinnedServers = pinnedServers;
}
public ResourceMap getResourceMap() {
return resourceMap;
}
public void setResourceMap(ResourceMap resourceMap) {
this.resourceMap = resourceMap;
}
public List<String> getInMessagePolicies() {
return inMessagePolicies;
}
public void setInMessagePolicies(List<String> inMessagePolicies) {
this.inMessagePolicies = inMessagePolicies;
}
public void addInMessagePolicy(String messagePolicy) {
this.inMessagePolicies.add(messagePolicy);
}
public List<String> getOutMessagePolicies() {
return outMessagePolicies;
}
public void setOutMessagePolicies(List<String> outMessagePolicies) {
this.outMessagePolicies = outMessagePolicies;
}
public void addOutMessagePolicy(String messagePolicy) {
this.outMessagePolicies.add(messagePolicy);
}
public List<PolicyInfo> getPolicies() {
return policies;
}
public void setPolicies(List<PolicyInfo> policies) {
this.policies = policies;
}
public void addPolicyInfo(PolicyInfo pi) {
this.policies.add(pi);
}
}
| false | true | public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
OMNode node = SynapseConfigUtils.getOMElementFromURL(url.toString());
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
handleException("Error reading from wsdl URI", e);
}
}
// if a WSDL was found
if (wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
boolean isWSDL11 = false;
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
isWSDL11 = true;
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
System.getProperty(SynapseConstants.SYNAPSE_HOME));
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else {
// this is for POX... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
proxyService.addOperation(mediateOperation);
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_SERVICE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicyInclude().addPolicyElement(PolicyInclude.AXIS_OPERATION_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicyInclude().addPolicyElement(
PolicyInclude.MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SANDESHA2_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RAMPART_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
| public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
boolean wsdlFound = false;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
OMNode node = SynapseConfigUtils.getOMElementFromURL(url.toString());
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
handleException("Error reading from wsdl URI", e);
}
} else {
// this is for POX... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
proxyService.addOperation(mediateOperation);
}
// if a WSDL was found
if (wsdlFound && wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
boolean isWSDL11 = false;
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
isWSDL11 = true;
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
System.getProperty(SynapseConstants.SYNAPSE_HOME));
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else {
handleException("Couldn't build the proxy service : " + name
+ ". Unable to locate the specified WSDL to build the service");
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_SERVICE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicyInclude().addPolicyElement(PolicyInclude.AXIS_OPERATION_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicyInclude().addPolicyElement(
PolicyInclude.MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicyInclude().addPolicyElement(
PolicyInclude.AXIS_MESSAGE_POLICY,
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SANDESHA2_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RAMPART_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
|
diff --git a/vme-service/src/main/java/org/fao/fi/vme/sync2/mapping/ObjectMapping.java b/vme-service/src/main/java/org/fao/fi/vme/sync2/mapping/ObjectMapping.java
index ed321f7c..de3bb694 100644
--- a/vme-service/src/main/java/org/fao/fi/vme/sync2/mapping/ObjectMapping.java
+++ b/vme-service/src/main/java/org/fao/fi/vme/sync2/mapping/ObjectMapping.java
@@ -1,97 +1,97 @@
package org.fao.fi.vme.sync2.mapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.fao.fi.figis.devcon.FIGISDoc;
import org.fao.fi.figis.domain.ObservationDomain;
import org.fao.fi.figis.domain.ObservationXml;
import org.fao.fi.figis.domain.VmeObservationDomain;
import org.fao.fi.vme.VmeException;
import org.fao.fi.vme.domain.GeneralMeasures;
import org.fao.fi.vme.domain.Profile;
import org.fao.fi.vme.domain.SpecificMeasures;
import org.fao.fi.vme.domain.Vme;
import org.fao.fi.vme.domain.YearObject;
import org.fao.fi.vme.sync2.mapping.xml.DefaultObservationXml;
import org.fao.fi.vme.sync2.mapping.xml.FigisDocBuilder;
import org.vme.fimes.jaxb.JaxbMarshall;
/**
* Stage A: domain objects without the year dimension: Vme and Rfmo.
*
* Stage B: domain objects with the year dimension:
*
* Vme trough History, SpecificMeasures, Profile
*
* Vme-Rfmo through History, GeneralMesaures-InformationSource.
*
* Stage B has only YearObject objects.
*
* Algorithm steps: (1) Collect all YearObject objects. Generate the Figis objects per year.
*
*
*
* @author Erik van Ingen
*
*/
public class ObjectMapping {
private final YearGrouping groupie = new YearGrouping();
private final FigisDocBuilder figisDocBuilder = new FigisDocBuilder();
private final JaxbMarshall marshall = new JaxbMarshall();
public VmeObservationDomain mapVme2Figis(Vme vme) {
// precondition
if (vme.getRfmo() == null) {
throw new VmeException("Detected Vme without Rfmo");
}
// logic
Map<Integer, List<YearObject<?>>> map = groupie.collect(vme);// not processed here InformationSource, To be done
Object[] years = map.keySet().toArray();
List<ObservationDomain> odList = new ArrayList<ObservationDomain>();
// every year results in one observation in English
for (Object year : years) {
ObservationDomain od = new DefaultObservationDomain().defineDefaultObservationXml();
List<ObservationXml> observationsPerLanguage = new ArrayList<ObservationXml>();
od.setObservationsPerLanguage(observationsPerLanguage);
od.setReportingYear(year.toString());
odList.add(od);
ObservationXml xml = new DefaultObservationXml().defineDefaultObservationXml();
observationsPerLanguage.add(xml);
FIGISDoc figisDoc = new DefaultFigisDoc().defineDefaultFIGISDoc();
figisDocBuilder.vme(vme, figisDoc);
- figisDocBuilder.year(figisDoc, year);
+ figisDocBuilder.year(year, figisDoc);
// now we get all the year related objects for that vme. The observation gets filled up with the information
// for that year.
List<YearObject<?>> l = map.get(year);
for (YearObject<?> yearObject : l) {
if (yearObject instanceof SpecificMeasures) {
figisDocBuilder.specificMeasures((SpecificMeasures) yearObject, figisDoc);
}
if (yearObject instanceof VmeHistory) {
figisDocBuilder.vmeHistory((VmeHistory) yearObject, figisDoc);
}
if (yearObject instanceof RfmoHistory) {
figisDocBuilder.rfmoHistory((RfmoHistory) yearObject, figisDoc);
}
if (yearObject instanceof Profile) {
figisDocBuilder.profile((Profile) yearObject, figisDoc);
}
if (yearObject instanceof GeneralMeasures) {
figisDocBuilder.generalMeasures((GeneralMeasures) yearObject, figisDoc);
}
}
xml.setXml(marshall.marshalToString(figisDoc));
}
VmeObservationDomain vod = new VmeObservationDomain();
vod.setObservationDomainList(odList);
return vod;
}
}
| true | true | public VmeObservationDomain mapVme2Figis(Vme vme) {
// precondition
if (vme.getRfmo() == null) {
throw new VmeException("Detected Vme without Rfmo");
}
// logic
Map<Integer, List<YearObject<?>>> map = groupie.collect(vme);// not processed here InformationSource, To be done
Object[] years = map.keySet().toArray();
List<ObservationDomain> odList = new ArrayList<ObservationDomain>();
// every year results in one observation in English
for (Object year : years) {
ObservationDomain od = new DefaultObservationDomain().defineDefaultObservationXml();
List<ObservationXml> observationsPerLanguage = new ArrayList<ObservationXml>();
od.setObservationsPerLanguage(observationsPerLanguage);
od.setReportingYear(year.toString());
odList.add(od);
ObservationXml xml = new DefaultObservationXml().defineDefaultObservationXml();
observationsPerLanguage.add(xml);
FIGISDoc figisDoc = new DefaultFigisDoc().defineDefaultFIGISDoc();
figisDocBuilder.vme(vme, figisDoc);
figisDocBuilder.year(figisDoc, year);
// now we get all the year related objects for that vme. The observation gets filled up with the information
// for that year.
List<YearObject<?>> l = map.get(year);
for (YearObject<?> yearObject : l) {
if (yearObject instanceof SpecificMeasures) {
figisDocBuilder.specificMeasures((SpecificMeasures) yearObject, figisDoc);
}
if (yearObject instanceof VmeHistory) {
figisDocBuilder.vmeHistory((VmeHistory) yearObject, figisDoc);
}
if (yearObject instanceof RfmoHistory) {
figisDocBuilder.rfmoHistory((RfmoHistory) yearObject, figisDoc);
}
if (yearObject instanceof Profile) {
figisDocBuilder.profile((Profile) yearObject, figisDoc);
}
if (yearObject instanceof GeneralMeasures) {
figisDocBuilder.generalMeasures((GeneralMeasures) yearObject, figisDoc);
}
}
xml.setXml(marshall.marshalToString(figisDoc));
}
VmeObservationDomain vod = new VmeObservationDomain();
vod.setObservationDomainList(odList);
return vod;
}
| public VmeObservationDomain mapVme2Figis(Vme vme) {
// precondition
if (vme.getRfmo() == null) {
throw new VmeException("Detected Vme without Rfmo");
}
// logic
Map<Integer, List<YearObject<?>>> map = groupie.collect(vme);// not processed here InformationSource, To be done
Object[] years = map.keySet().toArray();
List<ObservationDomain> odList = new ArrayList<ObservationDomain>();
// every year results in one observation in English
for (Object year : years) {
ObservationDomain od = new DefaultObservationDomain().defineDefaultObservationXml();
List<ObservationXml> observationsPerLanguage = new ArrayList<ObservationXml>();
od.setObservationsPerLanguage(observationsPerLanguage);
od.setReportingYear(year.toString());
odList.add(od);
ObservationXml xml = new DefaultObservationXml().defineDefaultObservationXml();
observationsPerLanguage.add(xml);
FIGISDoc figisDoc = new DefaultFigisDoc().defineDefaultFIGISDoc();
figisDocBuilder.vme(vme, figisDoc);
figisDocBuilder.year(year, figisDoc);
// now we get all the year related objects for that vme. The observation gets filled up with the information
// for that year.
List<YearObject<?>> l = map.get(year);
for (YearObject<?> yearObject : l) {
if (yearObject instanceof SpecificMeasures) {
figisDocBuilder.specificMeasures((SpecificMeasures) yearObject, figisDoc);
}
if (yearObject instanceof VmeHistory) {
figisDocBuilder.vmeHistory((VmeHistory) yearObject, figisDoc);
}
if (yearObject instanceof RfmoHistory) {
figisDocBuilder.rfmoHistory((RfmoHistory) yearObject, figisDoc);
}
if (yearObject instanceof Profile) {
figisDocBuilder.profile((Profile) yearObject, figisDoc);
}
if (yearObject instanceof GeneralMeasures) {
figisDocBuilder.generalMeasures((GeneralMeasures) yearObject, figisDoc);
}
}
xml.setXml(marshall.marshalToString(figisDoc));
}
VmeObservationDomain vod = new VmeObservationDomain();
vod.setObservationDomainList(odList);
return vod;
}
|
diff --git a/payment/src/main/java/com/ning/billing/payment/core/PaymentMethodProcessor.java b/payment/src/main/java/com/ning/billing/payment/core/PaymentMethodProcessor.java
index 16faab9fc..d0f961204 100644
--- a/payment/src/main/java/com/ning/billing/payment/core/PaymentMethodProcessor.java
+++ b/payment/src/main/java/com/ning/billing/payment/core/PaymentMethodProcessor.java
@@ -1,318 +1,318 @@
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.payment.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.account.api.DefaultMutableAccountData;
import com.ning.billing.account.api.MutableAccountData;
import com.ning.billing.payment.api.DefaultPaymentMethod;
import com.ning.billing.payment.api.DefaultPaymentMethodPlugin;
import com.ning.billing.payment.api.PaymentApiException;
import com.ning.billing.payment.api.PaymentMethod;
import com.ning.billing.payment.api.PaymentMethodPlugin;
import com.ning.billing.payment.dao.PaymentDao;
import com.ning.billing.payment.dao.PaymentMethodModelDao;
import com.ning.billing.payment.plugin.api.PaymentPluginApi;
import com.ning.billing.payment.plugin.api.PaymentPluginApiException;
import com.ning.billing.payment.provider.PaymentProviderPluginRegistry;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.globallocker.GlobalLocker;
import static com.ning.billing.payment.glue.PaymentModule.PLUGIN_EXECUTOR_NAMED;
public class PaymentMethodProcessor extends ProcessorBase {
@Inject
public PaymentMethodProcessor(final PaymentProviderPluginRegistry pluginRegistry,
final AccountUserApi accountUserApi,
final Bus eventBus,
final PaymentDao paymentDao,
final GlobalLocker locker,
@Named(PLUGIN_EXECUTOR_NAMED) final ExecutorService executor) {
super(pluginRegistry, accountUserApi, eventBus, paymentDao, locker, executor);
}
public Set<String> getAvailablePlugins() {
return pluginRegistry.getRegisteredPluginNames();
}
public String initializeAccountPlugin(final String pluginName, final Account account) throws PaymentApiException {
return new WithAccountLock<String>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<String>() {
@Override
public String doOperation() throws PaymentApiException {
PaymentPluginApi pluginApi = null;
try {
// STEPH do we want to really have a default or fail?? probably fail
pluginApi = pluginRegistry.getPlugin(pluginName);
return pluginApi.createPaymentProviderAccount(account);
} catch (PaymentPluginApiException e) {
throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_ACCOUNT_INIT,
account.getId(), pluginApi != null ? pluginApi.getName() : null, e.getErrorMessage());
}
}
});
}
public UUID addPaymentMethod(final String pluginName, final Account account,
final boolean setDefault, final PaymentMethodPlugin paymentMethodProps, final CallContext context)
throws PaymentApiException {
return new WithAccountLock<UUID>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<UUID>() {
@Override
public UUID doOperation() throws PaymentApiException {
PaymentMethod pm = null;
PaymentPluginApi pluginApi = null;
try {
pluginApi = pluginRegistry.getPlugin(pluginName);
pm = new DefaultPaymentMethod(account.getId(), pluginName, paymentMethodProps);
final String externalId = pluginApi.addPaymentMethod(account.getExternalKey(), paymentMethodProps, setDefault);
final PaymentMethodModelDao pmModel = new PaymentMethodModelDao(pm.getId(), pm.getAccountId(), pm.getPluginName(), pm.isActive(), externalId);
paymentDao.insertPaymentMethod(pmModel, context);
if (setDefault) {
final MutableAccountData updateAccountData = new DefaultMutableAccountData(account);
updateAccountData.setPaymentMethodId(pm.getId());
accountUserApi.updateAccount(account.getId(), updateAccountData, context);
}
} catch (PaymentPluginApiException e) {
// STEPH all errors should also take a pluginName
throw new PaymentApiException(ErrorCode.PAYMENT_ADD_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
} catch (AccountApiException e) {
throw new PaymentApiException(e);
}
return pm.getId();
}
});
}
public List<PaymentMethod> refreshPaymentMethods(final String pluginName, final Account account, final CallContext context)
throws PaymentApiException {
return new WithAccountLock<List<PaymentMethod>>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<List<PaymentMethod>>() {
@Override
public List<PaymentMethod> doOperation() throws PaymentApiException {
final PaymentPluginApi pluginApi;
try {
pluginApi = pluginRegistry.getPlugin(pluginName);
final List<PaymentMethodPlugin> pluginPms = pluginApi.getPaymentMethodDetails(account.getExternalKey());
// The method should never return null by convention, but let's not trust the plugin...
if (pluginPms == null) {
return ImmutableList.<PaymentMethod>of();
}
final List<PaymentMethodModelDao> finalPaymentMethods = new ArrayList<PaymentMethodModelDao>();
for (final PaymentMethodPlugin cur : pluginPms) {
final PaymentMethod input = new DefaultPaymentMethod(account.getId(), pluginName, cur);
final PaymentMethodModelDao pmModel = new PaymentMethodModelDao(input.getId(), input.getAccountId(), input.getPluginName(), input.isActive(), input.getPluginDetail().getExternalPaymentMethodId());
finalPaymentMethods.add(pmModel);
}
final List<PaymentMethodModelDao> refreshedPaymentMethods = paymentDao.refreshPaymentMethods(account.getId(), finalPaymentMethods, context);
return ImmutableList.<PaymentMethod>copyOf(Collections2.transform(refreshedPaymentMethods, new Function<PaymentMethodModelDao, PaymentMethod>() {
@Override
public PaymentMethod apply(final PaymentMethodModelDao input) {
- return new DefaultPaymentMethod(input);
+ return new DefaultPaymentMethod(input, getPaymentMethodDetail(pluginPms, input.getExternalId()));
}
}));
} catch (PaymentPluginApiException e) {
// STEPH all errors should also take a pluginName
throw new PaymentApiException(ErrorCode.PAYMENT_REFRESH_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
}
}
});
}
public List<PaymentMethod> getPaymentMethods(final Account account, final boolean withPluginDetail) throws PaymentApiException {
final List<PaymentMethodModelDao> paymentMethodModels = paymentDao.getPaymentMethods(account.getId());
if (paymentMethodModels.size() == 0) {
return Collections.emptyList();
}
return getPaymentMethodInternal(paymentMethodModels, account.getId(), account.getExternalKey(), withPluginDetail);
}
public PaymentMethod getPaymentMethodById(final UUID paymentMethodId)
throws PaymentApiException {
final PaymentMethodModelDao paymentMethodModel = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethodModel == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
return new DefaultPaymentMethod(paymentMethodModel, null);
}
public PaymentMethod getPaymentMethod(final Account account, final UUID paymentMethodId, final boolean withPluginDetail)
throws PaymentApiException {
final PaymentMethodModelDao paymentMethodModel = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethodModel == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
final List<PaymentMethod> result = getPaymentMethodInternal(Collections.singletonList(paymentMethodModel), account.getId(), account.getExternalKey(), withPluginDetail);
return (result.size() == 0) ? null : result.get(0);
}
private List<PaymentMethod> getPaymentMethodInternal(final List<PaymentMethodModelDao> paymentMethodModels, final UUID accountId, final String accountKey, final boolean withPluginDetail)
throws PaymentApiException {
final List<PaymentMethod> result = new ArrayList<PaymentMethod>(paymentMethodModels.size());
PaymentPluginApi pluginApi = null;
try {
List<PaymentMethodPlugin> pluginDetails = null;
for (final PaymentMethodModelDao cur : paymentMethodModels) {
if (withPluginDetail) {
pluginApi = pluginRegistry.getPlugin(cur.getPluginName());
pluginDetails = pluginApi.getPaymentMethodDetails(accountKey);
}
final PaymentMethod pm = new DefaultPaymentMethod(cur, getPaymentMethodDetail(pluginDetails, cur.getExternalId()));
result.add(pm);
}
} catch (PaymentPluginApiException e) {
throw new PaymentApiException(ErrorCode.PAYMENT_GET_PAYMENT_METHODS, accountId, e.getErrorMessage());
}
return result;
}
private PaymentMethodPlugin getPaymentMethodDetail(final List<PaymentMethodPlugin> pluginDetails, final String externalId) {
if (pluginDetails == null) {
return null;
}
for (final PaymentMethodPlugin cur : pluginDetails) {
if (cur.getExternalPaymentMethodId().equals(externalId)) {
return cur;
}
}
return null;
}
public void updatePaymentMethod(final Account account, final UUID paymentMethodId,
final PaymentMethodPlugin paymentMethodProps)
throws PaymentApiException {
new WithAccountLock<Void>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<Void>() {
@Override
public Void doOperation() throws PaymentApiException {
final PaymentMethodModelDao paymentMethodModel = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethodModel == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
try {
final PaymentMethodPlugin inputWithId = new DefaultPaymentMethodPlugin(paymentMethodProps, paymentMethodModel.getExternalId());
final PaymentPluginApi pluginApi = getPluginApi(paymentMethodId, account.getId());
pluginApi.updatePaymentMethod(account.getExternalKey(), inputWithId);
return null;
} catch (PaymentPluginApiException e) {
throw new PaymentApiException(ErrorCode.PAYMENT_UPD_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
}
}
});
}
public void deletedPaymentMethod(final Account account, final UUID paymentMethodId)
throws PaymentApiException {
new WithAccountLock<Void>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<Void>() {
@Override
public Void doOperation() throws PaymentApiException {
final PaymentMethodModelDao paymentMethodModel = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethodModel == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
try {
if (account.getPaymentMethodId().equals(paymentMethodId)) {
throw new PaymentApiException(ErrorCode.PAYMENT_DEL_DEFAULT_PAYMENT_METHOD, account.getId());
}
final PaymentPluginApi pluginApi = getPluginApi(paymentMethodId, account.getId());
pluginApi.deletePaymentMethod(account.getExternalKey(), paymentMethodModel.getExternalId());
paymentDao.deletedPaymentMethod(paymentMethodId);
return null;
} catch (PaymentPluginApiException e) {
throw new PaymentApiException(ErrorCode.PAYMENT_DEL_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
}
}
});
}
public void setDefaultPaymentMethod(final Account account, final UUID paymentMethodId, final CallContext context)
throws PaymentApiException {
new WithAccountLock<Void>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<Void>() {
@Override
public Void doOperation() throws PaymentApiException {
final PaymentMethodModelDao paymentMethodModel = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethodModel == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
try {
final PaymentPluginApi pluginApi = getPluginApi(paymentMethodId, account.getId());
pluginApi.setDefaultPaymentMethod(account.getExternalKey(), paymentMethodModel.getExternalId());
final MutableAccountData updateAccountData = new DefaultMutableAccountData(account);
updateAccountData.setPaymentMethodId(paymentMethodId);
accountUserApi.updateAccount(account.getId(), updateAccountData, context);
return null;
} catch (PaymentPluginApiException e) {
throw new PaymentApiException(ErrorCode.PAYMENT_UPD_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
} catch (AccountApiException e) {
throw new PaymentApiException(e);
}
}
});
}
private PaymentPluginApi getPluginApi(final UUID paymentMethodId, final UUID accountId)
throws PaymentApiException {
final PaymentMethodModelDao paymentMethod = paymentDao.getPaymentMethod(paymentMethodId);
if (paymentMethod == null) {
throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, paymentMethodId);
}
return pluginRegistry.getPlugin(paymentMethod.getPluginName());
}
}
| true | true | public List<PaymentMethod> refreshPaymentMethods(final String pluginName, final Account account, final CallContext context)
throws PaymentApiException {
return new WithAccountLock<List<PaymentMethod>>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<List<PaymentMethod>>() {
@Override
public List<PaymentMethod> doOperation() throws PaymentApiException {
final PaymentPluginApi pluginApi;
try {
pluginApi = pluginRegistry.getPlugin(pluginName);
final List<PaymentMethodPlugin> pluginPms = pluginApi.getPaymentMethodDetails(account.getExternalKey());
// The method should never return null by convention, but let's not trust the plugin...
if (pluginPms == null) {
return ImmutableList.<PaymentMethod>of();
}
final List<PaymentMethodModelDao> finalPaymentMethods = new ArrayList<PaymentMethodModelDao>();
for (final PaymentMethodPlugin cur : pluginPms) {
final PaymentMethod input = new DefaultPaymentMethod(account.getId(), pluginName, cur);
final PaymentMethodModelDao pmModel = new PaymentMethodModelDao(input.getId(), input.getAccountId(), input.getPluginName(), input.isActive(), input.getPluginDetail().getExternalPaymentMethodId());
finalPaymentMethods.add(pmModel);
}
final List<PaymentMethodModelDao> refreshedPaymentMethods = paymentDao.refreshPaymentMethods(account.getId(), finalPaymentMethods, context);
return ImmutableList.<PaymentMethod>copyOf(Collections2.transform(refreshedPaymentMethods, new Function<PaymentMethodModelDao, PaymentMethod>() {
@Override
public PaymentMethod apply(final PaymentMethodModelDao input) {
return new DefaultPaymentMethod(input);
}
}));
} catch (PaymentPluginApiException e) {
// STEPH all errors should also take a pluginName
throw new PaymentApiException(ErrorCode.PAYMENT_REFRESH_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
}
}
});
}
| public List<PaymentMethod> refreshPaymentMethods(final String pluginName, final Account account, final CallContext context)
throws PaymentApiException {
return new WithAccountLock<List<PaymentMethod>>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<List<PaymentMethod>>() {
@Override
public List<PaymentMethod> doOperation() throws PaymentApiException {
final PaymentPluginApi pluginApi;
try {
pluginApi = pluginRegistry.getPlugin(pluginName);
final List<PaymentMethodPlugin> pluginPms = pluginApi.getPaymentMethodDetails(account.getExternalKey());
// The method should never return null by convention, but let's not trust the plugin...
if (pluginPms == null) {
return ImmutableList.<PaymentMethod>of();
}
final List<PaymentMethodModelDao> finalPaymentMethods = new ArrayList<PaymentMethodModelDao>();
for (final PaymentMethodPlugin cur : pluginPms) {
final PaymentMethod input = new DefaultPaymentMethod(account.getId(), pluginName, cur);
final PaymentMethodModelDao pmModel = new PaymentMethodModelDao(input.getId(), input.getAccountId(), input.getPluginName(), input.isActive(), input.getPluginDetail().getExternalPaymentMethodId());
finalPaymentMethods.add(pmModel);
}
final List<PaymentMethodModelDao> refreshedPaymentMethods = paymentDao.refreshPaymentMethods(account.getId(), finalPaymentMethods, context);
return ImmutableList.<PaymentMethod>copyOf(Collections2.transform(refreshedPaymentMethods, new Function<PaymentMethodModelDao, PaymentMethod>() {
@Override
public PaymentMethod apply(final PaymentMethodModelDao input) {
return new DefaultPaymentMethod(input, getPaymentMethodDetail(pluginPms, input.getExternalId()));
}
}));
} catch (PaymentPluginApiException e) {
// STEPH all errors should also take a pluginName
throw new PaymentApiException(ErrorCode.PAYMENT_REFRESH_PAYMENT_METHOD, account.getId(), e.getErrorMessage());
}
}
});
}
|
diff --git a/atlassian-plugins-core/src/test/java/com/atlassian/plugin/TestDefaultPluginManagerLongRunning.java b/atlassian-plugins-core/src/test/java/com/atlassian/plugin/TestDefaultPluginManagerLongRunning.java
index c6c6c30b..8f3801cf 100644
--- a/atlassian-plugins-core/src/test/java/com/atlassian/plugin/TestDefaultPluginManagerLongRunning.java
+++ b/atlassian-plugins-core/src/test/java/com/atlassian/plugin/TestDefaultPluginManagerLongRunning.java
@@ -1,279 +1,291 @@
package com.atlassian.plugin;
import com.atlassian.plugin.descriptors.MockUnusedModuleDescriptor;
import com.atlassian.plugin.descriptors.RequiresRestart;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.impl.DefaultPluginEventManager;
import com.atlassian.plugin.factories.LegacyDynamicPluginFactory;
import com.atlassian.plugin.factories.XmlDynamicPluginFactory;
import com.atlassian.plugin.impl.StaticPlugin;
import com.atlassian.plugin.loaders.DirectoryPluginLoader;
import com.atlassian.plugin.loaders.PluginLoader;
import com.atlassian.plugin.loaders.classloading.AbstractTestClassLoader;
import com.atlassian.plugin.mock.MockAnimalModuleDescriptor;
import com.atlassian.plugin.repositories.FilePluginInstaller;
import com.atlassian.plugin.store.MemoryPluginStateStore;
import com.atlassian.plugin.test.PluginJarBuilder;
import com.atlassian.plugin.hostcontainer.DefaultHostContainer;
import org.apache.commons.io.FileUtils;
import com.mockobjects.dynamic.C;
import com.mockobjects.dynamic.Mock;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Testing {@link DefaultPluginManager}
*/
public class TestDefaultPluginManagerLongRunning extends AbstractTestClassLoader
{
/**
* the object being tested
*/
private DefaultPluginManager manager;
private PluginStateStore pluginStateStore;
private List<PluginLoader> pluginLoaders;
private DefaultModuleDescriptorFactory moduleDescriptorFactory; // we should be able to use the interface here?
private DirectoryPluginLoader directoryPluginLoader;
private PluginEventManager pluginEventManager;
@Override
protected void setUp() throws Exception
{
super.setUp();
pluginEventManager = new DefaultPluginEventManager();
pluginStateStore = new MemoryPluginStateStore();
pluginLoaders = new ArrayList<PluginLoader>();
moduleDescriptorFactory = new DefaultModuleDescriptorFactory(new DefaultHostContainer());
manager = new DefaultPluginManager(pluginStateStore, pluginLoaders, moduleDescriptorFactory, new DefaultPluginEventManager());
}
@Override
protected void tearDown() throws Exception
{
manager = null;
moduleDescriptorFactory = null;
pluginLoaders = null;
pluginStateStore = null;
if (directoryPluginLoader != null)
{
directoryPluginLoader.shutDown();
directoryPluginLoader = null;
}
super.tearDown();
}
public void testEnableFailed() throws PluginParseException
{
final Mock mockPluginLoader = new Mock(PluginLoader.class);
final Plugin plugin = new StaticPlugin()
{
@Override
public void setEnabled(final boolean enabled)
{
// do nothing
}
};
plugin.setKey("foo");
plugin.setEnabledByDefault(false);
plugin.setPluginInformation(new PluginInformation());
mockPluginLoader.expectAndReturn("loadAllPlugins", C.ANY_ARGS, Collections.singletonList(plugin));
final PluginLoader proxy = (PluginLoader) mockPluginLoader.proxy();
pluginLoaders.add(proxy);
manager.init();
assertEquals(1, manager.getPlugins().size());
assertEquals(0, manager.getEnabledPlugins().size());
assertFalse(plugin.getPluginState() == PluginState.ENABLED);
manager.enablePlugin("foo");
assertEquals(1, manager.getPlugins().size());
assertEquals(0, manager.getEnabledPlugins().size());
assertFalse(plugin.getPluginState() == PluginState.ENABLED);
}
private DefaultPluginManager makeClassLoadingPluginManager() throws PluginParseException
{
directoryPluginLoader = new DirectoryPluginLoader(pluginsTestDir, Arrays.asList(new LegacyDynamicPluginFactory(
PluginAccessor.Descriptor.FILENAME), new XmlDynamicPluginFactory()), pluginEventManager);
pluginLoaders.add(directoryPluginLoader);
moduleDescriptorFactory.addModuleDescriptor("animal", MockAnimalModuleDescriptor.class);
manager.init();
return manager;
}
public void testInstallPluginTwiceWithSameName() throws Exception
{
createFillAndCleanTempPluginDirectory();
FileUtils.cleanDirectory(pluginsTestDir);
final File plugin = File.createTempFile("plugin", ".jar");
- new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("foo.txt", "foo").addJava("my.MyClass",
- "package my; public class MyClass {}").build().renameTo(plugin);
+ plugin.delete();
+ File jar = new PluginJarBuilder("plugin")
+ .addPluginInformation("some.key", "My name", "1.0", 1)
+ .addResource("foo.txt", "foo")
+ .addJava("my.MyClass",
+ "package my; public class MyClass {}")
+ .build();
+ FileUtils.moveFile(jar, plugin);
final DefaultPluginManager manager = makeClassLoadingPluginManager();
manager.setPluginInstaller(new FilePluginInstaller(pluginsTestDir));
final String pluginKey = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin = manager.getPlugin(pluginKey);
assertNotNull(installedPlugin);
assertNotNull(installedPlugin.getClassLoader().getResourceAsStream("foo.txt"));
assertNull(installedPlugin.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin.getClassLoader().loadClass("my.MyClass"));
try
{
installedPlugin.getClassLoader().loadClass("my.MyNewClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
// sleep to ensure the new plugin is picked up
Thread.sleep(1000);
- new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("bar.txt", "bar").addJava("my.MyNewClass",
- "package my; public class MyNewClass {}").build().renameTo(plugin);
+ File jartmp = new PluginJarBuilder("plugin")
+ .addPluginInformation("some.key", "My name", "1.0", 1)
+ .addResource("bar.txt", "bar")
+ .addJava("my.MyNewClass",
+ "package my; public class MyNewClass {}")
+ .build();
+ plugin.delete();
+ FileUtils.moveFile(jartmp, plugin);
// reinstall the plugin
final String pluginKey2 = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin2 = manager.getPlugin(pluginKey2);
assertNotNull(installedPlugin2);
assertEquals(1, manager.getEnabledPlugins().size());
assertNull(installedPlugin2.getClassLoader().getResourceAsStream("foo.txt"));
assertNotNull(installedPlugin2.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin2.getClassLoader().loadClass("my.MyNewClass"));
try
{
installedPlugin2.getClassLoader().loadClass("my.MyClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
}
public void testInstallPluginTwiceWithDifferentName() throws Exception
{
createFillAndCleanTempPluginDirectory();
FileUtils.cleanDirectory(pluginsTestDir);
final File plugin1 = new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("foo.txt", "foo").addJava(
"my.MyClass", "package my; public class MyClass {}").build();
final DefaultPluginManager manager = makeClassLoadingPluginManager();
manager.setPluginInstaller(new FilePluginInstaller(pluginsTestDir));
final String pluginKey = manager.installPlugin(new JarPluginArtifact(plugin1));
assertTrue(new File(pluginsTestDir, plugin1.getName()).exists());
final Plugin installedPlugin = manager.getPlugin(pluginKey);
assertNotNull(installedPlugin);
assertNotNull(installedPlugin.getClassLoader().getResourceAsStream("foo.txt"));
assertNull(installedPlugin.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin.getClassLoader().loadClass("my.MyClass"));
try
{
installedPlugin.getClassLoader().loadClass("my.MyNewClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
// sleep to ensure the new plugin is picked up
Thread.sleep(1000);
final File plugin2 = new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("bar.txt", "bar").addJava(
"my.MyNewClass", "package my; public class MyNewClass {}").build();
// reinstall the plugin
final String pluginKey2 = manager.installPlugin(new JarPluginArtifact(plugin2));
assertFalse(new File(pluginsTestDir, plugin1.getName()).exists());
assertTrue(new File(pluginsTestDir, plugin2.getName()).exists());
final Plugin installedPlugin2 = manager.getPlugin(pluginKey2);
assertNotNull(installedPlugin2);
assertEquals(1, manager.getEnabledPlugins().size());
assertNull(installedPlugin2.getClassLoader().getResourceAsStream("foo.txt"));
assertNotNull(installedPlugin2.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin2.getClassLoader().loadClass("my.MyNewClass"));
try
{
installedPlugin2.getClassLoader().loadClass("my.MyClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
}
public void testAddPluginsWithDependencyIssuesNoResolution() throws Exception
{
final Plugin servicePlugin = new EnableInPassPlugin("service.plugin", 4);
final Plugin clientPlugin = new EnableInPassPlugin("client.plugin", 1);
manager.addPlugins(null, Arrays.asList(servicePlugin, clientPlugin));
assertTrue(clientPlugin.getPluginState() == PluginState.ENABLED);
assertFalse(servicePlugin.getPluginState() == PluginState.ENABLED);
}
public Plugin createPluginWithVersion(final String version)
{
final Plugin p = new StaticPlugin();
p.setKey("test.default.plugin");
final PluginInformation pInfo = p.getPluginInformation();
pInfo.setVersion(version);
return p;
}
private static class EnableInPassPlugin extends StaticPlugin
{
private int pass;
public EnableInPassPlugin(final String key, final int pass)
{
this.pass = pass;
setKey(key);
}
@Override
public void setEnabled(final boolean val)
{
super.setEnabled((--pass) <= 0);
}
}
class NothingModuleDescriptor extends MockUnusedModuleDescriptor
{}
@RequiresRestart
public static class RequiresRestartModuleDescriptor extends MockUnusedModuleDescriptor
{}
}
| false | true | public void testInstallPluginTwiceWithSameName() throws Exception
{
createFillAndCleanTempPluginDirectory();
FileUtils.cleanDirectory(pluginsTestDir);
final File plugin = File.createTempFile("plugin", ".jar");
new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("foo.txt", "foo").addJava("my.MyClass",
"package my; public class MyClass {}").build().renameTo(plugin);
final DefaultPluginManager manager = makeClassLoadingPluginManager();
manager.setPluginInstaller(new FilePluginInstaller(pluginsTestDir));
final String pluginKey = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin = manager.getPlugin(pluginKey);
assertNotNull(installedPlugin);
assertNotNull(installedPlugin.getClassLoader().getResourceAsStream("foo.txt"));
assertNull(installedPlugin.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin.getClassLoader().loadClass("my.MyClass"));
try
{
installedPlugin.getClassLoader().loadClass("my.MyNewClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
// sleep to ensure the new plugin is picked up
Thread.sleep(1000);
new PluginJarBuilder("plugin").addPluginInformation("some.key", "My name", "1.0", 1).addResource("bar.txt", "bar").addJava("my.MyNewClass",
"package my; public class MyNewClass {}").build().renameTo(plugin);
// reinstall the plugin
final String pluginKey2 = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin2 = manager.getPlugin(pluginKey2);
assertNotNull(installedPlugin2);
assertEquals(1, manager.getEnabledPlugins().size());
assertNull(installedPlugin2.getClassLoader().getResourceAsStream("foo.txt"));
assertNotNull(installedPlugin2.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin2.getClassLoader().loadClass("my.MyNewClass"));
try
{
installedPlugin2.getClassLoader().loadClass("my.MyClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
}
| public void testInstallPluginTwiceWithSameName() throws Exception
{
createFillAndCleanTempPluginDirectory();
FileUtils.cleanDirectory(pluginsTestDir);
final File plugin = File.createTempFile("plugin", ".jar");
plugin.delete();
File jar = new PluginJarBuilder("plugin")
.addPluginInformation("some.key", "My name", "1.0", 1)
.addResource("foo.txt", "foo")
.addJava("my.MyClass",
"package my; public class MyClass {}")
.build();
FileUtils.moveFile(jar, plugin);
final DefaultPluginManager manager = makeClassLoadingPluginManager();
manager.setPluginInstaller(new FilePluginInstaller(pluginsTestDir));
final String pluginKey = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin = manager.getPlugin(pluginKey);
assertNotNull(installedPlugin);
assertNotNull(installedPlugin.getClassLoader().getResourceAsStream("foo.txt"));
assertNull(installedPlugin.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin.getClassLoader().loadClass("my.MyClass"));
try
{
installedPlugin.getClassLoader().loadClass("my.MyNewClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
// sleep to ensure the new plugin is picked up
Thread.sleep(1000);
File jartmp = new PluginJarBuilder("plugin")
.addPluginInformation("some.key", "My name", "1.0", 1)
.addResource("bar.txt", "bar")
.addJava("my.MyNewClass",
"package my; public class MyNewClass {}")
.build();
plugin.delete();
FileUtils.moveFile(jartmp, plugin);
// reinstall the plugin
final String pluginKey2 = manager.installPlugin(new JarPluginArtifact(plugin));
assertTrue(new File(pluginsTestDir, plugin.getName()).exists());
final Plugin installedPlugin2 = manager.getPlugin(pluginKey2);
assertNotNull(installedPlugin2);
assertEquals(1, manager.getEnabledPlugins().size());
assertNull(installedPlugin2.getClassLoader().getResourceAsStream("foo.txt"));
assertNotNull(installedPlugin2.getClassLoader().getResourceAsStream("bar.txt"));
assertNotNull(installedPlugin2.getClassLoader().loadClass("my.MyNewClass"));
try
{
installedPlugin2.getClassLoader().loadClass("my.MyClass");
fail("Expected ClassNotFoundException for unknown class");
}
catch (final ClassNotFoundException e)
{
// expected
}
}
|
diff --git a/wharf-core/src/main/java/org/jfrog/wharf/ivy/resource/WharfUrlResource.java b/wharf-core/src/main/java/org/jfrog/wharf/ivy/resource/WharfUrlResource.java
index 54e5571..908d631 100644
--- a/wharf-core/src/main/java/org/jfrog/wharf/ivy/resource/WharfUrlResource.java
+++ b/wharf-core/src/main/java/org/jfrog/wharf/ivy/resource/WharfUrlResource.java
@@ -1,156 +1,159 @@
/*
*
* Copyright (C) 2010 JFrog Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package org.jfrog.wharf.ivy.resource;
import org.apache.ivy.plugins.repository.Resource;
import org.apache.ivy.plugins.repository.file.FileResource;
import org.apache.ivy.plugins.repository.url.URLResource;
import org.apache.ivy.util.url.URLHandlerRegistry;
import org.jfrog.wharf.ivy.handler.WharfUrlHandler;
import org.jfrog.wharf.ivy.util.WharfUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author Tomer Cohen
*/
public class WharfUrlResource implements Resource {
private URL url;
private boolean init = false;
private long lastModified;
private long contentLength;
private boolean exists;
private String sha1;
private String md5;
public WharfUrlResource(URL url) {
this.url = url;
}
public WharfUrlResource(Resource resource) {
if (resource instanceof FileResource) {
try {
url = ((FileResource) resource).getFile().toURI().toURL();
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed File URL", e);
}
} else if (resource instanceof URLResource) {
url = ((URLResource) resource).getURL();
} else if (resource instanceof WharfUrlResource) {
- try {
- url = new URL(resource.getName());
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
+ WharfUrlResource wharfUrlResource = (WharfUrlResource) resource;
+ this.url = wharfUrlResource.url;
+ this.init = wharfUrlResource.init;
+ this.lastModified = wharfUrlResource.lastModified;
+ this.contentLength = wharfUrlResource.contentLength;
+ this.exists = wharfUrlResource.exists;
+ this.sha1 = wharfUrlResource.sha1;
+ this.md5 = wharfUrlResource.md5;
} else {
throw new IllegalArgumentException("Wharf Downloader manage only URL and Files");
}
}
@Override
public String getName() {
return url.toExternalForm();
}
@Override
public Resource clone(String cloneName) {
try {
return new WharfUrlResource(new URL(cloneName));
} catch (MalformedURLException e) {
try {
return new WharfUrlResource(new File(cloneName).toURI().toURL());
} catch (MalformedURLException e1) {
throw new IllegalArgumentException(
"bad clone name provided: not suitable for an URLResource: " + cloneName);
}
}
}
@Override
public long getLastModified() {
if (!init) {
init();
}
return lastModified;
}
private void init() {
WharfUrlHandler.WharfUrlInfo info = new WharfUrlHandler().getURLInfo(url);
contentLength = info.getContentLength();
lastModified = info.getLastModified();
exists = info.isReachable();
sha1 = WharfUtils.getCleanChecksum(info.getSha1());
md5 = WharfUtils.getCleanChecksum(info.getMd5());
init = true;
}
@Override
public long getContentLength() {
if (!init) {
init();
}
return contentLength;
}
public String getSha1() {
if (!init) {
init();
}
return sha1;
}
public String getMd5() {
if (!init) {
init();
}
return md5;
}
@Override
public boolean exists() {
if (!init) {
init();
}
return exists;
}
public String toString() {
return getName();
}
@Override
public boolean isLocal() {
return false;
}
@Override
public InputStream openStream() throws IOException {
return URLHandlerRegistry.getDefault().openStream(url);
}
}
| true | true | public WharfUrlResource(Resource resource) {
if (resource instanceof FileResource) {
try {
url = ((FileResource) resource).getFile().toURI().toURL();
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed File URL", e);
}
} else if (resource instanceof URLResource) {
url = ((URLResource) resource).getURL();
} else if (resource instanceof WharfUrlResource) {
try {
url = new URL(resource.getName());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else {
throw new IllegalArgumentException("Wharf Downloader manage only URL and Files");
}
}
| public WharfUrlResource(Resource resource) {
if (resource instanceof FileResource) {
try {
url = ((FileResource) resource).getFile().toURI().toURL();
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed File URL", e);
}
} else if (resource instanceof URLResource) {
url = ((URLResource) resource).getURL();
} else if (resource instanceof WharfUrlResource) {
WharfUrlResource wharfUrlResource = (WharfUrlResource) resource;
this.url = wharfUrlResource.url;
this.init = wharfUrlResource.init;
this.lastModified = wharfUrlResource.lastModified;
this.contentLength = wharfUrlResource.contentLength;
this.exists = wharfUrlResource.exists;
this.sha1 = wharfUrlResource.sha1;
this.md5 = wharfUrlResource.md5;
} else {
throw new IllegalArgumentException("Wharf Downloader manage only URL and Files");
}
}
|
diff --git a/src/com/pindroid/fragment/AboutFragment.java b/src/com/pindroid/fragment/AboutFragment.java
index 051ddad..6a0614c 100644
--- a/src/com/pindroid/fragment/AboutFragment.java
+++ b/src/com/pindroid/fragment/AboutFragment.java
@@ -1,58 +1,58 @@
/*
* PinDroid - http://code.google.com/p/PinDroid/
*
* Copyright (C) 2010 Matt Schmidt
*
* PinDroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* PinDroid is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PinDroid; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package com.pindroid.fragment;
import com.pindroid.R;
import com.pindroid.activity.FragmentBaseActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
public class AboutFragment extends Fragment {
private FragmentBaseActivity base;
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
base = (FragmentBaseActivity)getActivity();
base.setTitle(R.string.about_activity_title);
WebView content = (WebView) base.findViewById(R.id.about_text_view);
- content.loadData(getString(R.string.about_text), "text/html", "utf-8");
+ content.loadDataWithBaseURL(null, getString(R.string.about_text), "text/html", "utf-8", null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.about_view_fragment, container, false);
}
}
| true | true | public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
base = (FragmentBaseActivity)getActivity();
base.setTitle(R.string.about_activity_title);
WebView content = (WebView) base.findViewById(R.id.about_text_view);
content.loadData(getString(R.string.about_text), "text/html", "utf-8");
}
| public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
base = (FragmentBaseActivity)getActivity();
base.setTitle(R.string.about_activity_title);
WebView content = (WebView) base.findViewById(R.id.about_text_view);
content.loadDataWithBaseURL(null, getString(R.string.about_text), "text/html", "utf-8", null);
}
|
diff --git a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/FilterTest.java b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/FilterTest.java
index 4de8efbe1..73418350c 100644
--- a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/FilterTest.java
+++ b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/FilterTest.java
@@ -1,62 +1,64 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.compare.tests;
import org.eclipse.compare.internal.CompareFilter;
import junit.framework.*;
import junit.framework.TestCase;
public class FilterTest extends TestCase {
CompareFilter fFilter;
public FilterTest(String name) {
super(name);
}
public void testFilterFile() {
CompareFilter f= new CompareFilter();
f.setFilters("*.class"); //$NON-NLS-1$
Assert.assertTrue("file foo.class should be filtered", f.filter("foo.class", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.java shouldn't be filtered", f.filter("foo.java", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testFilterDotFile() {
CompareFilter f= new CompareFilter();
f.setFilters(".cvsignore"); //$NON-NLS-1$
Assert.assertTrue("file .cvsignore should be filtered", f.filter(".cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.cvsignore shouldn't be filtered", f.filter("foo.cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testFilterFolder() {
CompareFilter f= new CompareFilter();
f.setFilters("bin/"); //$NON-NLS-1$
Assert.assertTrue("folder bin should be filtered", f.filter("bin", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file bin shouldn't be filtered", f.filter("bin", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testMultiFilter() {
CompareFilter f= new CompareFilter();
- f.setFilters("*.class, .cvsignore, bin/"); //$NON-NLS-1$
+ f.setFilters("*.class, .cvsignore, bin/, src/"); //$NON-NLS-1$
Assert.assertTrue("file foo.class should be filtered", f.filter("foo.class", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.java shouldn't be filtered", f.filter("foo.java", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("file .cvsignore should be filtered", f.filter(".cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.cvsignore shouldn't be filtered", f.filter("foo.cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("folder bin should be filtered", f.filter("bin", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file bin shouldn't be filtered", f.filter("bin", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
+ Assert.assertTrue("folder src should be filtered", f.filter("src", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
+ Assert.assertFalse("file src shouldn't be filtered", f.filter("src", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testVerify() {
//Assert.assertNull("filters don't verify", Filter.validateResourceFilters("*.class, .cvsignore, bin/"));
//Assert.assertNotNull("filters shouldn't verify", Filter.validateResourceFilters("bin//"));
}
}
| false | true | public void testMultiFilter() {
CompareFilter f= new CompareFilter();
f.setFilters("*.class, .cvsignore, bin/"); //$NON-NLS-1$
Assert.assertTrue("file foo.class should be filtered", f.filter("foo.class", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.java shouldn't be filtered", f.filter("foo.java", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("file .cvsignore should be filtered", f.filter(".cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.cvsignore shouldn't be filtered", f.filter("foo.cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("folder bin should be filtered", f.filter("bin", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file bin shouldn't be filtered", f.filter("bin", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
| public void testMultiFilter() {
CompareFilter f= new CompareFilter();
f.setFilters("*.class, .cvsignore, bin/, src/"); //$NON-NLS-1$
Assert.assertTrue("file foo.class should be filtered", f.filter("foo.class", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.java shouldn't be filtered", f.filter("foo.java", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("file .cvsignore should be filtered", f.filter(".cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file foo.cvsignore shouldn't be filtered", f.filter("foo.cvsignore", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("folder bin should be filtered", f.filter("bin", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file bin shouldn't be filtered", f.filter("bin", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertTrue("folder src should be filtered", f.filter("src", true, false)); //$NON-NLS-1$ //$NON-NLS-2$
Assert.assertFalse("file src shouldn't be filtered", f.filter("src", false, false)); //$NON-NLS-1$ //$NON-NLS-2$
}
|
diff --git a/src/GUI/Tag.java b/src/GUI/Tag.java
index 8d7d343..4c248b9 100644
--- a/src/GUI/Tag.java
+++ b/src/GUI/Tag.java
@@ -1,250 +1,249 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import GUIListeners.TagMouseListener;
import TrolleyRegistration.Flight;
import TrolleyRegistration.Trolley;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
/**
*
* @author haavamoa
*/
public class Tag{
public TrolleyApp trolleyApp;
public Flight flight;
public Trolley trolley;
public JPanel routePanel = new JPanel();
public JPanel weigthDatePanel = new JPanel();
public JPanel buttonPanel = new JPanel();
public JButton print;
private Action PrintTag;
private Action back;
public Tag(TrolleyApp trolleyApp,Flight flight,Trolley trolley) {
this.flight = flight;
this.trolleyApp = trolleyApp;
this.trolley = trolley;
trolleyApp.requestFocus();
trolleyApp.setLayout(new BorderLayout());
trolleyApp.removeAll();
trolleyApp.revalidate();
trolleyApp.repaint();
setActions();
setActionBindings();
routePanelSetup();
weigthDatePanelSetup();
buttonPanelSetup();
}
/**
* Sets up the panel to display the information about the route.
*/
public void routePanelSetup(){
routePanel.setLayout(new BorderLayout());
routePanel.setBackground(Color.white);
routePanel.setPreferredSize(new Dimension(50, 100));
// routePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
//Route panel inside route panel.
JPanel routeNumber = new JPanel();
routeNumber.setBackground(Color.white);
routeNumber.setLayout(new GridBagLayout());
c.insets = new Insets(0, 100, 0, 0);
c.gridx = 0;
c.gridy = 0;
routeNumber.add(new JLabel("Rute nummer :"),c);
c.gridx = 0;
c.gridy = 1;
JLabel routeNr = new JLabel(flight.flightRoute.getFlightRouteNr());
routeNr.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
routeNumber.add(routeNr,c);
routePanel.add(routeNumber,BorderLayout.WEST);
JPanel datePanel = new JPanel();
datePanel.setBackground(Color.white);
datePanel.setLayout(new GridBagLayout());
c.insets = new Insets(0, 0, 0, 100);
c.gridx = 0;
c.gridy = 1;
datePanel.add(new JLabel("Dato :"),c);
//Date
c.gridx = 0;
c.gridy = 2;
String dateS = new SimpleDateFormat("dd-MM-yyyy").format(flight.timestamp.getTime());
JLabel date = new JLabel(dateS);
date.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
datePanel.add(date,c);
routePanel.add(datePanel,BorderLayout.EAST);
trolleyApp.add(routePanel,BorderLayout.NORTH);
}
/**
* Sets up the panel to display the weight and the date.
*/
public void weigthDatePanelSetup(){
weigthDatePanel.setBackground(Color.white);
weigthDatePanel.setPreferredSize(new Dimension(trolleyApp.getWidth(), 70));
weigthDatePanel.setLayout(new GridBagLayout());
weigthDatePanel.setBorder(new MatteBorder(2, 0, 2, 0, Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
JLabel destination= new JLabel("Destinasjon :");
c.gridx = 0;
c.gridy = 1;
weigthDatePanel.add(destination,c);
JLabel dest = new JLabel(flight.flightRoute.getDestination());
c.gridx = 0;
c.gridy = 2;
dest.setFont(new Font(Font.MONOSPACED, Font.BOLD, 32));
weigthDatePanel.add(dest,c);
//Load weigth
c.insets = new Insets(100, 0, 0, 0);
c.gridx = 0;
c.gridy = 3;
weigthDatePanel.add(new JLabel("Lastvekt :"),c);
c.insets = new Insets(0, 0, 0, 0);
c.gridx = 0;
c.gridy = 4;
JLabel weigth = new JLabel(trolley.getPayLoad()+"kg");
weigth.setFont(new Font(Font.MONOSPACED, Font.BOLD, 32));
weigthDatePanel.add(weigth,c);
trolleyApp.add(weigthDatePanel,BorderLayout.CENTER);
}
/**
* Sets up the panel ti display print and cancel buttons.
*/
public void buttonPanelSetup(){
buttonPanel.setBackground(Color.white);
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setPreferredSize(new Dimension(trolleyApp.getWidth(), 150));
JButton btn;
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
//Print button
print= new JButton(PrintTag);
print.setText("Print tag");
buttonPanel.add(print,c);
//Cancel button
trolleyApp.add(buttonPanel,BorderLayout.SOUTH);
}
public void setActions(){
PrintTag = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName("Utskrift av tralleseddel");
printJob.setPrintable(new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX()-20, pageFormat.getImageableY()); //Setter y rettning litt mindre for å få det midstilt
g2d.scale(.65, .65); //0.65 ganger i forhold til applikasjonen.
//Pushing the size up for printing
for(Component c:weigthDatePanel.getComponents())
if(c instanceof JLabel){
if(((JLabel)c).getText().equals(flight.flightRoute.getDestination())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 100));
}else if(((JLabel)c).getText().equals(flight.flightRoute.getFlightNr())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 50));
}
}
// Turn off double buffering
print.hide();
trolleyApp.paint(g2d);
print.show();
// Turn double buffering back on
return(PAGE_EXISTS);
}
}
});
if (printJob.printDialog()){
try {
printJob.print();
new MainMenu(trolleyApp);
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
}
};
back = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
- new RegisterTrolley(trolleyApp);
}
};
}
public void setActionBindings(){
String action,key;
//Bind enter to calculate loadweight
action = "print";
key= "ENTER";
trolleyApp.getInputMap().put(KeyStroke.getKeyStroke(key), action);
trolleyApp.getActionMap().put(action, PrintTag);
action = "back";
key = "ESCAPE";
trolleyApp.getInputMap().put(KeyStroke.getKeyStroke(key), action);
trolleyApp.getActionMap().put(action, back);
}
}
| true | true | public void setActions(){
PrintTag = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName("Utskrift av tralleseddel");
printJob.setPrintable(new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX()-20, pageFormat.getImageableY()); //Setter y rettning litt mindre for å få det midstilt
g2d.scale(.65, .65); //0.65 ganger i forhold til applikasjonen.
//Pushing the size up for printing
for(Component c:weigthDatePanel.getComponents())
if(c instanceof JLabel){
if(((JLabel)c).getText().equals(flight.flightRoute.getDestination())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 100));
}else if(((JLabel)c).getText().equals(flight.flightRoute.getFlightNr())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 50));
}
}
// Turn off double buffering
print.hide();
trolleyApp.paint(g2d);
print.show();
// Turn double buffering back on
return(PAGE_EXISTS);
}
}
});
if (printJob.printDialog()){
try {
printJob.print();
new MainMenu(trolleyApp);
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
}
};
back = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
new RegisterTrolley(trolleyApp);
}
};
}
| public void setActions(){
PrintTag = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName("Utskrift av tralleseddel");
printJob.setPrintable(new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX()-20, pageFormat.getImageableY()); //Setter y rettning litt mindre for å få det midstilt
g2d.scale(.65, .65); //0.65 ganger i forhold til applikasjonen.
//Pushing the size up for printing
for(Component c:weigthDatePanel.getComponents())
if(c instanceof JLabel){
if(((JLabel)c).getText().equals(flight.flightRoute.getDestination())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 100));
}else if(((JLabel)c).getText().equals(flight.flightRoute.getFlightNr())){
c.setFont(new Font(Font.MONOSPACED, Font.BOLD, 50));
}
}
// Turn off double buffering
print.hide();
trolleyApp.paint(g2d);
print.show();
// Turn double buffering back on
return(PAGE_EXISTS);
}
}
});
if (printJob.printDialog()){
try {
printJob.print();
new MainMenu(trolleyApp);
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
}
};
back = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
}
|
diff --git a/src/com/wickedspiral/jacss/parser/Parser.java b/src/com/wickedspiral/jacss/parser/Parser.java
index fb15310..e52cb8b 100644
--- a/src/com/wickedspiral/jacss/parser/Parser.java
+++ b/src/com/wickedspiral/jacss/parser/Parser.java
@@ -1,558 +1,558 @@
package com.wickedspiral.jacss.parser;
import com.wickedspiral.jacss.lexer.Token;
import com.wickedspiral.jacss.lexer.TokenListener;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static com.wickedspiral.jacss.lexer.Token.*;
/**
* @author wasche
* @since 2011.08.04
*/
public class Parser implements TokenListener
{
private static final String MS_ALPHA = "progid:dximagetransform.microsoft.alpha(opacity=";
private static final Collection<String> UNITS = new HashSet<>(
Arrays.asList("px", "em", "pt", "in", "cm", "mm", "pc", "ex", "%"));
private static final Collection<String> KEYWORDS = new HashSet<>(
Arrays.asList("normal", "bold", "italic", "serif", "sans-serif", "fixed"));
private static final Collection<String> BOUNDARY_OPS = new HashSet<>(
Arrays.asList("{", "}", ">", ";", ":", ",")); // or comment
private static final Collection<String> DUAL_ZERO_PROPERTIES = new HashSet<>(
Arrays.asList("background-position", "-webkit-transform-origin", "-moz-transform-origin"));
private static final Collection<String> NONE_PROPERTIES = new HashSet<>();
static
{
NONE_PROPERTIES.add("outline");
for (String property : new String[] {"border", "margin", "padding"})
{
NONE_PROPERTIES.add(property);
for (String edge : new String[]{"top", "left", "bottom", "right"})
{
NONE_PROPERTIES.add(property + "-" + edge);
}
}
}
// buffers
private LinkedList<String> ruleBuffer;
private LinkedList<String> valueBuffer;
private LinkedList<String> rgbBuffer;
private String pending;
// flags
private boolean inRule;
private boolean space;
private boolean charset;
private boolean at;
private boolean ie5mac;
private boolean rgb;
private int checkSpace;
// other state
private String property;
private Token lastToken;
private String lastValue;
private PrintStream out;
private boolean debug;
private boolean keepTailingSemicolons;
private boolean noCollapseZeroes;
private boolean noCollapseNone;
public Parser(OutputStream outputStream, boolean debug, boolean keepTailingSemicolons, boolean noCollapseZeroes,
boolean noCollapseNone)
{
out = new PrintStream(new BufferedOutputStream(outputStream));
ruleBuffer = new LinkedList<>();
valueBuffer = new LinkedList<>();
rgbBuffer = new LinkedList<>();
inRule = false;
space = false;
charset = false;
at = false;
ie5mac = false;
rgb = false;
checkSpace = -1;
this.debug = debug;
this.keepTailingSemicolons = keepTailingSemicolons;
this.noCollapseZeroes = noCollapseZeroes;
this.noCollapseNone = noCollapseNone;
}
// ++ Output functions
private void output(Collection<String> strings)
{
for (String s : strings)
{
output(s);
}
}
private void output(String str)
{
out.print(str);
out.flush();
}
private void dump(String str)
{
ruleBuffer.add(pending);
ruleBuffer.add(str);
output(ruleBuffer);
ruleBuffer.clear();
}
private void write(String str)
{
if (str == null || str.length() == 0) return;
if (str.startsWith("/*!") && ruleBuffer.isEmpty())
{
output(str);
}
if ("}".equals(str))
{
// check for empty rule
if (!ruleBuffer.isEmpty() && !"{".equals(ruleBuffer.getLast()))
{
output(ruleBuffer);
output(str);
}
ruleBuffer.clear();
}
else
{
ruleBuffer.add(str);
}
}
private void buffer(String str)
{
if (str == null || str.length() == 0) return;
if (pending == null)
{
pending = str;
}
else
{
write(pending);
pending = str;
}
}
private void queue(String str)
{
if (str == null || str.length() == 0) return;
if (property != null)
{
valueBuffer.add(str);
}
else
{
buffer(str);
}
}
private void collapseValue()
{
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
String value = sb.toString();
if ("0 0".equals(value) || "0 0 0 0".equals(value) || "0 0 0".equals(value))
{
if (DUAL_ZERO_PROPERTIES.contains(value))
{
buffer("0 0");
}
else
{
buffer("0");
}
}
else if ("none".equals(value) && (NONE_PROPERTIES.contains(property) || "background".equals(property)) && !noCollapseNone)
{
buffer("0");
}
else
{
buffer(value);
}
}
// ++ TokenListener
public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (MS_ALPHA.equals(value.substring(1, MS_ALPHA.length() + 1).toLowerCase()))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
- queue(v.substring(2, 1));
- queue(v.substring(4, 1));
+ queue(v.substring(2, 3));
+ queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
public void end()
{
write(pending);
if (!ruleBuffer.isEmpty())
{
output(ruleBuffer);
}
}
}
| true | true | public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (MS_ALPHA.equals(value.substring(1, MS_ALPHA.length() + 1).toLowerCase()))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 1));
queue(v.substring(4, 1));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
| public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (MS_ALPHA.equals(value.substring(1, MS_ALPHA.length() + 1).toLowerCase()))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
|
diff --git a/toolkit/toolkit-view/src/main/java/org/bonitasoft/web/toolkit/client/ViewController.java b/toolkit/toolkit-view/src/main/java/org/bonitasoft/web/toolkit/client/ViewController.java
index 72003df4d..c7ff1e9f3 100644
--- a/toolkit/toolkit-view/src/main/java/org/bonitasoft/web/toolkit/client/ViewController.java
+++ b/toolkit/toolkit-view/src/main/java/org/bonitasoft/web/toolkit/client/ViewController.java
@@ -1,406 +1,406 @@
/**
* Copyright (C) 2009 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.web.toolkit.client;
import static com.google.gwt.query.client.GQuery.$;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.bonitasoft.web.toolkit.client.common.TreeIndexed;
import org.bonitasoft.web.toolkit.client.eventbus.MainEventBus;
import org.bonitasoft.web.toolkit.client.eventbus.events.ChangeViewEvent;
import org.bonitasoft.web.toolkit.client.ui.JsId;
import org.bonitasoft.web.toolkit.client.ui.RawView;
import org.bonitasoft.web.toolkit.client.ui.component.Link;
import org.bonitasoft.web.toolkit.client.ui.component.Refreshable;
import org.bonitasoft.web.toolkit.client.ui.component.core.AbstractComponent;
import org.bonitasoft.web.toolkit.client.ui.component.core.CustomPanel;
import org.bonitasoft.web.toolkit.client.ui.component.form.view.BlankPage;
import org.bonitasoft.web.toolkit.client.ui.component.form.view.DeleteItemPage;
import org.bonitasoft.web.toolkit.client.ui.component.form.view.EditItemPage;
import org.bonitasoft.web.toolkit.client.ui.page.ChangeLangPage;
import org.bonitasoft.web.toolkit.client.ui.page.PageOnItem;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
/**
* This Class defines the main controller of the entire GWT application. It is responsible for the interaction between the
* different components spread all over the window.
*
* @author Julien Mege
*/
public class ViewController {
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CONFIG
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static final String ROOT_DIV_ID = "body";
public static final String POPUP_DIV_ID = "popup";
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FIELDS
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected static final ViewController INSTANCE = new ViewController();
private RootPanel centralPanelContainer;
private String currentPageToken = null;
private final boolean disableUpdateAppView = false;
private final List<AbstractComponent> componentsWaitingForLoad = new LinkedList<AbstractComponent>();
private final List<Refreshable> componentsWaitingForRefresh = new LinkedList<Refreshable>();
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INIT AND CONSTRUCTOR
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Get the ViewController instance.
*
* @return the unique instance of the ViewController.
*/
public static ViewController getInstance() {
return INSTANCE;
}
protected ViewController() {
GWT.setUncaughtExceptionHandler(new CatchAllExceptionHandler());
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SHOW VIEWS
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private RawView currentPage = null;
private static String readToken(final String token) {
if (token == null || token.length() == 0) {
return token;
}
final String[] tokenParts = token.split("\\?");
return tokenParts[0];
}
public String getCurrentPageToken() {
return currentPageToken;
}
public void setCurrentPageToken(final String currentPageToken) {
this.currentPageToken = currentPageToken;
}
public static RawView showView(final String token) {
return showView(token, ROOT_DIV_ID);
}
public static RawView showView(final String token, final String parentId) {
return showView(token, parentId, new TreeIndexed<String>());
}
public static RawView showView(final String token, final Map<String, String> params) {
return showView(token, (String) null, params);
}
public static RawView showView(final String token, final TreeIndexed<String> params) {
return showView(token, (String) null, params);
}
public static RawView showView(final RawView view) {
return showView(view, ROOT_DIV_ID, view.getParameters());
}
public static RawView showView(final RawView view, final String parentId) {
return showView(view, parentId, view.getParameters());
}
public static RawView showView(final RawView view, final Map<String, String> params) {
return showView(view, ROOT_DIV_ID, new TreeIndexed<String>(params));
}
public static RawView showView(final String token, final String parentId, final Map<String, String> params) {
return showView(token, parentId, new TreeIndexed<String>(params));
}
public static RawView showView(final RawView view, final String parentId, final Map<String, String> params) {
return showView(view, parentId, new TreeIndexed<String>(params));
}
public static RawView showView(final String token, final String parentId, final TreeIndexed<String> params) {
Element rootElement = null;
if (parentId == null) {
rootElement = DOM.getElementById("body");
} else {
rootElement = DOM.getElementById(parentId);
}
if (rootElement != null) {
return showView(token, rootElement, params);
}
return null;
}
public static RawView showView(final RawView view, final String parentId, final TreeIndexed<String> params) {
assert parentId != null;
final Element rootElement = DOM.getElementById(parentId);
if (rootElement != null) {
return showView(view, rootElement, params);
}
return view;
}
public static RawView showView(final String token, final Element rootElement, final HashMap<String, String> params) {
return showView(token, rootElement, new TreeIndexed<String>(params));
}
public static RawView showView(final RawView view, final Element rootElement, final HashMap<String, String> params) {
return showView(view, rootElement, new TreeIndexed<String>(params));
}
public static RawView showView(final String token, final Element rootElement, final TreeIndexed<String> params) {
return showView(ViewController.getInstance().createView(token, params), rootElement, params);
}
public static RawView showView(final RawView view, final Element rootElement, final TreeIndexed<String> params) {
// Set the parent Element to the view that will be displayed
view.setParentElement(rootElement);
if (ViewController.ROOT_DIV_ID.equals(rootElement.getId())) {
// Reset unseless elements
ViewController.closePopup();
// getInstance().componentsWaitingForRefresh.clear();
getInstance().currentPage = view;
getInstance().setCurrentPageToken(view.getToken());
// Set the URL
- if (!BlankPage.TOKEN.equals(view.getToken())) {
- ClientApplicationURL.setPageToken(view.getToken(), false);
- }
+ //if (!BlankPage.TOKEN.equals(view.getToken())) {
+ ClientApplicationURL.setPageToken(view.getToken(), false);
+ //}
ClientApplicationURL.setPageAttributes(params);
ClientApplicationURL.refreshUrl(false);
}
final CustomPanel widget = view.toWidget();
final Element widgetElement = widget.getElement();
if (!(view instanceof PageOnItem<?>)) {
$(rootElement).empty();
} else {
$(widgetElement).hide();
}
rootElement.appendChild(widgetElement);
widget.onLoad();
ViewController.updateUI(rootElement, true);
MainEventBus.getInstance().fireEventFromSource(new ChangeViewEvent(view), getInstance());
return view;
}
public static void showPopup(final String token) {
showPopup(token, new TreeIndexed<String>());
}
public static void showPopup(final String token, final Map<String, String> params) {
ViewController.showPopup(token, new TreeIndexed<String>(params));
}
public static void showPopup(final String token, final TreeIndexed<String> params) {
showPopup(ViewController.getInstance().createView(token, params));
}
public static void showPopup(final RawView view) {
DOM.getElementById(ViewController.POPUP_DIV_ID).setInnerHTML("");
ViewController.openPopup();
addClosePopupAction(view);
ViewController.showView(view, ViewController.POPUP_DIV_ID);
}
private static void addClosePopupAction(final RawView view) {
final Element popupHeader = DOM.getElementById("popupcontainerheader");
popupHeader.setInnerHTML(""); // To remove button repetition after popup re-opening
popupHeader.appendChild(new Link(new JsId("close_popup"), "Close popup", "Close this popup", view.getClosePopupAction()).getElement());
}
private RawView createView(final String token) {
return this.createView(token, new TreeIndexed<String>());
}
private RawView createView(final String token, final Map<String, String> params) {
return this.createView(token, new TreeIndexed<String>(params));
}
private RawView createView(final String token, final TreeIndexed<String> params) {
RawView page = null;
if (token == ClientApplicationURL.TOKEN_ADD) {
page = new EditItemPage();
} else if (token == ClientApplicationURL.TOKEN_EDIT) {
page = new EditItemPage();
} else if (token == ClientApplicationURL.TOKEN_DELETE) {
page = new DeleteItemPage();
} else if (token == ChangeLangPage.TOKEN) {
page = new ChangeLangPage();
} else {
page = ApplicationFactoryClient.getDefaultFactory().defineViewTokens(token);
}
page.setParameters(params);
return page;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// POPUP
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static native void openPopup() /*-{
$wnd.$.popup.open();
}-*/;
protected static native void updatePopup() /*-{
$wnd.$.popup.update();
}-*/;
public static native void closePopup() /*-{
$wnd.$.popup.close();
}-*/;
public static native boolean hasOpenedPopup() /*-{
return $wnd.$.popup.isOpen();
}-*/;
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// JQUERY+ MAPPER
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static native void updateUI(Element element, boolean force)
/*-{
$wnd.$(element).updateUI(force);
}-*/;
public static native void updateUI(Element element)/*-{
$wnd.$(element).updateUI();
}-*/;
public static native void updateUI(String selector, boolean force)/*-{
$wnd.$(selector).updateUI(force);
}-*/;
public static native void updateUI(String selector)/*-{
$wnd.$(selector).updateUI();
}-*/;
public static native void back()/*-{
$wnd.historyBack();
}-*/;
public void historyBack() {
if (hasOpenedPopup()) {
closePopup();
triggerRefresh();
} else {
back();
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PAGE REFRESH
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void refreshCurrentPage() {
ViewController.getInstance().triggerRefresh();
}
public void registerOnLoadEvent(final AbstractComponent... components) {
for (final AbstractComponent component : components) {
if (!componentsWaitingForLoad.contains(component)) {
componentsWaitingForLoad.add(component);
}
}
}
public void unregisterOnLoadEvent(final AbstractComponent... components) {
for (final AbstractComponent component : components) {
componentsWaitingForLoad.remove(component);
}
}
public void registerOnPageRefreshEvent(final Refreshable... components) {
for (final Refreshable component : components) {
if (!componentsWaitingForRefresh.contains(component)) {
componentsWaitingForRefresh.add(component);
}
}
}
public void unregisterOnPageRefreshEvent(final Refreshable... components) {
for (final Refreshable component : components) {
componentsWaitingForRefresh.remove(component);
}
}
public void triggerLoad() {
for (final AbstractComponent component : componentsWaitingForLoad) {
// if (component instanceof AbstractComponent && !component.isInDom()) {
// this.componentsWaitingForLoad.remove(component);
// continue;
// }
component.triggerLoad();
}
componentsWaitingForLoad.clear();
}
public void triggerRefresh() {
// Clean components that are no longer in the DOM tree
for (int i = 0; i < componentsWaitingForRefresh.size(); i++) {
final Refreshable component = componentsWaitingForRefresh.get(i);
if (component instanceof AbstractComponent && !((AbstractComponent) component).isInDom()) {
componentsWaitingForRefresh.remove(component);
i--;
}
}
// Refresh automatically registered components
if (currentPage.getAllowAutomatedUpdate()) {
for (final Refreshable component : componentsWaitingForRefresh) {
component.refresh();
}
}
// Custom page refresh
currentPage.refresh();
}
}
| true | true | public static RawView showView(final RawView view, final Element rootElement, final TreeIndexed<String> params) {
// Set the parent Element to the view that will be displayed
view.setParentElement(rootElement);
if (ViewController.ROOT_DIV_ID.equals(rootElement.getId())) {
// Reset unseless elements
ViewController.closePopup();
// getInstance().componentsWaitingForRefresh.clear();
getInstance().currentPage = view;
getInstance().setCurrentPageToken(view.getToken());
// Set the URL
if (!BlankPage.TOKEN.equals(view.getToken())) {
ClientApplicationURL.setPageToken(view.getToken(), false);
}
ClientApplicationURL.setPageAttributes(params);
ClientApplicationURL.refreshUrl(false);
}
final CustomPanel widget = view.toWidget();
final Element widgetElement = widget.getElement();
if (!(view instanceof PageOnItem<?>)) {
$(rootElement).empty();
} else {
$(widgetElement).hide();
}
rootElement.appendChild(widgetElement);
widget.onLoad();
ViewController.updateUI(rootElement, true);
MainEventBus.getInstance().fireEventFromSource(new ChangeViewEvent(view), getInstance());
return view;
}
| public static RawView showView(final RawView view, final Element rootElement, final TreeIndexed<String> params) {
// Set the parent Element to the view that will be displayed
view.setParentElement(rootElement);
if (ViewController.ROOT_DIV_ID.equals(rootElement.getId())) {
// Reset unseless elements
ViewController.closePopup();
// getInstance().componentsWaitingForRefresh.clear();
getInstance().currentPage = view;
getInstance().setCurrentPageToken(view.getToken());
// Set the URL
//if (!BlankPage.TOKEN.equals(view.getToken())) {
ClientApplicationURL.setPageToken(view.getToken(), false);
//}
ClientApplicationURL.setPageAttributes(params);
ClientApplicationURL.refreshUrl(false);
}
final CustomPanel widget = view.toWidget();
final Element widgetElement = widget.getElement();
if (!(view instanceof PageOnItem<?>)) {
$(rootElement).empty();
} else {
$(widgetElement).hide();
}
rootElement.appendChild(widgetElement);
widget.onLoad();
ViewController.updateUI(rootElement, true);
MainEventBus.getInstance().fireEventFromSource(new ChangeViewEvent(view), getInstance());
return view;
}
|
diff --git a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/StudyXmlSerializerHelper.java b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/StudyXmlSerializerHelper.java
index d01adf1c4..82c47acd2 100644
--- a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/StudyXmlSerializerHelper.java
+++ b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/StudyXmlSerializerHelper.java
@@ -1,80 +1,80 @@
package edu.northwestern.bioinformatics.studycalendar.xml.writers;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import edu.northwestern.bioinformatics.studycalendar.domain.*;
import edu.northwestern.bioinformatics.studycalendar.domain.tools.TemplateTraversalHelper;
import org.dom4j.Element;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class StudyXmlSerializerHelper {
private ActivitySourceXmlSerializer activitySourceXmlSerializer;
public Element generateSourcesElementWithActivities(Study study) {
Collection<Activity> activities = findAllActivities(study);
Collection<Source> sources = groupActivitiesBySource(activities);
return activitySourceXmlSerializer.createElement(sources);
}
protected Collection<Activity> findAllActivities(Study study) {
Collection<Activity> result = new HashSet<Activity>();
for (PlannedActivity a : TemplateTraversalHelper.findChildren(study.getPlannedCalendar(), PlannedActivity.class)) {
result.add(a.getActivity());
}
for (Parent p : TemplateTraversalHelper.findRootParentNodes(study)) {
for (PlannedActivity a : TemplateTraversalHelper.findChildren(p, PlannedActivity.class)) {
result.add(a.getActivity());
}
}
return result;
}
protected Collection<Source> groupActivitiesBySource(Collection<Activity> all) {
List<Source> result = new ArrayList<Source>();
for (Activity a : all) {
if (!result.contains(a.getSource())) {
result.add(a.getSource().transientClone());
}
Source s = result.get(result.indexOf(a.getSource()));
s.addActivity(a.transientClone());
}
return result;
}
public void replaceActivityReferencesWithCorrespondingDefinitions(Study study, Element eStudy) {
Element eSource = eStudy.element("sources");
if (eSource != null) {
Collection<Source> sources = activitySourceXmlSerializer.readCollectionElement(eSource);
Collection<Activity> activityRefs = findAllActivities(study);
for (Activity ref : activityRefs) {
if (ref.getSource() == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Source is missing for activity reference [code={0}; source=(MISSING)]", ref.getCode()));
}
Source foundSource = ref.getSource().findSourceWhichHasSameName(sources);
Activity foundActivityDef = ref.findActivityInCollectionWhichHasSameCode(foundSource.getActivities());
if (foundActivityDef == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Problem resolving activity reference [code={0}; source={1}]", ref.getCode(), ref.getSource().getName()));
}
ref.updateActivity(foundActivityDef);
- ref.getProperties().clear();
+ ref.setProperties(new ArrayList<ActivityProperty>());
for (ActivityProperty p : (new ArrayList<ActivityProperty>(foundActivityDef.getProperties()))) {
ref.addProperty(p.clone());
}
}
}
}
public void setActivitySourceXmlSerializer(ActivitySourceXmlSerializer activitySourceXmlSerializer) {
this.activitySourceXmlSerializer = activitySourceXmlSerializer;
}
}
| true | true | public void replaceActivityReferencesWithCorrespondingDefinitions(Study study, Element eStudy) {
Element eSource = eStudy.element("sources");
if (eSource != null) {
Collection<Source> sources = activitySourceXmlSerializer.readCollectionElement(eSource);
Collection<Activity> activityRefs = findAllActivities(study);
for (Activity ref : activityRefs) {
if (ref.getSource() == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Source is missing for activity reference [code={0}; source=(MISSING)]", ref.getCode()));
}
Source foundSource = ref.getSource().findSourceWhichHasSameName(sources);
Activity foundActivityDef = ref.findActivityInCollectionWhichHasSameCode(foundSource.getActivities());
if (foundActivityDef == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Problem resolving activity reference [code={0}; source={1}]", ref.getCode(), ref.getSource().getName()));
}
ref.updateActivity(foundActivityDef);
ref.getProperties().clear();
for (ActivityProperty p : (new ArrayList<ActivityProperty>(foundActivityDef.getProperties()))) {
ref.addProperty(p.clone());
}
}
}
}
| public void replaceActivityReferencesWithCorrespondingDefinitions(Study study, Element eStudy) {
Element eSource = eStudy.element("sources");
if (eSource != null) {
Collection<Source> sources = activitySourceXmlSerializer.readCollectionElement(eSource);
Collection<Activity> activityRefs = findAllActivities(study);
for (Activity ref : activityRefs) {
if (ref.getSource() == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Source is missing for activity reference [code={0}; source=(MISSING)]", ref.getCode()));
}
Source foundSource = ref.getSource().findSourceWhichHasSameName(sources);
Activity foundActivityDef = ref.findActivityInCollectionWhichHasSameCode(foundSource.getActivities());
if (foundActivityDef == null) {
throw new StudyCalendarValidationException(MessageFormat.format("Problem resolving activity reference [code={0}; source={1}]", ref.getCode(), ref.getSource().getName()));
}
ref.updateActivity(foundActivityDef);
ref.setProperties(new ArrayList<ActivityProperty>());
for (ActivityProperty p : (new ArrayList<ActivityProperty>(foundActivityDef.getProperties()))) {
ref.addProperty(p.clone());
}
}
}
}
|
diff --git a/src/main/java/org/dynmap/PlayerFaces.java b/src/main/java/org/dynmap/PlayerFaces.java
index 470d1038..19210b72 100644
--- a/src/main/java/org/dynmap/PlayerFaces.java
+++ b/src/main/java/org/dynmap/PlayerFaces.java
@@ -1,139 +1,144 @@
package org.dynmap;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Type;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.dynmap.MapType.ImageFormat;
import org.dynmap.debug.Debug;
import org.dynmap.utils.DynmapBufferedImage;
import org.dynmap.utils.FileLockManager;
/**
* Listen for player logins, and process player faces by fetching skins *
*/
public class PlayerFaces {
private DynmapPlugin plugin;
private File facesdir;
private File faces8x8dir;
private File faces16x16dir;
private File faces32x32dir;
private class LoadPlayerImages implements Runnable {
public String playername;
public LoadPlayerImages(String playername) {
this.playername = playername;
}
public void run() {
BufferedImage img = null;
try {
URL url = new URL("http://s3.amazonaws.com/MinecraftSkins/" + playername + ".png");
img = ImageIO.read(url); /* Load skin for player */
} catch (IOException iox) {
Debug.debug("Error loading skin for '" + playername + "' - " + iox);
}
if(img == null) {
try {
InputStream in = getClass().getResourceAsStream("/char.png");
img = ImageIO.read(in); /* Load generic skin for player */
in.close();
} catch (IOException iox) {
Debug.debug("Error loading default skin for '" + playername + "' - " + iox);
}
}
if(img == null) { /* No image to process? Quit */
return;
}
int[] faceaccessory = new int[64]; /* 8x8 of face accessory */
/* Get buffered image for face at 8x8 */
DynmapBufferedImage face8x8 = DynmapBufferedImage.allocateBufferedImage(8, 8);
- int[] bgcolor = new int[1];
- img.getRGB(0, 0, 1, 1, bgcolor, 0, 1); /* Get BG color (for accessory face) */
img.getRGB(8, 8, 8, 8, face8x8.argb_buf, 0, 8); /* Read face from image */
img.getRGB(40, 8, 8, 8, faceaccessory, 0, 8); /* Read face accessory from image */
- /* Apply accessory to face: first element is transparency color so only ones not matching it */
+ /* Apply accessory to face: see if anything is transparent (if so, apply accessory */
+ boolean transp = false;
for(int i = 0; i < 64; i++) {
- if(faceaccessory[i] != bgcolor[0])
- face8x8.argb_buf[i] = faceaccessory[i];
- else if(face8x8.argb_buf[i] == bgcolor[0])
- face8x8.argb_buf[i] = 0;
+ if((faceaccessory[i] & 0xFF000000) == 0) {
+ transp = true;
+ break;
+ }
+ }
+ if(transp) {
+ for(int i = 0; i < 64; i++) {
+ if((faceaccessory[i] & 0xFF000000) != 0)
+ face8x8.argb_buf[i] = faceaccessory[i];
+ }
}
/* Write 8x8 file */
File img_8x8 = new File(faces8x8dir, playername + ".png");
FileLockManager.getWriteLock(img_8x8);
try {
FileLockManager.imageIOWrite(face8x8.buf_img, ImageFormat.FORMAT_PNG, img_8x8);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_8x8.getPath());
}
FileLockManager.releaseWriteLock(img_8x8);
/* Make 16x16 version */
DynmapBufferedImage face16x16 = DynmapBufferedImage.allocateBufferedImage(16, 16);
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
face16x16.argb_buf[i*16+j] = face8x8.argb_buf[(i/2)*8 + (j/2)];
}
}
/* Write 16x16 file */
File img_16x16 = new File(faces16x16dir, playername + ".png");
FileLockManager.getWriteLock(img_16x16);
try {
FileLockManager.imageIOWrite(face16x16.buf_img, ImageFormat.FORMAT_PNG, img_16x16);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_16x16.getPath());
}
FileLockManager.releaseWriteLock(img_16x16);
DynmapBufferedImage.freeBufferedImage(face16x16);
/* Make 32x32 version */
DynmapBufferedImage face32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32);
for(int i = 0; i < 32; i++) {
for(int j = 0; j < 32; j++) {
face32x32.argb_buf[i*32+j] = face8x8.argb_buf[(i/4)*8 + (j/4)];
}
}
/* Write 32x32 file */
File img_32x32 = new File(faces32x32dir, playername + ".png");
FileLockManager.getWriteLock(img_32x32);
try {
FileLockManager.imageIOWrite(face32x32.buf_img, ImageFormat.FORMAT_PNG, img_32x32);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_32x32.getPath());
}
FileLockManager.releaseWriteLock(img_32x32);
DynmapBufferedImage.freeBufferedImage(face32x32);
DynmapBufferedImage.freeBufferedImage(face8x8);
/* TODO: signal update for player icon to client */
}
}
private class LoginListener extends PlayerListener {
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
MapManager.scheduleDelayedJob(new LoadPlayerImages(event.getPlayer().getName()), 0);
}
}
public PlayerFaces(DynmapPlugin plugin) {
this.plugin = plugin;
plugin.registerEvent(Type.PLAYER_LOGIN, new LoginListener());
facesdir = new File(plugin.tilesDirectory, "faces");
facesdir.mkdirs(); /* Make sure directory exists */
faces8x8dir = new File(facesdir, "8x8");
faces8x8dir.mkdirs();
faces16x16dir = new File(facesdir, "16x16");
faces16x16dir.mkdirs();
faces32x32dir = new File(facesdir, "32x32");
faces32x32dir.mkdirs();
}
}
| false | true | public void run() {
BufferedImage img = null;
try {
URL url = new URL("http://s3.amazonaws.com/MinecraftSkins/" + playername + ".png");
img = ImageIO.read(url); /* Load skin for player */
} catch (IOException iox) {
Debug.debug("Error loading skin for '" + playername + "' - " + iox);
}
if(img == null) {
try {
InputStream in = getClass().getResourceAsStream("/char.png");
img = ImageIO.read(in); /* Load generic skin for player */
in.close();
} catch (IOException iox) {
Debug.debug("Error loading default skin for '" + playername + "' - " + iox);
}
}
if(img == null) { /* No image to process? Quit */
return;
}
int[] faceaccessory = new int[64]; /* 8x8 of face accessory */
/* Get buffered image for face at 8x8 */
DynmapBufferedImage face8x8 = DynmapBufferedImage.allocateBufferedImage(8, 8);
int[] bgcolor = new int[1];
img.getRGB(0, 0, 1, 1, bgcolor, 0, 1); /* Get BG color (for accessory face) */
img.getRGB(8, 8, 8, 8, face8x8.argb_buf, 0, 8); /* Read face from image */
img.getRGB(40, 8, 8, 8, faceaccessory, 0, 8); /* Read face accessory from image */
/* Apply accessory to face: first element is transparency color so only ones not matching it */
for(int i = 0; i < 64; i++) {
if(faceaccessory[i] != bgcolor[0])
face8x8.argb_buf[i] = faceaccessory[i];
else if(face8x8.argb_buf[i] == bgcolor[0])
face8x8.argb_buf[i] = 0;
}
/* Write 8x8 file */
File img_8x8 = new File(faces8x8dir, playername + ".png");
FileLockManager.getWriteLock(img_8x8);
try {
FileLockManager.imageIOWrite(face8x8.buf_img, ImageFormat.FORMAT_PNG, img_8x8);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_8x8.getPath());
}
FileLockManager.releaseWriteLock(img_8x8);
/* Make 16x16 version */
DynmapBufferedImage face16x16 = DynmapBufferedImage.allocateBufferedImage(16, 16);
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
face16x16.argb_buf[i*16+j] = face8x8.argb_buf[(i/2)*8 + (j/2)];
}
}
/* Write 16x16 file */
File img_16x16 = new File(faces16x16dir, playername + ".png");
FileLockManager.getWriteLock(img_16x16);
try {
FileLockManager.imageIOWrite(face16x16.buf_img, ImageFormat.FORMAT_PNG, img_16x16);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_16x16.getPath());
}
FileLockManager.releaseWriteLock(img_16x16);
DynmapBufferedImage.freeBufferedImage(face16x16);
/* Make 32x32 version */
DynmapBufferedImage face32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32);
for(int i = 0; i < 32; i++) {
for(int j = 0; j < 32; j++) {
face32x32.argb_buf[i*32+j] = face8x8.argb_buf[(i/4)*8 + (j/4)];
}
}
/* Write 32x32 file */
File img_32x32 = new File(faces32x32dir, playername + ".png");
FileLockManager.getWriteLock(img_32x32);
try {
FileLockManager.imageIOWrite(face32x32.buf_img, ImageFormat.FORMAT_PNG, img_32x32);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_32x32.getPath());
}
FileLockManager.releaseWriteLock(img_32x32);
DynmapBufferedImage.freeBufferedImage(face32x32);
DynmapBufferedImage.freeBufferedImage(face8x8);
/* TODO: signal update for player icon to client */
}
| public void run() {
BufferedImage img = null;
try {
URL url = new URL("http://s3.amazonaws.com/MinecraftSkins/" + playername + ".png");
img = ImageIO.read(url); /* Load skin for player */
} catch (IOException iox) {
Debug.debug("Error loading skin for '" + playername + "' - " + iox);
}
if(img == null) {
try {
InputStream in = getClass().getResourceAsStream("/char.png");
img = ImageIO.read(in); /* Load generic skin for player */
in.close();
} catch (IOException iox) {
Debug.debug("Error loading default skin for '" + playername + "' - " + iox);
}
}
if(img == null) { /* No image to process? Quit */
return;
}
int[] faceaccessory = new int[64]; /* 8x8 of face accessory */
/* Get buffered image for face at 8x8 */
DynmapBufferedImage face8x8 = DynmapBufferedImage.allocateBufferedImage(8, 8);
img.getRGB(8, 8, 8, 8, face8x8.argb_buf, 0, 8); /* Read face from image */
img.getRGB(40, 8, 8, 8, faceaccessory, 0, 8); /* Read face accessory from image */
/* Apply accessory to face: see if anything is transparent (if so, apply accessory */
boolean transp = false;
for(int i = 0; i < 64; i++) {
if((faceaccessory[i] & 0xFF000000) == 0) {
transp = true;
break;
}
}
if(transp) {
for(int i = 0; i < 64; i++) {
if((faceaccessory[i] & 0xFF000000) != 0)
face8x8.argb_buf[i] = faceaccessory[i];
}
}
/* Write 8x8 file */
File img_8x8 = new File(faces8x8dir, playername + ".png");
FileLockManager.getWriteLock(img_8x8);
try {
FileLockManager.imageIOWrite(face8x8.buf_img, ImageFormat.FORMAT_PNG, img_8x8);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_8x8.getPath());
}
FileLockManager.releaseWriteLock(img_8x8);
/* Make 16x16 version */
DynmapBufferedImage face16x16 = DynmapBufferedImage.allocateBufferedImage(16, 16);
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
face16x16.argb_buf[i*16+j] = face8x8.argb_buf[(i/2)*8 + (j/2)];
}
}
/* Write 16x16 file */
File img_16x16 = new File(faces16x16dir, playername + ".png");
FileLockManager.getWriteLock(img_16x16);
try {
FileLockManager.imageIOWrite(face16x16.buf_img, ImageFormat.FORMAT_PNG, img_16x16);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_16x16.getPath());
}
FileLockManager.releaseWriteLock(img_16x16);
DynmapBufferedImage.freeBufferedImage(face16x16);
/* Make 32x32 version */
DynmapBufferedImage face32x32 = DynmapBufferedImage.allocateBufferedImage(32, 32);
for(int i = 0; i < 32; i++) {
for(int j = 0; j < 32; j++) {
face32x32.argb_buf[i*32+j] = face8x8.argb_buf[(i/4)*8 + (j/4)];
}
}
/* Write 32x32 file */
File img_32x32 = new File(faces32x32dir, playername + ".png");
FileLockManager.getWriteLock(img_32x32);
try {
FileLockManager.imageIOWrite(face32x32.buf_img, ImageFormat.FORMAT_PNG, img_32x32);
} catch (IOException iox) {
Log.severe("Cannot write player icon " + img_32x32.getPath());
}
FileLockManager.releaseWriteLock(img_32x32);
DynmapBufferedImage.freeBufferedImage(face32x32);
DynmapBufferedImage.freeBufferedImage(face8x8);
/* TODO: signal update for player icon to client */
}
|
diff --git a/src/lib/com/izforge/izpack/installer/Unpacker.java b/src/lib/com/izforge/izpack/installer/Unpacker.java
index ca071d6c..efe82474 100644
--- a/src/lib/com/izforge/izpack/installer/Unpacker.java
+++ b/src/lib/com/izforge/izpack/installer/Unpacker.java
@@ -1,606 +1,606 @@
/*
* $Id$
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2001 Johannes Lehtinen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.installer;
import com.izforge.izpack.*;
import com.izforge.izpack.event.InstallerListener;
import com.izforge.izpack.util.*;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Pack200;
/**
* Unpacker class.
*
* @author Julien Ponge
* @author Johannes Lehtinen
*/
public class Unpacker extends UnpackerBase
{
private static final String tempSubPath = "/IzpackWebTemp";
private Pack200.Unpacker unpacker;
/**
* The constructor.
*
* @param idata The installation data.
* @param handler The installation progress handler.
*/
public Unpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler)
{
super(idata, handler);
}
/* (non-Javadoc)
* @see com.izforge.izpack.installer.IUnpacker#run()
*/
public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
String message = err.getMessage();
if ("Installation cancelled".equals(message))
{
handler.emitNotification("Installation cancelled");
}
else
{
- if (message == null || message.isEmpty())
+ if (message == null || "".equals(message))
{
message = "Internal error occured : " + err.toString();
}
handler.emitError("An error occured", message);
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
private Pack200.Unpacker getPack200Unpacker()
{
if (unpacker == null)
{
unpacker = Pack200.newUnpacker();
}
return unpacker;
}
/**
* Returns a stream to a pack, location depending on if it's web based.
*
* @param uninstall true if pack must be uninstalled
* @return The stream or null if it could not be found.
* @throws Exception Description of the Exception
*/
private InputStream getPackAsStream(String packid, boolean uninstall) throws Exception
{
InputStream in = null;
String webDirURL = idata.info.getWebDirURL();
packid = "-" + packid;
if (webDirURL == null) // local
{
in = Unpacker.class.getResourceAsStream("/packs/pack" + packid);
}
else
// web based
{
// TODO: Look first in same directory as primary jar
// This may include prompting for changing of media
// TODO: download and cache them all before starting copy process
// See compiler.Packager#getJarOutputStream for the counterpart
String baseName = idata.info.getInstallerBase();
String packURL = webDirURL + "/" + baseName + ".pack" + packid + ".jar";
String tf = IoHelper.translatePath(idata.info.getUninstallerPath()+ Unpacker.tempSubPath, vs);
String tempfile;
try
{
tempfile = WebRepositoryAccessor.getCachedUrl(packURL, tf);
udata.addFile(tempfile, uninstall);
}
catch (Exception e)
{
if ("Cancelled".equals(e.getMessage()))
{
throw new InstallerException("Installation cancelled", e);
}
else
{
throw new InstallerException("Installation failed", e);
}
}
URL url = new URL("jar:" + tempfile + "!/packs/pack" + packid);
//URL url = new URL("jar:" + packURL + "!/packs/pack" + packid);
// JarURLConnection jarConnection = (JarURLConnection)
// url.openConnection();
// TODO: what happens when using an automated installer?
in = new WebAccessor(null).openInputStream(url);
// TODO: Fails miserably when pack jars are not found, so this is
// temporary
if (in == null)
{
throw new InstallerException(url.toString() + " not available", new FileNotFoundException(url.toString()));
}
}
if (in != null && idata.info.getPackDecoderClassName() != null)
{
Class<Object> decoder = (Class<Object>) Class.forName(idata.info.getPackDecoderClassName());
Class[] paramsClasses = new Class[1];
paramsClasses[0] = Class.forName("java.io.InputStream");
Constructor<Object> constructor = decoder.getDeclaredConstructor(paramsClasses);
// Our first used decoder input stream (bzip2) reads byte for byte from
// the source. Therefore we put a buffering stream between it and the
// source.
InputStream buffer = new BufferedInputStream(in);
Object[] params = {buffer};
Object instance = null;
instance = constructor.newInstance(params);
if (!InputStream.class.isInstance(instance))
{
throw new InstallerException("'" + idata.info.getPackDecoderClassName()
+ "' must be derived from "
+ InputStream.class.toString());
}
in = (InputStream) instance;
}
return in;
}
}
| true | true | public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
String message = err.getMessage();
if ("Installation cancelled".equals(message))
{
handler.emitNotification("Installation cancelled");
}
else
{
if (message == null || message.isEmpty())
{
message = "Internal error occured : " + err.toString();
}
handler.emitError("An error occured", message);
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
| public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
String message = err.getMessage();
if ("Installation cancelled".equals(message))
{
handler.emitNotification("Installation cancelled");
}
else
{
if (message == null || "".equals(message))
{
message = "Internal error occured : " + err.toString();
}
handler.emitError("An error occured", message);
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
|
diff --git a/backend/src/com/mymed/controller/core/manager/AbstractManager.java b/backend/src/com/mymed/controller/core/manager/AbstractManager.java
index d4fbb9cb5..1e22cd75f 100644
--- a/backend/src/com/mymed/controller/core/manager/AbstractManager.java
+++ b/backend/src/com/mymed/controller/core/manager/AbstractManager.java
@@ -1,293 +1,273 @@
/*
* Copyright 2012 INRIA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mymed.controller.core.manager;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import ch.qos.logback.classic.Logger;
import com.mymed.controller.core.exception.InternalBackEndException;
import com.mymed.controller.core.manager.storage.IStorageManager;
import com.mymed.model.data.AbstractMBean;
import com.mymed.properties.IProperties;
import com.mymed.properties.PropType;
import com.mymed.properties.PropertiesManager;
import com.mymed.utils.ClassType;
import com.mymed.utils.MLogger;
/**
* Abstract manager the all the managers should extend.
* <p>
* This manager provides the basic operation to recreate a bean object.
*
* @author lvanni
* @author Milo Casagrande
*/
public abstract class AbstractManager {
/**
* Default value for the 403 HTTP error code.
*/
public static final int ERROR_FORBIDDEN = 403;
/**
* Default value for the 404 HTTP error code.
*/
public static final int ERROR_NOT_FOUND = 404;
/**
* Default value for the 409 HTTP error code.
*/
public static final int ERROR_CONFLICT = 409;
/**
* The default storage manager.
*/
protected IStorageManager storageManager;
/**
* The default logger to be used.
*/
protected static final Logger LOGGER = MLogger.getLogger();
/**
* The default properties manager.
*/
private static final PropertiesManager PROPERTIES = PropertiesManager.getInstance();
/**
* General properties about mymed.
*/
protected static final IProperties GENERAL = PROPERTIES.getManager(PropType.GENERAL);
/**
* Properties values for the columns in the data structure.
*/
protected static final IProperties COLUMNS = PROPERTIES.getManager(PropType.COLUMNS);
/**
* Common error strings.
*/
protected static final IProperties ERRORS = PROPERTIES.getManager(PropType.ERRORS);
/**
* Fields of the various beans/objects.
*/
protected static final IProperties FIELDS = PROPERTIES.getManager(PropType.FIELDS);
/**
* This is the URL address of the server, necessary for configuring data across all the backend. If nothing has been
* set at compile time, the default value is an empty string.
*/
private static final String DEFAULT_SERVER_URI = PROPERTIES.getManager(PropType.GENERAL).get("general.server.uri");
/**
* The protocol used for communications. This is the default value provided via the properties.
*/
private static final String DEFAULT_SERVER_PROTOCOL = PROPERTIES.getManager(PropType.GENERAL).get(
"general.server.protocol");
/**
* This is the server URI as to be used in the backend.
*/
private String SERVER_URI;
/**
* The protocol used for communications: should be 'http://' or 'https://'.
*/
private final String SERVER_PROTOCOL;
/**
* Default error string for encoding exceptions.
*/
protected static final String ERROR_ENCODING = ERRORS.get("error.encoding");
/**
* Value of the private modifiers (for introspection).
*/
private static final int PRIV = Modifier.PRIVATE;
private String table;
/**
* Default constructor.
*
* @param storageManager
*/
public AbstractManager(final IStorageManager storageManager) {
this.storageManager = storageManager;
// Set a default global URI to be used by the backend, if we cannot get the host name
// we fallback to use localhost.
if ("".equals(DEFAULT_SERVER_URI)) {
try {
SERVER_URI = InetAddress.getLocalHost().getCanonicalHostName();
} catch (final UnknownHostException ex) {
LOGGER.debug("Error retrieving host name of the machine, falling back to 'localhost'", ex);
SERVER_URI = "localhost"; // NOPMD
}
} else {
SERVER_URI = DEFAULT_SERVER_URI;
}
// We do not trust what users write on the command line
SERVER_PROTOCOL = DEFAULT_SERVER_PROTOCOL.split(":")[0] + "://";
}
public AbstractManager(String table, final IStorageManager storageManager) {
this(storageManager);
this.table = table;
}
public Map<String, String> fetch(String id){
return storageManager.selectAllStr(table, id);
}
/**
* Introspection
*
* @param clazz
* the class to introspect
* @param args
* the values of the class fields
* @return an object of the defined clazz
* @throws InternalBackEndException
*/
public AbstractMBean introspection(final Class<? extends AbstractMBean> clazz, final Map<byte[], byte[]> args)
throws InternalBackEndException {
AbstractMBean mbean = null;
String fieldName = "";
// We create a new instance of the object we are reflecting on
Constructor<?> ctor;
try {
ctor = clazz.getConstructor();
mbean = (AbstractMBean) ctor.newInstance();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
+ } catch (Exception e) {
+ throw new InternalBackEndException(e);
}
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
fieldName = com.mymed.utils.MConverter.byteArrayToString(arg.getKey());
final Field field = clazz.getDeclaredField(fieldName);
/*
* We check the value of the modifiers of the field: if the field is private and final, or private
* static and final, we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers != PRIV) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = clazz.getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
- } catch (final NoSuchFieldException e) {
- LOGGER.info("WARNING: {} is not a bean field", fieldName);
- } catch (final SecurityException ex) {
- throw new InternalBackEndException(ex);
- } catch (final NoSuchMethodException ex) {
- throw new InternalBackEndException(ex);
- } catch (final IllegalArgumentException ex) {
- throw new InternalBackEndException(ex);
- } catch (final IllegalAccessException ex) {
- throw new InternalBackEndException(ex);
- } catch (final InvocationTargetException ex) {
- throw new InternalBackEndException(ex);
+ } catch (final Exception e) {
+ LOGGER.info("WARNING: {} error with field", fieldName);
}
}
return mbean;
}
/**
* Create the name of the setter method based on the field name and its class.
* <p>
* This is particularly useful due to the fact that boolean fields do not have a normal setter name.
*
* @param field
* the filed we want the setter method of
* @param classType
* the class type of the field
* @return the name of the setter method
*/
private String createSetterName(final Field field, final ClassType classType) {
final StringBuilder setterName = new StringBuilder(20);
final String fieldName = field.getName();
setterName.append("set");
String subName = fieldName;
/*
* Check that the boolean field we are on does start with 'is'. This should be the default prefix for boolean
* fields. In this case the setter method will be based on the field name, but without the 'is' prefix.
*/
if (classType.equals(ClassType.BOOL) && fieldName.startsWith("is")) {
subName = fieldName.substring(2, fieldName.length());
}
setterName.append(subName.substring(0, 1).toUpperCase(Locale.US));
setterName.append(subName.substring(1));
setterName.trimToSize();
return setterName.toString();
}
/**
* Retrieves the server URI as defined at build time.
*
* @return the server URI to use
*/
public String getServerURI() {
return SERVER_URI;
}
/**
* Retrieves the server protocol as defined at build time.
*
* @return the server protocol to use
*/
public String getServerProtocol() {
return SERVER_PROTOCOL;
}
}
| false | true | public AbstractMBean introspection(final Class<? extends AbstractMBean> clazz, final Map<byte[], byte[]> args)
throws InternalBackEndException {
AbstractMBean mbean = null;
String fieldName = "";
// We create a new instance of the object we are reflecting on
Constructor<?> ctor;
try {
ctor = clazz.getConstructor();
mbean = (AbstractMBean) ctor.newInstance();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
fieldName = com.mymed.utils.MConverter.byteArrayToString(arg.getKey());
final Field field = clazz.getDeclaredField(fieldName);
/*
* We check the value of the modifiers of the field: if the field is private and final, or private
* static and final, we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers != PRIV) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = clazz.getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
} catch (final NoSuchFieldException e) {
LOGGER.info("WARNING: {} is not a bean field", fieldName);
} catch (final SecurityException ex) {
throw new InternalBackEndException(ex);
} catch (final NoSuchMethodException ex) {
throw new InternalBackEndException(ex);
} catch (final IllegalArgumentException ex) {
throw new InternalBackEndException(ex);
} catch (final IllegalAccessException ex) {
throw new InternalBackEndException(ex);
} catch (final InvocationTargetException ex) {
throw new InternalBackEndException(ex);
}
}
return mbean;
}
| public AbstractMBean introspection(final Class<? extends AbstractMBean> clazz, final Map<byte[], byte[]> args)
throws InternalBackEndException {
AbstractMBean mbean = null;
String fieldName = "";
// We create a new instance of the object we are reflecting on
Constructor<?> ctor;
try {
ctor = clazz.getConstructor();
mbean = (AbstractMBean) ctor.newInstance();
} catch (Exception e) {
throw new InternalBackEndException(e);
}
for (final Entry<byte[], byte[]> arg : args.entrySet()) {
try {
fieldName = com.mymed.utils.MConverter.byteArrayToString(arg.getKey());
final Field field = clazz.getDeclaredField(fieldName);
/*
* We check the value of the modifiers of the field: if the field is private and final, or private
* static and final, we skip it.
*/
final int modifiers = field.getModifiers();
if (modifiers != PRIV) {
continue;
}
final ClassType classType = ClassType.inferType(field.getGenericType());
final String setterName = createSetterName(field, classType);
final Method method = clazz.getMethod(setterName, classType.getPrimitiveType());
final Object argument = ClassType.objectFromClassType(classType, arg.getValue());
method.invoke(mbean, argument);
} catch (final Exception e) {
LOGGER.info("WARNING: {} error with field", fieldName);
}
}
return mbean;
}
|
diff --git a/simulator/code/simulator/elevatorcontrol/DriveControl.java b/simulator/code/simulator/elevatorcontrol/DriveControl.java
index 5e9024d..d1315b8 100644
--- a/simulator/code/simulator/elevatorcontrol/DriveControl.java
+++ b/simulator/code/simulator/elevatorcontrol/DriveControl.java
@@ -1,369 +1,370 @@
/* 18649 Fall 2012
* (Group 17)
* Jesse Salazar (jessesal)
* Rajeev Sharma (rdsharma)
* Collin Buchan (cbuchan)
* Jessica Tiu (jtiu) - Author
* Last modified: 2012-Nov-03
*/
package simulator.elevatorcontrol;
import jSimPack.SimTime;
import simulator.elevatorcontrol.Utility.AtFloorArray;
import simulator.elevatorcontrol.Utility.CommitPointCalculator;
import simulator.elevatorcontrol.Utility.DoorClosedHallwayArray;
import simulator.elevatormodules.CarWeightCanPayloadTranslator;
import simulator.elevatormodules.DriveObject;
import simulator.elevatormodules.LevelingCanPayloadTranslator;
import simulator.framework.*;
import simulator.payloads.CanMailbox;
import simulator.payloads.CanMailbox.ReadableCanMailbox;
import simulator.payloads.CanMailbox.WriteableCanMailbox;
import simulator.payloads.DrivePayload;
import simulator.payloads.DrivePayload.WriteableDrivePayload;
import simulator.payloads.DriveSpeedPayload;
import simulator.payloads.DriveSpeedPayload.ReadableDriveSpeedPayload;
/**
* There is one DriveControl, which controls the elevator Drive
* (the main motor moving Car Up and Down). For simplicity we will assume
* this node never fails, although the system could be implemented with
* two such nodes, one per each of the Drive windings.
*
* @author Jessica Tiu
*/
public class DriveControl extends Controller {
/**
* ************************************************************************
* Declarations
* ************************************************************************
*/
//note that inputs are Readable objects, while outputs are Writeable objects
//local physical state
private WriteableDrivePayload localDrive;
private ReadableDriveSpeedPayload localDriveSpeed;
//output network messages
private WriteableCanMailbox networkDriveOut;
private WriteableCanMailbox networkDriveSpeedOut;
//translators for output network messages
private DriveCommandCanPayloadTranslator mDrive;
private DriveSpeedCanPayloadTranslator mDriveSpeed;
//input network messages
private ReadableCanMailbox networkLevelUp;
private ReadableCanMailbox networkLevelDown;
private ReadableCanMailbox networkEmergencyBrake;
private ReadableCanMailbox networkCarWeight;
private ReadableCanMailbox networkDesiredFloor;
//private ReadableCanMailbox networkCarLevelPosition;
private DoorClosedHallwayArray networkDoorClosedFront;
private DoorClosedHallwayArray networkDoorClosedBack;
private AtFloorArray networkAtFloorArray;
private CommitPointCalculator networkCommitPoint;
//translators for input network messages
private LevelingCanPayloadTranslator mLevelUp;
private LevelingCanPayloadTranslator mLevelDown;
private TinyBooleanCanPayloadTranslator mEmergencyBrake;
private CarWeightCanPayloadTranslator mCarWeight;
private DesiredFloorCanPayloadTranslator mDesiredFloor;
//private CarLevelPositionCanPayloadTranslator mCarLevelPosition;
//store the period for the controller
private SimTime period;
//enumerate states
private enum State {
STATE_DRIVE_STOPPED,
STATE_DRIVE_LEVEL,
STATE_DRIVE_SLOW,
STATE_DRIVE_FAST,
}
//state variable initialized to the initial state DRIVE_STOPPED
private State state = State.STATE_DRIVE_STOPPED;
private Direction driveDir = Direction.UP;
/**
* The arguments listed in the .cf configuration file should match the order and
* type given here.
* <p/>
* For your elevator controllers, you should make sure that the constructor matches
* the method signatures in ControllerBuilder.makeAll().
* <p/>
* controllers.add(createControllerObject("DriveControl",
* MessageDictionary.DRIVE_CONTROL_PERIOD, verbose));
*/
public DriveControl(SimTime period, boolean verbose) {
//call to the Controller superclass constructor is required
super("DriveControl", verbose);
this.period = period;
/*
* The log() method is inherited from the Controller class. It takes an
* array of objects which will be converted to strings and concatenated
* only if the log message is actually written.
*
* For performance reasons, call with comma-separated lists, e.g.:
* log("object=",object);
* Do NOT call with concatenated objects like:
* log("object=" + object);
*/
log("Created DriveControl with period = ", period);
//payloads
localDrive = DrivePayload.getWriteablePayload(); //output
localDriveSpeed = DriveSpeedPayload.getReadablePayload(); //input
physicalInterface.sendTimeTriggered(localDrive, period);
physicalInterface.registerTimeTriggered(localDriveSpeed);
//output network messages
networkDriveOut = CanMailbox.getWriteableCanMailbox(MessageDictionary.DRIVE_COMMAND_CAN_ID);
networkDriveSpeedOut = CanMailbox.getWriteableCanMailbox(MessageDictionary.DRIVE_SPEED_CAN_ID);
mDrive = new DriveCommandCanPayloadTranslator(networkDriveOut);
mDriveSpeed = new DriveSpeedCanPayloadTranslator(networkDriveSpeedOut);
canInterface.sendTimeTriggered(networkDriveOut, period);
canInterface.sendTimeTriggered(networkDriveSpeedOut, period);
//input network messages
networkLevelUp =
CanMailbox.getReadableCanMailbox(MessageDictionary.LEVELING_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(Direction.UP));
networkLevelDown =
CanMailbox.getReadableCanMailbox(MessageDictionary.LEVELING_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(Direction.DOWN));
networkEmergencyBrake =
CanMailbox.getReadableCanMailbox(MessageDictionary.EMERGENCY_BRAKE_CAN_ID);
networkCarWeight =
CanMailbox.getReadableCanMailbox(MessageDictionary.CAR_WEIGHT_CAN_ID);
networkDesiredFloor =
CanMailbox.getReadableCanMailbox(MessageDictionary.DESIRED_FLOOR_CAN_ID);
//networkCarLevelPosition =
// CanMailbox.getReadableCanMailbox(MessageDictionary.CAR_POSITION_CAN_ID);
networkDoorClosedFront = new Utility.DoorClosedHallwayArray(Hallway.FRONT, canInterface);
networkDoorClosedBack = new Utility.DoorClosedHallwayArray(Hallway.BACK, canInterface);
networkAtFloorArray = new Utility.AtFloorArray(canInterface);
networkCommitPoint = new Utility.CommitPointCalculator(canInterface);
mLevelUp =
new LevelingCanPayloadTranslator(networkLevelUp, Direction.UP);
mLevelDown =
new LevelingCanPayloadTranslator(networkLevelDown, Direction.DOWN);
mEmergencyBrake =
new TinyBooleanCanPayloadTranslator(networkEmergencyBrake);
mCarWeight =
new CarWeightCanPayloadTranslator(networkCarWeight);
// used to calculate desiredDir
mDesiredFloor =
new DesiredFloorCanPayloadTranslator(networkDesiredFloor);
//mCarLevelPosition =
// new CarLevelPositionCanPayloadTranslator(networkCarLevelPosition);
canInterface.registerTimeTriggered(networkLevelUp);
canInterface.registerTimeTriggered(networkLevelDown);
canInterface.registerTimeTriggered(networkEmergencyBrake);
canInterface.registerTimeTriggered(networkCarWeight);
canInterface.registerTimeTriggered(networkDesiredFloor);
//canInterface.registerTimeTriggered(networkCarLevelPosition);
/* issuing the timer start method with no callback data means a NULL value
* will be passed to the callback later. Use the callback data to distinguish
* callbacks from multiple calls to timer.start() (e.g. if you have multiple
* timers.
*/
timer.start(period);
}
public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DRIVE_STOPPED:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_STOPPED
localDrive.set(Speed.STOP, Direction.STOP);
mDrive.set(Speed.STOP, Direction.STOP);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//log("localDrive="+localDrive.speed()+", "+localDrive.direction());
//log("localDriveSpeed="+localDriveSpeed.speed()+", "+localDriveSpeed.direction());
//log("mDriveSpeed="+mDriveSpeed.getSpeed()+", "+mDriveSpeed.getDirection());
//transitions
//#transition 'T6.1'
// if (driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) {
// newState = State.STATE_DRIVE_LEVEL;
// }
if ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) ||
(mCarWeight.getWeight() >= Elevator.MaxCarCapacity && (!mLevelUp.getValue() || !mLevelDown.getValue()))) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.3'
else if (driveDir != Direction.STOP
&& networkDoorClosedFront.getAllClosed() && networkDoorClosedBack.getAllClosed()
&& !mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_SLOW;
} else newState = state;
break;
case STATE_DRIVE_LEVEL:
driveDir = getDriveDir(driveDir);
Direction levelDir = getLevelDir();
//state actions for DRIVE_LEVEL
localDrive.set(Speed.LEVEL, levelDir);
mDrive.set(Speed.LEVEL, levelDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.2'
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue()
- || mEmergencyBrake.getValue()) {
+ && localDriveSpeed.speed() <= 0.05 || mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_SLOW:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_SLOW
localDrive.set(Speed.SLOW, driveDir);
mDrive.set(Speed.SLOW, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue() &&
localDriveSpeed.speed() < DriveObject.SlowSpeed) {
newState = State.STATE_DRIVE_STOPPED;
}
//#transition 'T6.4'
- if ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue())
- && !mEmergencyBrake.getValue()) || mCarWeight.getWeight() >= Elevator.MaxCarCapacity) {
+ if (localDriveSpeed.speed() <= 0.25 && ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue())
+ && !mEmergencyBrake.getValue()) || mCarWeight.getWeight() >= Elevator.MaxCarCapacity)) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.5'
else if (driveDir != Direction.STOP
&& !(localDriveSpeed.speed() < DriveObject.SlowSpeed) //********** finished accelerating
&& !networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())) {
newState = State.STATE_DRIVE_FAST;
}
//#transition 'T6.7'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_FAST:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_FAST
localDrive.set(Speed.FAST, driveDir);
mDrive.set(Speed.FAST, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.6'
- if (driveDir != Direction.STOP
+ if ( (driveDir != Direction.STOP
&& networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())
+ && !mEmergencyBrake.getValue())
|| mCarWeight.getWeight() >= Elevator.MaxCarCapacity) {
newState = State.STATE_DRIVE_SLOW;
}
//#transition 'T6.8'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
System.out.println("Transition:" + state + "->" + newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
/**
* Macros -- getLevelDir, getDriveDir
*/
//returns the level direction based on mLevel sensors
private Direction getLevelDir() {
if (!mLevelUp.getValue() && mLevelDown.getValue()) return Direction.UP;
else if (mLevelUp.getValue() && !mLevelDown.getValue()) return Direction.DOWN;
else return Direction.STOP;
}
//returns the desired direction based on current floor and desired floor by dispatcher
private Direction getDriveDir(Direction curDirection) {
if (mDesiredFloor.getFloor() < 1) {
return Direction.STOP;
}
Direction driveDir = curDirection;
int currentFloor = networkAtFloorArray.getCurrentFloor();
int desiredFloor = mDesiredFloor.getFloor();
//check car is not between floors
if (currentFloor != MessageDictionary.NONE) {
//current floor below desired floor
if (currentFloor < desiredFloor) {
driveDir = Direction.UP;
}
//current floor above desired floor
else if (currentFloor > desiredFloor) {
driveDir = Direction.DOWN;
}
//current floor is desired floor
else {
driveDir = Direction.STOP;
}
}
return driveDir;
}
}
| false | true | public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DRIVE_STOPPED:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_STOPPED
localDrive.set(Speed.STOP, Direction.STOP);
mDrive.set(Speed.STOP, Direction.STOP);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//log("localDrive="+localDrive.speed()+", "+localDrive.direction());
//log("localDriveSpeed="+localDriveSpeed.speed()+", "+localDriveSpeed.direction());
//log("mDriveSpeed="+mDriveSpeed.getSpeed()+", "+mDriveSpeed.getDirection());
//transitions
//#transition 'T6.1'
// if (driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) {
// newState = State.STATE_DRIVE_LEVEL;
// }
if ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) ||
(mCarWeight.getWeight() >= Elevator.MaxCarCapacity && (!mLevelUp.getValue() || !mLevelDown.getValue()))) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.3'
else if (driveDir != Direction.STOP
&& networkDoorClosedFront.getAllClosed() && networkDoorClosedBack.getAllClosed()
&& !mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_SLOW;
} else newState = state;
break;
case STATE_DRIVE_LEVEL:
driveDir = getDriveDir(driveDir);
Direction levelDir = getLevelDir();
//state actions for DRIVE_LEVEL
localDrive.set(Speed.LEVEL, levelDir);
mDrive.set(Speed.LEVEL, levelDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.2'
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue()
|| mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_SLOW:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_SLOW
localDrive.set(Speed.SLOW, driveDir);
mDrive.set(Speed.SLOW, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue() &&
localDriveSpeed.speed() < DriveObject.SlowSpeed) {
newState = State.STATE_DRIVE_STOPPED;
}
//#transition 'T6.4'
if ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue())
&& !mEmergencyBrake.getValue()) || mCarWeight.getWeight() >= Elevator.MaxCarCapacity) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.5'
else if (driveDir != Direction.STOP
&& !(localDriveSpeed.speed() < DriveObject.SlowSpeed) //********** finished accelerating
&& !networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())) {
newState = State.STATE_DRIVE_FAST;
}
//#transition 'T6.7'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_FAST:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_FAST
localDrive.set(Speed.FAST, driveDir);
mDrive.set(Speed.FAST, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.6'
if (driveDir != Direction.STOP
&& networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())
|| mCarWeight.getWeight() >= Elevator.MaxCarCapacity) {
newState = State.STATE_DRIVE_SLOW;
}
//#transition 'T6.8'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
System.out.println("Transition:" + state + "->" + newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
| public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DRIVE_STOPPED:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_STOPPED
localDrive.set(Speed.STOP, Direction.STOP);
mDrive.set(Speed.STOP, Direction.STOP);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//log("localDrive="+localDrive.speed()+", "+localDrive.direction());
//log("localDriveSpeed="+localDriveSpeed.speed()+", "+localDriveSpeed.direction());
//log("mDriveSpeed="+mDriveSpeed.getSpeed()+", "+mDriveSpeed.getDirection());
//transitions
//#transition 'T6.1'
// if (driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) {
// newState = State.STATE_DRIVE_LEVEL;
// }
if ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue()) && localDriveSpeed.speed() == 0) ||
(mCarWeight.getWeight() >= Elevator.MaxCarCapacity && (!mLevelUp.getValue() || !mLevelDown.getValue()))) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.3'
else if (driveDir != Direction.STOP
&& networkDoorClosedFront.getAllClosed() && networkDoorClosedBack.getAllClosed()
&& !mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_SLOW;
} else newState = state;
break;
case STATE_DRIVE_LEVEL:
driveDir = getDriveDir(driveDir);
Direction levelDir = getLevelDir();
//state actions for DRIVE_LEVEL
localDrive.set(Speed.LEVEL, levelDir);
mDrive.set(Speed.LEVEL, levelDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.2'
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue()
&& localDriveSpeed.speed() <= 0.05 || mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_SLOW:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_SLOW
localDrive.set(Speed.SLOW, driveDir);
mDrive.set(Speed.SLOW, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
if (driveDir == Direction.STOP && mLevelUp.getValue() && mLevelDown.getValue() &&
localDriveSpeed.speed() < DriveObject.SlowSpeed) {
newState = State.STATE_DRIVE_STOPPED;
}
//#transition 'T6.4'
if (localDriveSpeed.speed() <= 0.25 && ((driveDir == Direction.STOP && (!mLevelUp.getValue() || !mLevelDown.getValue())
&& !mEmergencyBrake.getValue()) || mCarWeight.getWeight() >= Elevator.MaxCarCapacity)) {
newState = State.STATE_DRIVE_LEVEL;
}
//#transition 'T6.5'
else if (driveDir != Direction.STOP
&& !(localDriveSpeed.speed() < DriveObject.SlowSpeed) //********** finished accelerating
&& !networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())) {
newState = State.STATE_DRIVE_FAST;
}
//#transition 'T6.7'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
case STATE_DRIVE_FAST:
driveDir = getDriveDir(driveDir);
//state actions for DRIVE_FAST
localDrive.set(Speed.FAST, driveDir);
mDrive.set(Speed.FAST, driveDir);
mDriveSpeed.set(localDriveSpeed.speed(), localDriveSpeed.direction());
//transitions
//#transition 'T6.6'
if ( (driveDir != Direction.STOP
&& networkCommitPoint.commitPoint(
mDesiredFloor.getFloor(), localDriveSpeed.direction(), localDriveSpeed.speed())
&& !mEmergencyBrake.getValue())
|| mCarWeight.getWeight() >= Elevator.MaxCarCapacity) {
newState = State.STATE_DRIVE_SLOW;
}
//#transition 'T6.8'
else if (mEmergencyBrake.getValue()) {
newState = State.STATE_DRIVE_STOPPED;
} else newState = state;
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
System.out.println("Transition:" + state + "->" + newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java
index 8e8b9a02d..83a753ec8 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java
@@ -1,143 +1,143 @@
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.team.internal.ccvs.core.CVSMergeSubscriber;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.core.client.Command;
import org.eclipse.team.internal.ccvs.core.client.Update;
import org.eclipse.team.internal.ccvs.ui.*;
import org.eclipse.team.internal.ccvs.ui.actions.WorkspaceTraversalAction;
import org.eclipse.team.internal.ccvs.ui.mappings.ModelMergeOperation;
import org.eclipse.team.internal.ccvs.ui.mappings.ModelMergeParticipant;
import org.eclipse.team.internal.ccvs.ui.operations.UpdateOperation;
import org.eclipse.team.internal.ccvs.ui.subscriber.MergeSynchronizeParticipant;
import org.eclipse.team.internal.ccvs.ui.tags.TagSource;
import org.eclipse.team.ui.TeamUI;
import org.eclipse.team.ui.synchronize.ISynchronizeParticipant;
import org.eclipse.ui.IWorkbenchPart;
public class MergeWizard extends Wizard {
MergeWizardPage page;
IResource[] resources;
private final IWorkbenchPart part;
private final ResourceMapping[] mappings;
public MergeWizard(IWorkbenchPart part, IResource[] resources, ResourceMapping[] mappings) {
this.part = part;
this.resources = resources;
this.mappings = mappings;
}
public void addPages() {
setNeedsProgressMonitor(true);
TagSource tagSource = TagSource.create(resources);
setWindowTitle(CVSUIMessages.MergeWizard_title);
ImageDescriptor mergeImage = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_MERGE);
page = new MergeWizardPage("mergePage", CVSUIMessages.MergeWizard_0, mergeImage, CVSUIMessages.MergeWizard_1, tagSource); //$NON-NLS-1$
addPage(page);
}
public boolean performFinish() {
CVSTag startTag = page.getStartTag();
CVSTag endTag = page.getEndTag();
if (startTag == null || !page.isPreview()) {
// Perform the update (merge) in the background
UpdateOperation op = new UpdateOperation(getPart(), mappings, getLocalOptions(startTag, endTag), null);
try {
op.run();
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Ignore
}
} else {
if (isShowModelSync()) {
ModelMergeParticipant participant = ModelMergeParticipant.getMatchingParticipant(mappings, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(getProjects(resources), startTag, endTag, true);
try {
new ModelMergeOperation(getPart(), mappings, s, page.isOnlyPreviewConflicts()).run();
} catch (InvocationTargetException e) {
CVSUIPlugin.log(IStatus.ERROR, "Internal error", e.getTargetException()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Ignore
}
} else {
participant.refresh(null, mappings);
}
} else {
// First check if there is an existing matching participant, if so then re-use it
try {
resources = getAllResources(startTag, endTag);
} catch (InvocationTargetException e) {
// Log and continue with the original resources
- CVSUIPlugin.log(IStatus.ERROR, "An error occurred while detemrining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$
+ CVSUIPlugin.log(IStatus.ERROR, "An error occurred while determining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$
}
MergeSynchronizeParticipant participant = MergeSynchronizeParticipant.getMatchingParticipant(resources, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(resources, startTag, endTag, false);
participant = new MergeSynchronizeParticipant(s);
TeamUI.getSynchronizeManager().addSynchronizeParticipants(new ISynchronizeParticipant[] {participant});
}
participant.refresh(resources, null, null, null);
}
}
return true;
}
private IResource[] getAllResources(CVSTag startTag, CVSTag endTag) throws InvocationTargetException {
// Only do the extra work if the model is a logical model (i.e. not IResource)
if (!WorkspaceTraversalAction.isLogicalModel(mappings))
return resources;
CVSMergeSubscriber s = new CVSMergeSubscriber(WorkspaceTraversalAction.getProjects(resources), startTag, endTag, false);
IResource[] allResources = WorkspaceTraversalAction.getResourcesToCompare(mappings, s);
s.cancel();
return allResources;
}
public static boolean isShowModelSync() {
return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_ENABLE_MODEL_SYNC);
}
private IResource[] getProjects(IResource[] resources) {
Set projects = new HashSet();
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
projects.add(resource.getProject());
}
return (IResource[]) projects.toArray(new IResource[projects.size()]);
}
private Command.LocalOption[] getLocalOptions(CVSTag startTag, CVSTag endTag) {
List options = new ArrayList();
if (startTag != null) {
options.add(Command.makeArgumentOption(Update.JOIN, startTag.getName()));
}
options.add(Command.makeArgumentOption(Update.JOIN, endTag.getName()));
return (Command.LocalOption[]) options.toArray(new Command.LocalOption[options.size()]);
}
private IWorkbenchPart getPart() {
return part;
}
}
| true | true | public boolean performFinish() {
CVSTag startTag = page.getStartTag();
CVSTag endTag = page.getEndTag();
if (startTag == null || !page.isPreview()) {
// Perform the update (merge) in the background
UpdateOperation op = new UpdateOperation(getPart(), mappings, getLocalOptions(startTag, endTag), null);
try {
op.run();
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Ignore
}
} else {
if (isShowModelSync()) {
ModelMergeParticipant participant = ModelMergeParticipant.getMatchingParticipant(mappings, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(getProjects(resources), startTag, endTag, true);
try {
new ModelMergeOperation(getPart(), mappings, s, page.isOnlyPreviewConflicts()).run();
} catch (InvocationTargetException e) {
CVSUIPlugin.log(IStatus.ERROR, "Internal error", e.getTargetException()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Ignore
}
} else {
participant.refresh(null, mappings);
}
} else {
// First check if there is an existing matching participant, if so then re-use it
try {
resources = getAllResources(startTag, endTag);
} catch (InvocationTargetException e) {
// Log and continue with the original resources
CVSUIPlugin.log(IStatus.ERROR, "An error occurred while detemrining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$
}
MergeSynchronizeParticipant participant = MergeSynchronizeParticipant.getMatchingParticipant(resources, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(resources, startTag, endTag, false);
participant = new MergeSynchronizeParticipant(s);
TeamUI.getSynchronizeManager().addSynchronizeParticipants(new ISynchronizeParticipant[] {participant});
}
participant.refresh(resources, null, null, null);
}
}
return true;
}
| public boolean performFinish() {
CVSTag startTag = page.getStartTag();
CVSTag endTag = page.getEndTag();
if (startTag == null || !page.isPreview()) {
// Perform the update (merge) in the background
UpdateOperation op = new UpdateOperation(getPart(), mappings, getLocalOptions(startTag, endTag), null);
try {
op.run();
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Ignore
}
} else {
if (isShowModelSync()) {
ModelMergeParticipant participant = ModelMergeParticipant.getMatchingParticipant(mappings, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(getProjects(resources), startTag, endTag, true);
try {
new ModelMergeOperation(getPart(), mappings, s, page.isOnlyPreviewConflicts()).run();
} catch (InvocationTargetException e) {
CVSUIPlugin.log(IStatus.ERROR, "Internal error", e.getTargetException()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Ignore
}
} else {
participant.refresh(null, mappings);
}
} else {
// First check if there is an existing matching participant, if so then re-use it
try {
resources = getAllResources(startTag, endTag);
} catch (InvocationTargetException e) {
// Log and continue with the original resources
CVSUIPlugin.log(IStatus.ERROR, "An error occurred while determining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$
}
MergeSynchronizeParticipant participant = MergeSynchronizeParticipant.getMatchingParticipant(resources, startTag, endTag);
if(participant == null) {
CVSMergeSubscriber s = new CVSMergeSubscriber(resources, startTag, endTag, false);
participant = new MergeSynchronizeParticipant(s);
TeamUI.getSynchronizeManager().addSynchronizeParticipants(new ISynchronizeParticipant[] {participant});
}
participant.refresh(resources, null, null, null);
}
}
return true;
}
|
diff --git a/src/main/java/org/sonar/ide/intellij/model/ToolWindowModel.java b/src/main/java/org/sonar/ide/intellij/model/ToolWindowModel.java
index fd25b0c..36dea89 100644
--- a/src/main/java/org/sonar/ide/intellij/model/ToolWindowModel.java
+++ b/src/main/java/org/sonar/ide/intellij/model/ToolWindowModel.java
@@ -1,74 +1,74 @@
package org.sonar.ide.intellij.model;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.sonar.ide.intellij.listener.RefreshListener;
import org.sonar.ide.intellij.utils.SonarCache;
import org.sonar.wsclient.services.Source;
import org.sonar.wsclient.services.Violation;
import javax.swing.SwingUtilities;
import java.util.*;
public class ToolWindowModel {
private Project project;
private ViolationTableModel violationTableModel;
private SonarTreeModel violationTreeModel;
private SonarCache sonarCache;
public ToolWindowModel(Project project, ViolationTableModel violationTableModel, SonarTreeModel violationTreeModel, SonarCache sonarCache) {
this.project = project;
this.violationTableModel = violationTableModel;
this.violationTreeModel = violationTreeModel;
this.sonarCache = sonarCache;
}
public ViolationTableModel getViolationTableModel() {
return this.violationTableModel;
}
public void refreshViolationsTable(VirtualFile newFile) {
sonarCache.loadViolations(newFile, new RefreshListener<Violation>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Violation> violations) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isFileCurrentlySelected(virtualFile)) {
violationTableModel.setViolations(virtualFile, violations);
Map<VirtualFile, List<Violation>> map = new HashMap<VirtualFile, List<Violation>>();
map.put(virtualFile, violations);
violationTreeModel.setViolations(map);
}
}
});
}
});
sonarCache.loadSource(newFile, new RefreshListener<Source>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Source> source) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
- if (isFileCurrentlySelected(virtualFile) && !source.isEmpty()) {
+ if (isFileCurrentlySelected(virtualFile) && source != null && !source.isEmpty()) {
violationTableModel.setSource(virtualFile, source.get(0));
}
}
});
}
});
}
private boolean isFileCurrentlySelected(VirtualFile virtualFile) {
VirtualFile[] selectedFiles = FileEditorManager.getInstance(this.project).getSelectedFiles();
for (VirtualFile selectedFile : selectedFiles) {
if (selectedFile.equals(virtualFile)) {
return true;
}
}
return false;
}
}
| true | true | public void refreshViolationsTable(VirtualFile newFile) {
sonarCache.loadViolations(newFile, new RefreshListener<Violation>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Violation> violations) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isFileCurrentlySelected(virtualFile)) {
violationTableModel.setViolations(virtualFile, violations);
Map<VirtualFile, List<Violation>> map = new HashMap<VirtualFile, List<Violation>>();
map.put(virtualFile, violations);
violationTreeModel.setViolations(map);
}
}
});
}
});
sonarCache.loadSource(newFile, new RefreshListener<Source>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Source> source) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isFileCurrentlySelected(virtualFile) && !source.isEmpty()) {
violationTableModel.setSource(virtualFile, source.get(0));
}
}
});
}
});
}
| public void refreshViolationsTable(VirtualFile newFile) {
sonarCache.loadViolations(newFile, new RefreshListener<Violation>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Violation> violations) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isFileCurrentlySelected(virtualFile)) {
violationTableModel.setViolations(virtualFile, violations);
Map<VirtualFile, List<Violation>> map = new HashMap<VirtualFile, List<Violation>>();
map.put(virtualFile, violations);
violationTreeModel.setViolations(map);
}
}
});
}
});
sonarCache.loadSource(newFile, new RefreshListener<Source>() {
@Override
public void doneRefresh(final VirtualFile virtualFile, final List<Source> source) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isFileCurrentlySelected(virtualFile) && source != null && !source.isEmpty()) {
violationTableModel.setSource(virtualFile, source.get(0));
}
}
});
}
});
}
|
diff --git a/src/ajm/ruby.java b/src/ajm/ruby.java
index 4110f35..4926128 100644
--- a/src/ajm/ruby.java
+++ b/src/ajm/ruby.java
@@ -1,280 +1,281 @@
package ajm;
/*
Copyright (c) 2008-2009, Adam Murray ([email protected]). All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.File;
import java.util.Date;
import org.apache.bsf.BSFException;
import ajm.maxsupport.AbstractMaxRubyObject;
import ajm.rubysupport.RubyException;
import ajm.util.*;
import com.cycling74.max.*;
/**
* The ajm.ruby MaxObject
*
* @author Adam Murray ([email protected])
*/
public class ruby extends AbstractMaxRubyObject {
private int evaloutlet = 0;
private File scriptFile;
private Atom[] scriptFileArgs;
private boolean listproc = true;
private boolean autowatch = false;
private FileWatcher fileWatcher;
/**
* The Constructor
*
* @param args
* 1 optional integer arg specifies the number of outlets
*/
public ruby(Atom[] args) {
super();
declareAttribute("evaloutlet", "getevaloutlet", "evaloutlet");
declareAttribute("scriptfile", "getscriptfile", "scriptfile");
declareAttribute("listproc");
declareAttribute("autowatch", "getautowatch", "autowatch");
int outlets = 1;
if (args.length > 0 && args[0].isInt() && args[0].getInt() > 1) {
outlets = args[0].getInt();
}
declareIO(1, outlets);
createInfoOutlet(false);
}
@Override
protected Executable getInitializer() {
return new RubyInitializer();
}
protected class RubyInitializer extends DefaultRubyInitializer {
@Override
public void execute() {
super.execute();
if (scriptFile != null) {
initFile();
}
}
}
@Override
public void notifyDeleted() {
stopFileWatcher();
super.notifyDeleted();
}
public int getevaloutlet() {
return evaloutlet;
}
public void evaloutlet(int evaloutlet) {
if (evaloutlet >= getNumOutlets()) {
err("Invalid evaloutlet " + evaloutlet);
}
else {
this.evaloutlet = evaloutlet;
}
}
public String getscriptfile() {
return scriptFile.getAbsolutePath();
}
public void scriptfile(Atom[] args) {
if (args != null && args.length > 0) {
scriptFile = Utils.getFile(args[0].toString());
scriptFileArgs = Atom.removeFirst(args);
}
else {
scriptFile = Utils.getFile(null);
scriptFileArgs = Atom.emptyArray;
}
if (scriptFile != null && initialized) {
initFile();
} // if not initialized initFile() will be called by the Initializer
}
public boolean getautowatch() {
return autowatch;
}
public void autowatch(boolean autowatch) {
this.autowatch = autowatch;
if (initialized) {
if (autowatch) {
startFileWatcher();
}
else {
stopFileWatcher();
}
}
}
private void startFileWatcher() {
if (fileWatcher == null) {
if (scriptFile != null && autowatch) {
fileWatcher = new FileWatcher(scriptFile, fileWatcherCallback);
fileWatcher.start();
}
}
else {
fileWatcher.setFile(scriptFile); // in case a new file was loaded - see scriptfile() / initFile()
fileWatcher.resumeWatching();
}
}
private void stopFileWatcher() {
if (fileWatcher != null) {
fileWatcher.pauseWatching();
}
}
private Executable fileWatcherCallback = new Executable() {
public void execute() {
loadFile();
}
};
private void initFile() {
stopFileWatcher();
loadFile();
startFileWatcher();
}
private synchronized void loadFile() {
info("loading script '" + scriptFile + "' on " + new Date());
try {
ruby.init(scriptFile, scriptFileArgs);
} catch (RubyException e) {
err("Error evaluating script file: " + scriptFile.getPath());
}
}
public void bang() {
eval("bang()");
}
public void list(Atom[] args) {
if (listproc) {
StringBuilder s = new StringBuilder("list([");
for (int i = 0; i < args.length; i++) {
if (i > 0) {
s.append(",");
}
s.append(args[i]);
}
s.append("])");
eval(s);
}
else {
anything(null, args);
}
}
public void anything(String msg, Atom[] args) {
StringBuilder input = new StringBuilder();
if (msg != null) {
input.append(Utils.detokenize(msg));
}
for (Atom arg : args) {
input.append(" ").append(Utils.detokenize(arg.toString()));
}
eval(input.toString().trim());
}
public void text(String script) {
eval(script.trim());
}
public void textblock(String name) {
String script = TextBlock.get(name);
if (script != null) {
eval(script);
}
else {
error("No textblock named '" + name + "'");
}
}
protected void eval(CharSequence input) {
try {
if (ruby == null) {
err("not initialized yet. Did not evaluate: " + input
+ ". If you are loadbanging a script, try using a deferlow.");
return;
}
Object val = ruby.eval(input, evaloutlet >= 0);
if (evaloutlet >= 0) {
// this check occurs here instead of evaloutlet() because we want
// to allow negative numbers to suppress eval output
if (val instanceof Atom[]) {
outlet(evaloutlet, (Atom[]) val);
}
else {
outlet(evaloutlet, (Atom) val);
}
}
} catch (RubyException e) {
err("could not evaluate: " + input);
Throwable t = e.getCause();
if (t != null && !(t instanceof BSFException)) {
String st = Utils.getStackTrace(t);
for (String s : st.split("\n")) {
error(s);
}
}
}
+ System.err.flush();
}
private TextViewer textViewer;
@Override
protected void dblclick() {
if (scriptFile != null) {
if (textViewer == null) {
textViewer = new TextViewer(scriptFile.getName());
}
textViewer.setText(Utils.getFileAsString(scriptFile));
int[] rect = getMaxBox().getRect();
int[] loc = getParentPatcher().getWindow().getLocation();
textViewer.setCenter(loc[0] + (rect[0] + rect[2]) / 2, loc[1] + (rect[1] + rect[3]) / 2);
textViewer.show();
}
}
}
| true | true | protected void eval(CharSequence input) {
try {
if (ruby == null) {
err("not initialized yet. Did not evaluate: " + input
+ ". If you are loadbanging a script, try using a deferlow.");
return;
}
Object val = ruby.eval(input, evaloutlet >= 0);
if (evaloutlet >= 0) {
// this check occurs here instead of evaloutlet() because we want
// to allow negative numbers to suppress eval output
if (val instanceof Atom[]) {
outlet(evaloutlet, (Atom[]) val);
}
else {
outlet(evaloutlet, (Atom) val);
}
}
} catch (RubyException e) {
err("could not evaluate: " + input);
Throwable t = e.getCause();
if (t != null && !(t instanceof BSFException)) {
String st = Utils.getStackTrace(t);
for (String s : st.split("\n")) {
error(s);
}
}
}
}
| protected void eval(CharSequence input) {
try {
if (ruby == null) {
err("not initialized yet. Did not evaluate: " + input
+ ". If you are loadbanging a script, try using a deferlow.");
return;
}
Object val = ruby.eval(input, evaloutlet >= 0);
if (evaloutlet >= 0) {
// this check occurs here instead of evaloutlet() because we want
// to allow negative numbers to suppress eval output
if (val instanceof Atom[]) {
outlet(evaloutlet, (Atom[]) val);
}
else {
outlet(evaloutlet, (Atom) val);
}
}
} catch (RubyException e) {
err("could not evaluate: " + input);
Throwable t = e.getCause();
if (t != null && !(t instanceof BSFException)) {
String st = Utils.getStackTrace(t);
for (String s : st.split("\n")) {
error(s);
}
}
}
System.err.flush();
}
|
diff --git a/AndroidExploration/src/org/crazydays/android/sensor/SensorsActivity.java b/AndroidExploration/src/org/crazydays/android/sensor/SensorsActivity.java
index 14f74ac..c6e8b92 100644
--- a/AndroidExploration/src/org/crazydays/android/sensor/SensorsActivity.java
+++ b/AndroidExploration/src/org/crazydays/android/sensor/SensorsActivity.java
@@ -1,87 +1,87 @@
/* $Id$ */
package org.crazydays.android.sensor;
import org.crazydays.android.R;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.EditText;
/**
* SensorActivity
*/
public class SensorsActivity
extends Activity
implements SensorEventListener
{
/** sensor manager */
protected SensorManager sensorManager;
/** magnetic sensor */
protected Sensor magnetic;
/**
* On create.
*
* @param state State
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle state)
{
super.onCreate(state);
setContentView(R.layout.sensor);
setupSensors();
}
/**
* Setup sensors.
*/
protected void setupSensors()
{
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
@Override
protected void onResume()
{
super.onResume();
sensorManager.registerListener(this, magnetic,
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause()
{
super.onPause();
sensorManager.unregisterListener(this, magnetic);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1)
{
}
@Override
public void onSensorChanged(SensorEvent event)
{
if (event.sensor == magnetic) {
EditText x = (EditText) findViewById(R.id.magneticDisplayX);
x.setText(Float.toString(event.values[0]));
- EditText y = (EditText) findViewById(R.id.magneticDisplayX);
+ EditText y = (EditText) findViewById(R.id.magneticDisplayY);
y.setText(Float.toString(event.values[1]));
- EditText z = (EditText) findViewById(R.id.magneticDisplayX);
+ EditText z = (EditText) findViewById(R.id.magneticDisplayZ);
z.setText(Float.toString(event.values[2]));
}
}
}
| false | true | public void onSensorChanged(SensorEvent event)
{
if (event.sensor == magnetic) {
EditText x = (EditText) findViewById(R.id.magneticDisplayX);
x.setText(Float.toString(event.values[0]));
EditText y = (EditText) findViewById(R.id.magneticDisplayX);
y.setText(Float.toString(event.values[1]));
EditText z = (EditText) findViewById(R.id.magneticDisplayX);
z.setText(Float.toString(event.values[2]));
}
}
| public void onSensorChanged(SensorEvent event)
{
if (event.sensor == magnetic) {
EditText x = (EditText) findViewById(R.id.magneticDisplayX);
x.setText(Float.toString(event.values[0]));
EditText y = (EditText) findViewById(R.id.magneticDisplayY);
y.setText(Float.toString(event.values[1]));
EditText z = (EditText) findViewById(R.id.magneticDisplayZ);
z.setText(Float.toString(event.values[2]));
}
}
|
diff --git a/src/org/mariotaku/twidere/fragment/ActivitiesAboutMeFragment.java b/src/org/mariotaku/twidere/fragment/ActivitiesAboutMeFragment.java
index 3ac8ad93..7fc07153 100644
--- a/src/org/mariotaku/twidere/fragment/ActivitiesAboutMeFragment.java
+++ b/src/org/mariotaku/twidere/fragment/ActivitiesAboutMeFragment.java
@@ -1,456 +1,459 @@
/*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mariotaku.twidere.fragment;
import static android.text.format.DateUtils.getRelativeTimeSpanString;
import static org.mariotaku.twidere.util.Utils.formatSameDayTime;
import static org.mariotaku.twidere.util.Utils.getBiggerTwitterProfileImage;
import static org.mariotaku.twidere.util.Utils.openStatus;
import static org.mariotaku.twidere.util.Utils.openUserFollowers;
import static org.mariotaku.twidere.util.Utils.openUserProfile;
import static org.mariotaku.twidere.util.Utils.parseString;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.mariotaku.twidere.R;
import org.mariotaku.twidere.adapter.ArrayAdapter;
import org.mariotaku.twidere.adapter.iface.IBaseAdapter;
import org.mariotaku.twidere.app.TwidereApplication;
import org.mariotaku.twidere.loader.ActivitiesAboutMeLoader;
import org.mariotaku.twidere.loader.Twitter4JActivitiesLoader;
import org.mariotaku.twidere.model.ParcelableStatus;
import org.mariotaku.twidere.model.ParcelableUser;
import org.mariotaku.twidere.util.ImageLoaderWrapper;
import org.mariotaku.twidere.view.holder.ActivityViewHolder;
import twitter4j.Activity;
import twitter4j.Activity.Action;
import twitter4j.Status;
import twitter4j.User;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class ActivitiesAboutMeFragment extends PullToRefreshListFragment implements
LoaderCallbacks<List<Activity>> {
private ActivitiesAdapter mAdapter;
private SharedPreferences mPreferences;
private List<Activity> mData;
private long mAccountId;
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new ActivitiesAdapter(getActivity());
mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, getArguments(), this);
setListShown(false);
}
@Override
public Loader<List<Activity>> onCreateLoader(final int id, final Bundle args) {
setProgressBarIndeterminateVisibility(true);
final long account_id = mAccountId = args != null ? args.getLong(INTENT_KEY_ACCOUNT_ID, -1) : -1;
final boolean is_home_tab = args != null ? args.getBoolean(INTENT_KEY_IS_HOME_TAB) : false;
return new ActivitiesAboutMeLoader(getActivity(), account_id, mData, getClass().getSimpleName(), is_home_tab);
}
@Override
public void onDestroy() {
Twitter4JActivitiesLoader.writeSerializableStatuses(this, getActivity(), mData, getArguments());
super.onDestroy();
}
@Override
public void onDestroyView() {
Twitter4JActivitiesLoader.writeSerializableStatuses(this, getActivity(), mData, getArguments());
super.onDestroyView();
}
@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id) {
if (mAccountId <= 0) return;
final int adapter_pos = position - l.getHeaderViewsCount();
final Activity item = mAdapter.getItem(adapter_pos);
final User[] sources = item.getSources();
final Status[] target_statuses = item.getTargetStatuses();
final int sources_length = sources != null ? sources.length : 0;
final Action action = item.getAction();
final boolean hires_profile_image = getResources().getBoolean(R.bool.hires_profile_image);
if (sources_length > 0) {
final Status[] target_objects = item.getTargetObjectStatuses();
switch (action.getActionId()) {
case Action.ACTION_FAVORITE: {
if (sources_length == 1) {
openUserProfile(getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
} else {
if (target_statuses != null && target_statuses.length > 0) {
final Status status = target_statuses[0];
openStatus(getActivity(), new ParcelableStatus(status, mAccountId, false,
hires_profile_image));
}
}
break;
}
case Action.ACTION_FOLLOW: {
if (sources_length == 1) {
openUserProfile(getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
} else {
openUserFollowers(getActivity(), mAccountId, mAccountId, null);
}
break;
}
case Action.ACTION_MENTION: {
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
openStatus(getActivity(), new ParcelableStatus(status, mAccountId, false, hires_profile_image));
}
break;
}
case Action.ACTION_REPLY: {
if (target_statuses != null && target_statuses.length > 0) {
final Status status = target_statuses[0];
openStatus(getActivity(), new ParcelableStatus(status, mAccountId, false, hires_profile_image));
}
break;
}
case Action.ACTION_RETWEET: {
if (sources_length == 1) {
openUserProfile(getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
} else {
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
openStatus(getActivity(), new ParcelableStatus(status, mAccountId, false,
hires_profile_image));
}
}
break;
}
}
}
}
@Override
public void onLoaderReset(final Loader<List<Activity>> loader) {
mAdapter.setData(null);
mData = null;
}
@Override
public void onLoadFinished(final Loader<List<Activity>> loader, final List<Activity> data) {
setProgressBarIndeterminateVisibility(false);
mAdapter.setData(data);
mData = data;
onRefreshComplete();
setListShown(true);
}
@Override
public void onPullDownToRefresh() {
getLoaderManager().restartLoader(0, getArguments(), this);
}
@Override
public void onPullUpToRefresh() {
}
@Override
public void onResume() {
super.onResume();
final float text_size = mPreferences.getInt(PREFERENCE_KEY_TEXT_SIZE, PREFERENCE_DEFAULT_TEXT_SIZE);
final boolean display_profile_image = mPreferences.getBoolean(PREFERENCE_KEY_DISPLAY_PROFILE_IMAGE, true);
final boolean show_absolute_time = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_ABSOLUTE_TIME, false);
mAdapter.setDisplayProfileImage(display_profile_image);
mAdapter.setTextSize(text_size);
mAdapter.setShowAbsoluteTime(show_absolute_time);
}
static class ActivitiesAdapter extends ArrayAdapter<Activity> implements IBaseAdapter {
private boolean mDisplayProfileImage, mDisplayName, mShowAbsoluteTime;
private final boolean mDisplayHiResProfileImage;
private float mTextSize;
private final ImageLoaderWrapper mProfileImageLoader;
private final Context mContext;
public ActivitiesAdapter(final Context context) {
super(context, R.layout.activity_list_item);
mContext = context;
final TwidereApplication application = TwidereApplication.getInstance(context);
mProfileImageLoader = application.getImageLoaderWrapper();
mDisplayHiResProfileImage = context.getResources().getBoolean(R.bool.hires_profile_image);
}
@Override
public long getItemId(final int position) {
final Object obj = getItem(position);
return obj != null ? obj.hashCode() : 0;
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
final Object tag = view.getTag();
final ActivityViewHolder holder = tag instanceof ActivityViewHolder ? (ActivityViewHolder) tag
: new ActivityViewHolder(view);
if (!(tag instanceof ActivityViewHolder)) {
view.setTag(holder);
}
holder.reset();
holder.setTextSize(mTextSize);
- final Object item = getItem(position);
- if (!(item instanceof Activity)) return view;
- final Activity activity = (Activity) item;
- final Date created_at = activity.getCreatedAt();
+ final Activity item;
+ try {
+ item = getItem(position);
+ } catch (ClassCastException e) {
+ return view;
+ }
+ final Date created_at = item.getCreatedAt();
if (created_at != null) {
if (mShowAbsoluteTime) {
holder.time.setText(formatSameDayTime(mContext, created_at.getTime()));
} else {
holder.time.setText(getRelativeTimeSpanString(created_at.getTime()));
}
}
- final User[] sources = activity.getSources();
- final Status[] target_statuses = activity.getTargetStatuses();
+ final User[] sources = item.getSources();
+ final Status[] target_statuses = item.getTargetStatuses();
final int sources_length = sources != null ? sources.length : 0;
final int target_statuses_length = target_statuses != null ? target_statuses.length : 0;
- final Action action = activity.getAction();
+ final Action action = item.getAction();
holder.profile_image.setVisibility(mDisplayProfileImage ? View.VISIBLE : View.GONE);
if (sources_length > 0) {
final User first_source = sources[0];
- final Status[] target_objects = activity.getTargetObjectStatuses();
+ final Status[] target_objects = item.getTargetObjectStatuses();
final String name = mDisplayName ? first_source.getName() : first_source.getScreenName();
switch (action.getActionId()) {
case Action.ACTION_FAVORITE: {
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_FOLLOW: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_MENTION: {
holder.title.setText(name);
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_REPLY: {
holder.title.setText(name);
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_RETWEET: {
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_LIST_MEMBER_ADDED: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title
.setText(mContext.getString(R.string.activity_about_me_list_member_added, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_list_member_added_multi,
name, sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
}
}
return view;
}
public void onItemSelected(final Object item) {
notifyDataSetChanged();
}
public void onItemUnselected(final Object item) {
notifyDataSetChanged();
}
public void setData(final List<Activity> data) {
clear();
if (data == null) return;
addAll(data);
}
@Override
public void setDisplayProfileImage(final boolean display) {
if (display != mDisplayProfileImage) {
mDisplayProfileImage = display;
notifyDataSetChanged();
}
}
@Override
public void setNameDisplayOption(final String option) {
// TODO: Implement this method
}
public void setShowAbsoluteTime(final boolean show) {
if (show != mShowAbsoluteTime) {
mShowAbsoluteTime = show;
notifyDataSetChanged();
}
}
@Override
public void setTextSize(final float text_size) {
if (text_size != mTextSize) {
mTextSize = text_size;
notifyDataSetChanged();
}
}
private void setProfileImage(final URL url, final ActivityViewHolder holder) {
if (!mDisplayProfileImage) return;
if (mDisplayHiResProfileImage) {
mProfileImageLoader.displayProfileImage(holder.profile_image,
getBiggerTwitterProfileImage(parseString(url)));
} else {
mProfileImageLoader.displayProfileImage(holder.profile_image, parseString(url));
}
}
private void setUserProfileImages(final User[] users, final ActivityViewHolder holder) {
if (!mDisplayProfileImage) return;
final int length = users.length;
for (int i = 0; i < length; i++) {
if (i > 4) {
break;
}
final User user = users[i];
final ImageView activity_profile_image;
switch (i) {
case 0: {
activity_profile_image = holder.activity_profile_image_1;
break;
}
case 1: {
activity_profile_image = holder.activity_profile_image_2;
break;
}
case 2: {
activity_profile_image = holder.activity_profile_image_3;
break;
}
case 3: {
activity_profile_image = holder.activity_profile_image_4;
break;
}
case 4: {
activity_profile_image = holder.activity_profile_image_5;
break;
}
default: {
activity_profile_image = null;
}
}
if (mDisplayHiResProfileImage) {
mProfileImageLoader.displayProfileImage(activity_profile_image,
getBiggerTwitterProfileImage(parseString(user.getProfileImageURL())));
} else {
mProfileImageLoader.displayProfileImage(activity_profile_image,
parseString(user.getProfileImageURL()));
}
}
}
}
}
| false | true | public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
final Object tag = view.getTag();
final ActivityViewHolder holder = tag instanceof ActivityViewHolder ? (ActivityViewHolder) tag
: new ActivityViewHolder(view);
if (!(tag instanceof ActivityViewHolder)) {
view.setTag(holder);
}
holder.reset();
holder.setTextSize(mTextSize);
final Object item = getItem(position);
if (!(item instanceof Activity)) return view;
final Activity activity = (Activity) item;
final Date created_at = activity.getCreatedAt();
if (created_at != null) {
if (mShowAbsoluteTime) {
holder.time.setText(formatSameDayTime(mContext, created_at.getTime()));
} else {
holder.time.setText(getRelativeTimeSpanString(created_at.getTime()));
}
}
final User[] sources = activity.getSources();
final Status[] target_statuses = activity.getTargetStatuses();
final int sources_length = sources != null ? sources.length : 0;
final int target_statuses_length = target_statuses != null ? target_statuses.length : 0;
final Action action = activity.getAction();
holder.profile_image.setVisibility(mDisplayProfileImage ? View.VISIBLE : View.GONE);
if (sources_length > 0) {
final User first_source = sources[0];
final Status[] target_objects = activity.getTargetObjectStatuses();
final String name = mDisplayName ? first_source.getName() : first_source.getScreenName();
switch (action.getActionId()) {
case Action.ACTION_FAVORITE: {
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_FOLLOW: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_MENTION: {
holder.title.setText(name);
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_REPLY: {
holder.title.setText(name);
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_RETWEET: {
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_LIST_MEMBER_ADDED: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title
.setText(mContext.getString(R.string.activity_about_me_list_member_added, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_list_member_added_multi,
name, sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
}
}
return view;
}
| public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
final Object tag = view.getTag();
final ActivityViewHolder holder = tag instanceof ActivityViewHolder ? (ActivityViewHolder) tag
: new ActivityViewHolder(view);
if (!(tag instanceof ActivityViewHolder)) {
view.setTag(holder);
}
holder.reset();
holder.setTextSize(mTextSize);
final Activity item;
try {
item = getItem(position);
} catch (ClassCastException e) {
return view;
}
final Date created_at = item.getCreatedAt();
if (created_at != null) {
if (mShowAbsoluteTime) {
holder.time.setText(formatSameDayTime(mContext, created_at.getTime()));
} else {
holder.time.setText(getRelativeTimeSpanString(created_at.getTime()));
}
}
final User[] sources = item.getSources();
final Status[] target_statuses = item.getTargetStatuses();
final int sources_length = sources != null ? sources.length : 0;
final int target_statuses_length = target_statuses != null ? target_statuses.length : 0;
final Action action = item.getAction();
holder.profile_image.setVisibility(mDisplayProfileImage ? View.VISIBLE : View.GONE);
if (sources_length > 0) {
final User first_source = sources[0];
final Status[] target_objects = item.getTargetObjectStatuses();
final String name = mDisplayName ? first_source.getName() : first_source.getScreenName();
switch (action.getActionId()) {
case Action.ACTION_FAVORITE: {
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_favorite_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_FOLLOW: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_follow_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_MENTION: {
holder.title.setText(name);
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_REPLY: {
holder.title.setText(name);
if (target_statuses_length > 0) {
final Status status = target_statuses[0];
holder.text.setText(status.getText());
if (status.getInReplyToStatusId() > 0 && status.getInReplyToScreenName() != null) {
holder.reply_status.setVisibility(View.VISIBLE);
holder.reply_status.setText(mContext.getString(R.string.in_reply_to,
status.getInReplyToScreenName()));
holder.reply_status.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_indicator_reply, 0, 0, 0);
}
}
setProfileImage(first_source.getProfileImageURL(), holder);
break;
}
case Action.ACTION_RETWEET: {
if (target_objects != null && target_objects.length > 0) {
final Status status = target_objects[0];
holder.text.setSingleLine(true);
holder.text.setEllipsize(TruncateAt.END);
holder.text.setText(status.getText());
}
if (sources_length == 1) {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_retweet_multi, name,
sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
case Action.ACTION_LIST_MEMBER_ADDED: {
holder.text.setVisibility(View.GONE);
if (sources_length == 1) {
holder.title
.setText(mContext.getString(R.string.activity_about_me_list_member_added, name));
} else {
holder.title.setText(mContext.getString(R.string.activity_about_me_list_member_added_multi,
name, sources_length - 1));
}
holder.activity_profile_image_container.setVisibility(mDisplayProfileImage ? View.VISIBLE
: View.GONE);
setUserProfileImages(sources, holder);
break;
}
}
}
return view;
}
|
diff --git a/nanite-hadoop/src/main/java/uk/bl/wap/hadoop/profiler/FormatProfiler.java b/nanite-hadoop/src/main/java/uk/bl/wap/hadoop/profiler/FormatProfiler.java
index c112a8b..02039c0 100644
--- a/nanite-hadoop/src/main/java/uk/bl/wap/hadoop/profiler/FormatProfiler.java
+++ b/nanite-hadoop/src/main/java/uk/bl/wap/hadoop/profiler/FormatProfiler.java
@@ -1,123 +1,123 @@
package uk.bl.wap.hadoop.profiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.util.Tool;
import org.apache.log4j.Logger;
import uk.bl.wap.hadoop.ArchiveFileInputFormat;
import uk.bl.wap.hadoop.format.Ohcount;
import uk.bl.wap.hadoop.util.Unpack;
/**
* WARCTikExtractor
* Extracts text using Tika from a series of WARC files.
*
* @author rcoram
*/
@SuppressWarnings( { "deprecation" } )
public class FormatProfiler extends Configured implements Tool {
private static Logger log = Logger.getLogger(FormatProfiler.class.getName());
private static final String CONFIG = "/hadoop_utils.config";
public int run( String[] args ) throws IOException {
JobConf conf = new JobConf( getConf(), FormatProfiler.class );
log.info("Loading paths...");
String line = null;
List<Path> paths = new ArrayList<Path>();
BufferedReader br = new BufferedReader( new FileReader( args[ 0 ] ) );
while( ( line = br.readLine() ) != null ) {
paths.add( new Path( line ) );
}
log.info("Setting paths...");
FileInputFormat.setInputPaths( conf, paths.toArray(new Path[] {}) );
log.info("Set "+paths.size()+" InputPaths");
FileOutputFormat.setOutputPath( conf, new Path( args[ 1 ] ) );
//this.setProperties( conf );
conf.setJobName( args[ 0 ] + "_" + System.currentTimeMillis() );
conf.setInputFormat( ArchiveFileInputFormat.class );
conf.setMapperClass( FormatProfilerMapper.class );
conf.setReducerClass( FormatProfilerReducer.class );
conf.setOutputFormat( TextOutputFormat.class );
conf.set( "map.output.key.field.separator", "" );
conf.setOutputKeyClass( Text.class );
conf.setOutputValueClass( Text.class );
conf.setMapOutputValueClass( Text.class );
// Override the task timeout to cope with behaviour when processing malformed archive files:
- // 30 mins:
- conf.set("mapred.task.timeout", "1800000");
+ // Actually, error indicates 20,000 seconds is the default here, which is 5.5 hrs!
+ //conf.set("mapred.task.timeout", "1800000");
// Manually set a large number of reducers:
conf.setNumReduceTasks(50);
JobClient.runJob( conf );
return 0;
}
private void setProperties( JobConf conf ) throws IOException {
Properties properties = new Properties();
properties.load( this.getClass().getResourceAsStream( ( CONFIG ) ) );
conf.set( "solr.default", properties.getProperty( "solr_default" ) );
conf.set( "solr.image", properties.getProperty( "solr_image" ) );
conf.set( "solr.media", properties.getProperty( "solr_media" ) );
conf.set( "solr.batch.size", properties.getProperty( "solr_batch_size" ) );
conf.set( "solr.threads", properties.getProperty( "solr_threads" ) );
conf.set( "solr.image.regex", properties.getProperty( "solr_image_regex" ) );
conf.set( "solr.media.regex", properties.getProperty( "solr_media_regex" ) );
conf.set( "record.exclude.mime", properties.getProperty( "mime_exclude" ) );
conf.set( "record.exclude.url", properties.getProperty( "url_exclude" ) );
conf.set( "record.size.max", properties.getProperty( "max_payload_size" ) );
conf.set( "record.include.response", properties.getProperty( "response_include" ) );
conf.set( "record.include.protocol", properties.getProperty( "protocol_include" ) );
conf.set( "tika.exclude.mime", properties.getProperty( "mime_exclude" ) );
conf.set( "tika.timeout", properties.getProperty( "tika_timeout" ) );
}
public static void main( String[] args ) throws Exception {
if( !( args.length > 0 ) ) {
System.out.println( "Need input file.list and output dir!" );
System.exit( 0 );
}
int ret = ToolRunner.run( new FormatProfiler(), args );
System.exit( ret );
}
private String getWctTi( String warcName ) {
Pattern pattern = Pattern.compile( "^BL-([0-9]+)-[0-9]+\\.warc(\\.gz)?$" );
Matcher matcher = pattern.matcher( warcName );
if( matcher.matches() ) {
return matcher.group( 1 );
}
return "";
}
}
| true | true | public int run( String[] args ) throws IOException {
JobConf conf = new JobConf( getConf(), FormatProfiler.class );
log.info("Loading paths...");
String line = null;
List<Path> paths = new ArrayList<Path>();
BufferedReader br = new BufferedReader( new FileReader( args[ 0 ] ) );
while( ( line = br.readLine() ) != null ) {
paths.add( new Path( line ) );
}
log.info("Setting paths...");
FileInputFormat.setInputPaths( conf, paths.toArray(new Path[] {}) );
log.info("Set "+paths.size()+" InputPaths");
FileOutputFormat.setOutputPath( conf, new Path( args[ 1 ] ) );
//this.setProperties( conf );
conf.setJobName( args[ 0 ] + "_" + System.currentTimeMillis() );
conf.setInputFormat( ArchiveFileInputFormat.class );
conf.setMapperClass( FormatProfilerMapper.class );
conf.setReducerClass( FormatProfilerReducer.class );
conf.setOutputFormat( TextOutputFormat.class );
conf.set( "map.output.key.field.separator", "" );
conf.setOutputKeyClass( Text.class );
conf.setOutputValueClass( Text.class );
conf.setMapOutputValueClass( Text.class );
// Override the task timeout to cope with behaviour when processing malformed archive files:
// 30 mins:
conf.set("mapred.task.timeout", "1800000");
// Manually set a large number of reducers:
conf.setNumReduceTasks(50);
JobClient.runJob( conf );
return 0;
}
| public int run( String[] args ) throws IOException {
JobConf conf = new JobConf( getConf(), FormatProfiler.class );
log.info("Loading paths...");
String line = null;
List<Path> paths = new ArrayList<Path>();
BufferedReader br = new BufferedReader( new FileReader( args[ 0 ] ) );
while( ( line = br.readLine() ) != null ) {
paths.add( new Path( line ) );
}
log.info("Setting paths...");
FileInputFormat.setInputPaths( conf, paths.toArray(new Path[] {}) );
log.info("Set "+paths.size()+" InputPaths");
FileOutputFormat.setOutputPath( conf, new Path( args[ 1 ] ) );
//this.setProperties( conf );
conf.setJobName( args[ 0 ] + "_" + System.currentTimeMillis() );
conf.setInputFormat( ArchiveFileInputFormat.class );
conf.setMapperClass( FormatProfilerMapper.class );
conf.setReducerClass( FormatProfilerReducer.class );
conf.setOutputFormat( TextOutputFormat.class );
conf.set( "map.output.key.field.separator", "" );
conf.setOutputKeyClass( Text.class );
conf.setOutputValueClass( Text.class );
conf.setMapOutputValueClass( Text.class );
// Override the task timeout to cope with behaviour when processing malformed archive files:
// Actually, error indicates 20,000 seconds is the default here, which is 5.5 hrs!
//conf.set("mapred.task.timeout", "1800000");
// Manually set a large number of reducers:
conf.setNumReduceTasks(50);
JobClient.runJob( conf );
return 0;
}
|
diff --git a/plugins/experimental/org.eclipse.uml2.diagram.sequence/custom-src/org/eclipse/uml2/diagram/sequence/figures/StateInvariantShape.java b/plugins/experimental/org.eclipse.uml2.diagram.sequence/custom-src/org/eclipse/uml2/diagram/sequence/figures/StateInvariantShape.java
index d22e90c08..98b4e3054 100644
--- a/plugins/experimental/org.eclipse.uml2.diagram.sequence/custom-src/org/eclipse/uml2/diagram/sequence/figures/StateInvariantShape.java
+++ b/plugins/experimental/org.eclipse.uml2.diagram.sequence/custom-src/org/eclipse/uml2/diagram/sequence/figures/StateInvariantShape.java
@@ -1,59 +1,60 @@
package org.eclipse.uml2.diagram.sequence.figures;
import org.eclipse.draw2d.BorderLayout;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.uml2.diagram.common.editparts.NeedsParentEditPart;
import org.eclipse.uml2.diagram.common.layered.MultiLayeredContainer;
import org.eclipse.uml2.diagram.common.layered.MultilayeredFigure;
import org.eclipse.uml2.diagram.common.layered.MultilayeredSupport;
import org.eclipse.uml2.diagram.common.layered.MultilayeredSupportImpl;
import org.eclipse.uml2.diagram.sequence.part.UMLDiagramEditorPlugin;
public class StateInvariantShape extends RoundedRectangle implements MultilayeredFigure, NeedsParentEditPart {
protected static final int DEFAULT_RADIUS = 15;
protected static final int VERTICAL_SPACING = 2;
private final MultilayeredSupportImpl myMultilayeredSupport = new MultilayeredSupportImpl();
private Label myInplaceLabel;
public StateInvariantShape () {
+ setLineWidth(1);
setOutline(false);
setBackgroundColor(ColorConstants.lightGray);
corner.width = DEFAULT_RADIUS;
corner.height = DEFAULT_RADIUS;
setLayoutManager(new BorderLayout());
int gapWidth = corner.width/2;
myInplaceLabel = new Label("");
myInplaceLabel.setForegroundColor(ColorConstants.black);
myInplaceLabel.setFont(UMLDiagramEditorPlugin.getInstance().getDefaultBoldFont());
myInplaceLabel.setBorder(new MarginBorder(VERTICAL_SPACING,gapWidth,VERTICAL_SPACING,gapWidth));
myInplaceLabel.setLabelAlignment(PositionConstants.CENTER);
add(myInplaceLabel, BorderLayout.CENTER);
myMultilayeredSupport.setLayerToFigure(MultiLayeredContainer.MIDDLE_LAYER, this);
myMultilayeredSupport.setLayerToContentPane(MultiLayeredContainer.MIDDLE_LAYER, this);
}
public Label getStateInvariantInplaceLabel() {
return myInplaceLabel;
}
public MultilayeredSupport getMultilayeredSupport() {
return myMultilayeredSupport;
}
public void hookParentEditPart(GraphicalEditPart parentEditPart) {
myMultilayeredSupport.setParentFromParentEditPart(parentEditPart);
}
}
| true | true | public StateInvariantShape () {
setOutline(false);
setBackgroundColor(ColorConstants.lightGray);
corner.width = DEFAULT_RADIUS;
corner.height = DEFAULT_RADIUS;
setLayoutManager(new BorderLayout());
int gapWidth = corner.width/2;
myInplaceLabel = new Label("");
myInplaceLabel.setForegroundColor(ColorConstants.black);
myInplaceLabel.setFont(UMLDiagramEditorPlugin.getInstance().getDefaultBoldFont());
myInplaceLabel.setBorder(new MarginBorder(VERTICAL_SPACING,gapWidth,VERTICAL_SPACING,gapWidth));
myInplaceLabel.setLabelAlignment(PositionConstants.CENTER);
add(myInplaceLabel, BorderLayout.CENTER);
myMultilayeredSupport.setLayerToFigure(MultiLayeredContainer.MIDDLE_LAYER, this);
myMultilayeredSupport.setLayerToContentPane(MultiLayeredContainer.MIDDLE_LAYER, this);
}
| public StateInvariantShape () {
setLineWidth(1);
setOutline(false);
setBackgroundColor(ColorConstants.lightGray);
corner.width = DEFAULT_RADIUS;
corner.height = DEFAULT_RADIUS;
setLayoutManager(new BorderLayout());
int gapWidth = corner.width/2;
myInplaceLabel = new Label("");
myInplaceLabel.setForegroundColor(ColorConstants.black);
myInplaceLabel.setFont(UMLDiagramEditorPlugin.getInstance().getDefaultBoldFont());
myInplaceLabel.setBorder(new MarginBorder(VERTICAL_SPACING,gapWidth,VERTICAL_SPACING,gapWidth));
myInplaceLabel.setLabelAlignment(PositionConstants.CENTER);
add(myInplaceLabel, BorderLayout.CENTER);
myMultilayeredSupport.setLayerToFigure(MultiLayeredContainer.MIDDLE_LAYER, this);
myMultilayeredSupport.setLayerToContentPane(MultiLayeredContainer.MIDDLE_LAYER, this);
}
|
diff --git a/org.eclipse.m2e.scm/src/org/eclipse/m2e/scm/internal/wizards/MavenProjectCheckoutJob.java b/org.eclipse.m2e.scm/src/org/eclipse/m2e/scm/internal/wizards/MavenProjectCheckoutJob.java
index a45e869..3a6f682 100644
--- a/org.eclipse.m2e.scm/src/org/eclipse/m2e/scm/internal/wizards/MavenProjectCheckoutJob.java
+++ b/org.eclipse.m2e.scm/src/org/eclipse/m2e/scm/internal/wizards/MavenProjectCheckoutJob.java
@@ -1,275 +1,275 @@
/*******************************************************************************
* Copyright (c) 2008-2010 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sonatype, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.m2e.scm.internal.wizards;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.model.Model;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.MavenModelManager;
import org.eclipse.m2e.core.internal.lifecyclemapping.discovery.LifecycleMappingConfiguration;
import org.eclipse.m2e.core.project.IMavenProjectImportResult;
import org.eclipse.m2e.core.project.LocalProjectScanner;
import org.eclipse.m2e.core.project.MavenProjectInfo;
import org.eclipse.m2e.core.project.ProjectImportConfiguration;
import org.eclipse.m2e.core.ui.internal.M2EUIPluginActivator;
import org.eclipse.m2e.core.ui.internal.actions.OpenMavenConsoleAction;
import org.eclipse.m2e.core.ui.internal.wizards.AbstactCreateMavenProjectJob;
import org.eclipse.m2e.core.ui.internal.wizards.MavenImportWizard;
import org.eclipse.m2e.scm.MavenCheckoutOperation;
import org.eclipse.m2e.scm.MavenProjectScmInfo;
import org.eclipse.m2e.scm.internal.Messages;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.NewProjectAction;
import org.eclipse.ui.progress.IProgressConstants;
import org.eclipse.ui.wizards.datatransfer.ExternalProjectImportWizard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Maven project checkout Job
*
* @author Eugene Kuleshov
*/
public abstract class MavenProjectCheckoutJob extends WorkspaceJob {
private static final Logger log = LoggerFactory.getLogger(MavenProjectCheckoutJob.class);
final ProjectImportConfiguration configuration;
boolean checkoutAllProjects;
Collection<MavenProjectInfo> projects;
File location;
List<String> collectedLocations = new ArrayList<String>();
final List<IWorkingSet> workingSets;
public MavenProjectCheckoutJob(ProjectImportConfiguration importConfiguration, boolean checkoutAllProjects,
List<IWorkingSet> workingSets) {
super(Messages.MavenProjectCheckoutJob_title);
this.configuration = importConfiguration;
this.checkoutAllProjects = checkoutAllProjects;
this.workingSets = workingSets;
setProperty(IProgressConstants.ACTION_PROPERTY, new OpenMavenConsoleAction());
addJobChangeListener(new CheckoutJobChangeListener());
}
public void setLocation(File location) {
this.location = location;
}
protected abstract Collection<MavenProjectScmInfo> getProjects(IProgressMonitor monitor) throws InterruptedException;
// WorkspaceJob
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
try {
MavenCheckoutOperation operation = new MavenCheckoutOperation(location, getProjects(monitor));
operation.run(monitor);
collectedLocations.addAll(operation.getLocations());
IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
MavenModelManager modelManager = MavenPlugin.getMavenModelManager();
LocalProjectScanner scanner = new LocalProjectScanner(workspace.getLocation().toFile(), operation.getLocations(),
true, modelManager);
scanner.run(monitor);
this.projects = MavenPlugin.getProjectConfigurationManager().collectProjects(scanner.getProjects());
if(checkoutAllProjects) {
// check if there any project name conflicts
for(MavenProjectInfo projectInfo : projects) {
Model model = projectInfo.getModel();
if(model == null) {
model = modelManager.readMavenModel(projectInfo.getPomFile());
projectInfo.setModel(model);
}
String projectName = configuration.getProjectName(model);
IProject project = workspace.getProject(projectName);
if(project.exists()) {
checkoutAllProjects = false;
break;
}
}
}
return Status.OK_STATUS;
} catch(InterruptedException ex) {
return Status.CANCEL_STATUS;
}
}
/**
* Checkout job listener
*/
final class CheckoutJobChangeListener extends JobChangeAdapter {
public void done(IJobChangeEvent event) {
IStatus result = event.getResult();
if(result.getSeverity() == IStatus.CANCEL) {
return;
} else if(!result.isOK()) {
// XXX report errors
return;
}
if(projects.isEmpty()) {
log.info("No Maven projects to import");
if(collectedLocations.size()==1) {
final String location = collectedLocations.get(0);
DirectoryScanner projectScanner = new DirectoryScanner();
projectScanner.setBasedir(location);
projectScanner.setIncludes(new String[] {"**/.project"}); //$NON-NLS-1$
projectScanner.scan();
String[] projectFiles = projectScanner.getIncludedFiles();
if(projectFiles!=null && projectFiles.length>0) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm_title, //
Messages.MavenProjectCheckoutJob_confirm_message);
if(res) {
IWizard wizard = new ExternalProjectImportWizard(collectedLocations.get(0));
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
wizard);
dialog.open();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm2_title, //
Messages.MavenProjectCheckoutJob_confirm2_message);
if(res) {
Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay());
clipboard.setContents(new Object[] { location }, new Transfer[] { TextTransfer.getInstance() });
NewProjectAction newProjectAction = new NewProjectAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
newProjectAction.run();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
cleanup(collectedLocations);
}
if(checkoutAllProjects) {
if(M2EUIPluginActivator.getDefault().getMavenDiscovery() != null) {
final LifecycleMappingConfiguration mappingConfiguration = LifecycleMappingConfiguration.calculate(projects,
configuration, new NullProgressMonitor());
- if(!mappingConfiguration.isMappingComplete()) {
+ if(!mappingConfiguration.isMappingComplete(true)) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations,
mappingConfiguration);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
return;
}
}
WorkspaceJob job = new AbstactCreateMavenProjectJob(Messages.MavenProjectCheckoutJob_job, workingSets) {
@Override
protected List<IProject> doCreateMavenProjects(IProgressMonitor monitor) throws CoreException {
Set<MavenProjectInfo> projectSet = MavenPlugin.getProjectConfigurationManager().collectProjects(projects);
List<IMavenProjectImportResult> results = MavenPlugin.getProjectConfigurationManager().importProjects(
projectSet, configuration, monitor);
return toProjects(results);
}
};
ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory()
.modifyRule(ResourcesPlugin.getWorkspace().getRoot());
job.setRule(rule);
job.schedule();
} else {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
}
}
protected void cleanup(List<String> locations) {
for(String location : locations) {
try {
FileUtils.deleteDirectory(location);
} catch(IOException ex) {
String msg = "Can't delete " + location + "; " + (ex.getMessage() == null ? ex.toString() : ex.getMessage()); //$NON-NLS-1$
log.error(msg, ex);
}
}
}
}
}
| true | true | public void done(IJobChangeEvent event) {
IStatus result = event.getResult();
if(result.getSeverity() == IStatus.CANCEL) {
return;
} else if(!result.isOK()) {
// XXX report errors
return;
}
if(projects.isEmpty()) {
log.info("No Maven projects to import");
if(collectedLocations.size()==1) {
final String location = collectedLocations.get(0);
DirectoryScanner projectScanner = new DirectoryScanner();
projectScanner.setBasedir(location);
projectScanner.setIncludes(new String[] {"**/.project"}); //$NON-NLS-1$
projectScanner.scan();
String[] projectFiles = projectScanner.getIncludedFiles();
if(projectFiles!=null && projectFiles.length>0) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm_title, //
Messages.MavenProjectCheckoutJob_confirm_message);
if(res) {
IWizard wizard = new ExternalProjectImportWizard(collectedLocations.get(0));
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
wizard);
dialog.open();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm2_title, //
Messages.MavenProjectCheckoutJob_confirm2_message);
if(res) {
Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay());
clipboard.setContents(new Object[] { location }, new Transfer[] { TextTransfer.getInstance() });
NewProjectAction newProjectAction = new NewProjectAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
newProjectAction.run();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
cleanup(collectedLocations);
}
if(checkoutAllProjects) {
if(M2EUIPluginActivator.getDefault().getMavenDiscovery() != null) {
final LifecycleMappingConfiguration mappingConfiguration = LifecycleMappingConfiguration.calculate(projects,
configuration, new NullProgressMonitor());
if(!mappingConfiguration.isMappingComplete()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations,
mappingConfiguration);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
return;
}
}
WorkspaceJob job = new AbstactCreateMavenProjectJob(Messages.MavenProjectCheckoutJob_job, workingSets) {
@Override
protected List<IProject> doCreateMavenProjects(IProgressMonitor monitor) throws CoreException {
Set<MavenProjectInfo> projectSet = MavenPlugin.getProjectConfigurationManager().collectProjects(projects);
List<IMavenProjectImportResult> results = MavenPlugin.getProjectConfigurationManager().importProjects(
projectSet, configuration, monitor);
return toProjects(results);
}
};
ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory()
.modifyRule(ResourcesPlugin.getWorkspace().getRoot());
job.setRule(rule);
job.schedule();
} else {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
}
}
| public void done(IJobChangeEvent event) {
IStatus result = event.getResult();
if(result.getSeverity() == IStatus.CANCEL) {
return;
} else if(!result.isOK()) {
// XXX report errors
return;
}
if(projects.isEmpty()) {
log.info("No Maven projects to import");
if(collectedLocations.size()==1) {
final String location = collectedLocations.get(0);
DirectoryScanner projectScanner = new DirectoryScanner();
projectScanner.setBasedir(location);
projectScanner.setIncludes(new String[] {"**/.project"}); //$NON-NLS-1$
projectScanner.scan();
String[] projectFiles = projectScanner.getIncludedFiles();
if(projectFiles!=null && projectFiles.length>0) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm_title, //
Messages.MavenProjectCheckoutJob_confirm_message);
if(res) {
IWizard wizard = new ExternalProjectImportWizard(collectedLocations.get(0));
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
wizard);
dialog.open();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
public void run() {
boolean res = MessageDialog.openConfirm(PlatformUI.getWorkbench().getDisplay().getActiveShell(), //
Messages.MavenProjectCheckoutJob_confirm2_title, //
Messages.MavenProjectCheckoutJob_confirm2_message);
if(res) {
Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay());
clipboard.setContents(new Object[] { location }, new Transfer[] { TextTransfer.getInstance() });
NewProjectAction newProjectAction = new NewProjectAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow());
newProjectAction.run();
} else {
cleanup(collectedLocations);
}
}
});
return;
}
cleanup(collectedLocations);
}
if(checkoutAllProjects) {
if(M2EUIPluginActivator.getDefault().getMavenDiscovery() != null) {
final LifecycleMappingConfiguration mappingConfiguration = LifecycleMappingConfiguration.calculate(projects,
configuration, new NullProgressMonitor());
if(!mappingConfiguration.isMappingComplete(true)) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations,
mappingConfiguration);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
return;
}
}
WorkspaceJob job = new AbstactCreateMavenProjectJob(Messages.MavenProjectCheckoutJob_job, workingSets) {
@Override
protected List<IProject> doCreateMavenProjects(IProgressMonitor monitor) throws CoreException {
Set<MavenProjectInfo> projectSet = MavenPlugin.getProjectConfigurationManager().collectProjects(projects);
List<IMavenProjectImportResult> results = MavenPlugin.getProjectConfigurationManager().importProjects(
projectSet, configuration, monitor);
return toProjects(results);
}
};
ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory()
.modifyRule(ResourcesPlugin.getWorkspace().getRoot());
job.setRule(rule);
job.schedule();
} else {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MavenImportWizard wizard = new MavenImportWizard(configuration, collectedLocations);
WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), wizard);
int res = dialog.open();
if(res == Window.CANCEL) {
cleanup(collectedLocations);
}
}
});
}
}
|
diff --git a/wayback-core/src/test/java/org/archive/wayback/accesscontrol/robotstxt/RobotExclusionFilterTest.java b/wayback-core/src/test/java/org/archive/wayback/accesscontrol/robotstxt/RobotExclusionFilterTest.java
index 43d513b5a..2a5f284fd 100644
--- a/wayback-core/src/test/java/org/archive/wayback/accesscontrol/robotstxt/RobotExclusionFilterTest.java
+++ b/wayback-core/src/test/java/org/archive/wayback/accesscontrol/robotstxt/RobotExclusionFilterTest.java
@@ -1,82 +1,82 @@
/*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.wayback.accesscontrol.robotstxt;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
/**
*
*
* @author brad
* @version $Date$, $Revision$
*/
public class RobotExclusionFilterTest extends TestCase {
/**
*
*/
public void testFoo() {
String re = "^www[0-9]+\\.";
Pattern p = Pattern.compile(re);
String url = "www4.archive.org";
Matcher m = p.matcher(url);
assertTrue(m.find());
}
/**
*
*/
protected final static String HTTP_PREFIX = "http://";
public void testSearchResultToRobotUrlStrings() {
RobotExclusionFilter f = new RobotExclusionFilter(null,"",100);
String test1[] = {"www.foo.com","foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.foo.com", HTTP_PREFIX),test1);
- String test2[] = {"www.foo.com","foo.com"};
+ String test2[] = {"foo.com","www.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("foo.com", HTTP_PREFIX),test2);
- String test3[] = {"www.fool.foo.com","fool.foo.com"};
+ String test3[] = {"fool.foo.com","www.fool.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("fool.foo.com", HTTP_PREFIX),test3);
String test4[] = {"www.foo.com","foo.com", "www4.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4.foo.com", HTTP_PREFIX),test4);
String test5[] = {"www4w.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4w.foo.com", HTTP_PREFIX),test5);
String test6[] = {"www.www.foo.com","www.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.www.foo.com", HTTP_PREFIX),test6);
}
private void compareListTo(List<String> list, String strings[]) {
assertEquals(list.size(), strings.length);
for(int i = 0; i < strings.length; i++) {
String listS = list.get(i);
String arrayS = "http://" + strings[i] + "/robots.txt";
assertEquals(listS, arrayS);
}
}
}
| false | true | public void testSearchResultToRobotUrlStrings() {
RobotExclusionFilter f = new RobotExclusionFilter(null,"",100);
String test1[] = {"www.foo.com","foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.foo.com", HTTP_PREFIX),test1);
String test2[] = {"www.foo.com","foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("foo.com", HTTP_PREFIX),test2);
String test3[] = {"www.fool.foo.com","fool.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("fool.foo.com", HTTP_PREFIX),test3);
String test4[] = {"www.foo.com","foo.com", "www4.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4.foo.com", HTTP_PREFIX),test4);
String test5[] = {"www4w.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4w.foo.com", HTTP_PREFIX),test5);
String test6[] = {"www.www.foo.com","www.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.www.foo.com", HTTP_PREFIX),test6);
}
| public void testSearchResultToRobotUrlStrings() {
RobotExclusionFilter f = new RobotExclusionFilter(null,"",100);
String test1[] = {"www.foo.com","foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.foo.com", HTTP_PREFIX),test1);
String test2[] = {"foo.com","www.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("foo.com", HTTP_PREFIX),test2);
String test3[] = {"fool.foo.com","www.fool.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("fool.foo.com", HTTP_PREFIX),test3);
String test4[] = {"www.foo.com","foo.com", "www4.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4.foo.com", HTTP_PREFIX),test4);
String test5[] = {"www4w.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www4w.foo.com", HTTP_PREFIX),test5);
String test6[] = {"www.www.foo.com","www.foo.com"};
compareListTo(f.searchResultToRobotUrlStrings("www.www.foo.com", HTTP_PREFIX),test6);
}
|
diff --git a/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/custom/TableEditor.java b/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/custom/TableEditor.java
index aca2dd363..4c4cff71e 100644
--- a/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/custom/TableEditor.java
+++ b/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/custom/TableEditor.java
@@ -1,281 +1,286 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.custom;
import org.eclipse.rwt.internal.theme.ThemeManager;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.internal.widgets.textkit.TextThemeAdapter;
import org.eclipse.swt.widgets.*;
/**
*
* A TableEditor is a manager for a Control that appears above a cell in a Table and tracks with the
* moving and resizing of that cell. It can be used to display a text widget above a cell
* in a Table so that the user can edit the contents of that cell. It can also be used to display
* a button that can launch a dialog for modifying the contents of the associated cell.
*
* <p> Here is an example of using a TableEditor:
* <code><pre>
* final Table table = new Table(shell, SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
* TableColumn column1 = new TableColumn(table, SWT.NONE);
* TableColumn column2 = new TableColumn(table, SWT.NONE);
* for (int i = 0; i < 10; i++) {
* TableItem item = new TableItem(table, SWT.NONE);
* item.setText(new String[] {"item " + i, "edit this value"});
* }
* column1.pack();
* column2.pack();
*
* final TableEditor editor = new TableEditor(table);
* //The editor must have the same size as the cell and must
* //not be any smaller than 50 pixels.
* editor.horizontalAlignment = SWT.LEFT;
* editor.grabHorizontal = true;
* editor.minimumWidth = 50;
* // editing the second column
* final int EDITABLECOLUMN = 1;
*
* table.addSelectionListener(new SelectionAdapter() {
* public void widgetSelected(SelectionEvent e) {
* // Clean up any previous editor control
* Control oldEditor = editor.getEditor();
* if (oldEditor != null) oldEditor.dispose();
*
* // Identify the selected row
* TableItem item = (TableItem)e.item;
* if (item == null) return;
*
* // The control that will be the editor must be a child of the Table
* Text newEditor = new Text(table, SWT.NONE);
* newEditor.setText(item.getText(EDITABLECOLUMN));
* newEditor.addModifyListener(new ModifyListener() {
* public void modifyText(ModifyEvent e) {
* Text text = (Text)editor.getEditor();
* editor.getItem().setText(EDITABLECOLUMN, text.getText());
* }
* });
* newEditor.selectAll();
* newEditor.setFocus();
* editor.setEditor(newEditor, item, EDITABLECOLUMN);
* }
* });
* </pre></code>
*
* <!--
* @see <a href="http://www.eclipse.org/swt/snippets/#tableeditor">TableEditor snippets</a>
* @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
* -->
*
* @since 1.2
*/
public class TableEditor extends ControlEditor {
Table table;
TableItem item;
int column = -1;
ControlListener columnListener;
Runnable timer;
static final int TIMEOUT = 1500;
/**
* Creates a TableEditor for the specified Table.
*
* @param table the Table Control above which this editor will be displayed
*
*/
public TableEditor (Table table) {
super(table);
this.table = table;
columnListener = new ControlListener() {
public void controlMoved(ControlEvent e){
layout ();
}
public void controlResized(ControlEvent e){
layout ();
}
};
timer = new Runnable () {
public void run() {
layout ();
}
};
// To be consistent with older versions of SWT, grabVertical defaults to true
grabVertical = true;
}
Rectangle computeBounds () {
if (item == null || column == -1 || item.isDisposed()) return new Rectangle(0, 0, 0, 0);
Rectangle cell = item.getBounds(column);
Rectangle rect = item.getImageBounds(column);
- cell.x = rect.x + rect.width;
- cell.width -= rect.width;
+ // [rst] Fix for bug 269065: [TableEditor] Cell editors misaligned when cell
+ // padding is set on table
+ // https://bugs.eclipse.org/bugs/show_bug.cgi?id=269065
+ if( rect.width > 0 ) {
+ cell.width -= rect.width + rect.x - cell.x;
+ cell.x = rect.x + rect.width;
+ }
Rectangle area = table.getClientArea();
if (cell.x < area.x + area.width) {
if (cell.x + cell.width > area.x + area.width) {
cell.width = area.x + area.width - cell.x;
}
}
Rectangle editorRect = new Rectangle(cell.x, cell.y, minimumWidth, minimumHeight);
if (grabHorizontal) {
editorRect.width = Math.max(cell.width, minimumWidth);
}
if (grabVertical) {
editorRect.height = Math.max(cell.height, minimumHeight);
}
if (horizontalAlignment == SWT.RIGHT) {
editorRect.x += cell.width - editorRect.width;
} else if (horizontalAlignment == SWT.LEFT) {
// do nothing - cell.x is the right answer
} else { // default is CENTER
editorRect.x += (cell.width - editorRect.width)/2;
}
if (verticalAlignment == SWT.BOTTOM) {
editorRect.y += cell.height - editorRect.height;
} else if (verticalAlignment == SWT.TOP) {
// do nothing - cell.y is the right answer
} else { // default is CENTER
editorRect.y += (cell.height - editorRect.height)/2;
}
// TODO [rst] Increase editor size since the Text widget cuts off text if it's
// smaller than text height + padding + 2
// See bug 255187: Table cell editor geometry problems
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=255187
if( editor instanceof Text ) {
Text text = ( Text )editor;
ThemeManager themeManager = ThemeManager.getInstance();
TextThemeAdapter themeAdapter
= ( TextThemeAdapter )themeManager.getThemeAdapter( Text.class );
Rectangle padding = themeAdapter.getPadding( text );
editorRect.x -= padding.x;
editorRect.y -= padding.y - 1;
editorRect.width += padding.width;
editorRect.height += padding.height - 2;
}
return editorRect;
}
/**
* Removes all associations between the TableEditor and the cell in the table. The
* Table and the editor Control are <b>not</b> disposed.
*/
public void dispose () {
if (table != null && !table.isDisposed()) {
if (this.column > -1 && this.column < table.getColumnCount()){
TableColumn tableColumn = table.getColumn(this.column);
tableColumn.removeControlListener(columnListener);
}
}
columnListener = null;
table = null;
item = null;
column = -1;
timer = null;
super.dispose();
}
/**
* Returns the zero based index of the column of the cell being tracked by this editor.
*
* @return the zero based index of the column of the cell being tracked by this editor
*/
public int getColumn () {
return column;
}
/**
* Returns the TableItem for the row of the cell being tracked by this editor.
*
* @return the TableItem for the row of the cell being tracked by this editor
*/
public TableItem getItem () {
return item;
}
void resize () {
layout();
// /*
// * On some platforms, the table scrolls when an item that
// * is partially visible at the bottom of the table is
// * selected. Ensure that the correct row is edited by
// * laying out one more time in a timerExec().
// */
// if (table != null) {
// Display display = table.getDisplay();
// display.timerExec(-1, timer);
// display.timerExec(TIMEOUT, timer);
// }
}
/**
* Sets the zero based index of the column of the cell being tracked by this editor.
*
* @param column the zero based index of the column of the cell being tracked by this editor
*/
public void setColumn(int column) {
int columnCount = table.getColumnCount();
// Separately handle the case where the table has no TableColumns.
// In this situation, there is a single default column.
if (columnCount == 0) {
this.column = (column == 0) ? 0 : -1;
resize();
return;
}
if (this.column > -1 && this.column < columnCount){
TableColumn tableColumn = table.getColumn(this.column);
tableColumn.removeControlListener(columnListener);
this.column = -1;
}
if (column < 0 || column >= table.getColumnCount()) return;
this.column = column;
TableColumn tableColumn = table.getColumn(this.column);
tableColumn.addControlListener(columnListener);
resize();
}
/**
* Specifies the <code>TableItem</code> that is to be edited.
*
* @param item the item to be edited
*/
public void setItem (TableItem item) {
this.item = item;
resize();
}
public void setEditor (Control editor) {
super.setEditor(editor);
resize();
}
/**
* Specify the Control that is to be displayed and the cell in the table that it is to be positioned above.
*
* <p>Note: The Control provided as the editor <b>must</b> be created with its parent being the Table control
* specified in the TableEditor constructor.
*
* @param editor the Control that is displayed above the cell being edited
* @param item the TableItem for the row of the cell being tracked by this editor
* @param column the zero based index of the column of the cell being tracked by this editor
*/
public void setEditor (Control editor, TableItem item, int column) {
setItem(item);
setColumn(column);
setEditor(editor);
}
public void layout () {
if (table == null || table.isDisposed()) return;
if (item == null || item.isDisposed()) return;
int columnCount = table.getColumnCount();
if (columnCount == 0 && column != 0) return;
if (columnCount > 0 && (column < 0 || column >= columnCount)) return;
super.layout();
}
}
| true | true | Rectangle computeBounds () {
if (item == null || column == -1 || item.isDisposed()) return new Rectangle(0, 0, 0, 0);
Rectangle cell = item.getBounds(column);
Rectangle rect = item.getImageBounds(column);
cell.x = rect.x + rect.width;
cell.width -= rect.width;
Rectangle area = table.getClientArea();
if (cell.x < area.x + area.width) {
if (cell.x + cell.width > area.x + area.width) {
cell.width = area.x + area.width - cell.x;
}
}
Rectangle editorRect = new Rectangle(cell.x, cell.y, minimumWidth, minimumHeight);
if (grabHorizontal) {
editorRect.width = Math.max(cell.width, minimumWidth);
}
if (grabVertical) {
editorRect.height = Math.max(cell.height, minimumHeight);
}
if (horizontalAlignment == SWT.RIGHT) {
editorRect.x += cell.width - editorRect.width;
} else if (horizontalAlignment == SWT.LEFT) {
// do nothing - cell.x is the right answer
} else { // default is CENTER
editorRect.x += (cell.width - editorRect.width)/2;
}
if (verticalAlignment == SWT.BOTTOM) {
editorRect.y += cell.height - editorRect.height;
} else if (verticalAlignment == SWT.TOP) {
// do nothing - cell.y is the right answer
} else { // default is CENTER
editorRect.y += (cell.height - editorRect.height)/2;
}
// TODO [rst] Increase editor size since the Text widget cuts off text if it's
// smaller than text height + padding + 2
// See bug 255187: Table cell editor geometry problems
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=255187
if( editor instanceof Text ) {
Text text = ( Text )editor;
ThemeManager themeManager = ThemeManager.getInstance();
TextThemeAdapter themeAdapter
= ( TextThemeAdapter )themeManager.getThemeAdapter( Text.class );
Rectangle padding = themeAdapter.getPadding( text );
editorRect.x -= padding.x;
editorRect.y -= padding.y - 1;
editorRect.width += padding.width;
editorRect.height += padding.height - 2;
}
return editorRect;
}
| Rectangle computeBounds () {
if (item == null || column == -1 || item.isDisposed()) return new Rectangle(0, 0, 0, 0);
Rectangle cell = item.getBounds(column);
Rectangle rect = item.getImageBounds(column);
// [rst] Fix for bug 269065: [TableEditor] Cell editors misaligned when cell
// padding is set on table
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=269065
if( rect.width > 0 ) {
cell.width -= rect.width + rect.x - cell.x;
cell.x = rect.x + rect.width;
}
Rectangle area = table.getClientArea();
if (cell.x < area.x + area.width) {
if (cell.x + cell.width > area.x + area.width) {
cell.width = area.x + area.width - cell.x;
}
}
Rectangle editorRect = new Rectangle(cell.x, cell.y, minimumWidth, minimumHeight);
if (grabHorizontal) {
editorRect.width = Math.max(cell.width, minimumWidth);
}
if (grabVertical) {
editorRect.height = Math.max(cell.height, minimumHeight);
}
if (horizontalAlignment == SWT.RIGHT) {
editorRect.x += cell.width - editorRect.width;
} else if (horizontalAlignment == SWT.LEFT) {
// do nothing - cell.x is the right answer
} else { // default is CENTER
editorRect.x += (cell.width - editorRect.width)/2;
}
if (verticalAlignment == SWT.BOTTOM) {
editorRect.y += cell.height - editorRect.height;
} else if (verticalAlignment == SWT.TOP) {
// do nothing - cell.y is the right answer
} else { // default is CENTER
editorRect.y += (cell.height - editorRect.height)/2;
}
// TODO [rst] Increase editor size since the Text widget cuts off text if it's
// smaller than text height + padding + 2
// See bug 255187: Table cell editor geometry problems
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=255187
if( editor instanceof Text ) {
Text text = ( Text )editor;
ThemeManager themeManager = ThemeManager.getInstance();
TextThemeAdapter themeAdapter
= ( TextThemeAdapter )themeManager.getThemeAdapter( Text.class );
Rectangle padding = themeAdapter.getPadding( text );
editorRect.x -= padding.x;
editorRect.y -= padding.y - 1;
editorRect.width += padding.width;
editorRect.height += padding.height - 2;
}
return editorRect;
}
|
diff --git a/src/cz/cvut/localtrade/FilterDialogFragment.java b/src/cz/cvut/localtrade/FilterDialogFragment.java
index d851096..9a2e51d 100644
--- a/src/cz/cvut/localtrade/FilterDialogFragment.java
+++ b/src/cz/cvut/localtrade/FilterDialogFragment.java
@@ -1,42 +1,42 @@
package cz.cvut.localtrade;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ScrollView;
public class FilterDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ScrollView v = new ScrollView(getActivity());
v.setPadding(15, 15, 15, 15);
v.addView(inflater.inflate(R.layout.filter_items_dialog, null));
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
- builder.setPositiveButton(R.string.cancel,
+ builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
| true | true | public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ScrollView v = new ScrollView(getActivity());
v.setPadding(15, 15, 15, 15);
v.addView(inflater.inflate(R.layout.filter_items_dialog, null));
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
| public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ScrollView v = new ScrollView(getActivity());
v.setPadding(15, 15, 15, 15);
v.addView(inflater.inflate(R.layout.filter_items_dialog, null));
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
|
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java
index 907aaebb8..596849967 100644
--- a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java
+++ b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java
@@ -1,391 +1,393 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text.link;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
/**
* A group of positions in multiple documents that are simultaneously modified -
* if one gets edited, all other positions in a <code>PositionGroup</code>
* are edited the same way. All linked positions in a group have the same
* content.
* <p>
* Normally, new positions are given a tab stop weight which can be used by
* clients, e.g. the UI. If no weight is given, a position will not be visited.
* If no weights are used at all, the first position in a document is taken as
* the only stop as to comply with the behavior of the old linked position
* infrastructure.
* </p>
* <p>
* Clients may instantiate this class.
* </p>
*
* @since 3.0
*/
public class LinkedPositionGroup {
/** Sequence constant declaring that a position should not be stopped by. */
public static final int NO_STOP= -1;
/* members */
/** The linked positions of this group. */
private final List fPositions= new LinkedList();
/** Whether we are sealed or not. */
private boolean fIsSealed= false;
/**
* <code>true</code> if there are custom iteration weights. For backward
* compatibility.
*/
private boolean fHasCustomIteration= false;
/*
* iteration variables, set to communicate state between isLegalEvent and
* handleEvent
*/
/** The position including the most recent <code>DocumentEvent</code>. */
private LinkedPosition fLastPosition;
/** The region covered by <code>fLastPosition</code> before the document
* change.
*/
private IRegion fLastRegion;
/**
* Adds a position to this group. The document region defined by the
* position must contain the same content (and thus have the same length) as
* any of the other positions already in this group. Additionally, all
* positions added must be disjoint; otherwise a
* <code>BadLocationException</code> is thrown.
* <p>
* Positions added using this method are owned by this group afterwards and
* may not be updated or modified thereafter.
* </p>
* <p>
* Once a group has been added to a <code>LinkedModeModel</code>, it
* becomes <em>sealed</em> and no positions may be added any more.
* </p>
*
* @param position the position to add
* @throws BadLocationException if the position is invalid or conflicts with
* other positions in the group
* @throws IllegalStateException if the group has already been added to a
* model
*/
public void addPosition(LinkedPosition position) throws BadLocationException {
/*
* Enforces constraints and sets the custom iteration flag. If the
* position is already in this group, nothing happens.
*/
Assert.isNotNull(position);
if (fIsSealed)
throw new IllegalStateException("cannot add positions after the group is added to an model"); //$NON-NLS-1$
if (!fPositions.contains(position)) {
enforceDisjoint(position);
enforceEqualContent(position);
fPositions.add(position);
fHasCustomIteration |= position.getSequenceNumber() != LinkedPositionGroup.NO_STOP;
} else
return; // nothing happens
}
/**
* Enforces the invariant that all positions must contain the same string.
*
* @param position the position to check
* @throws BadLocationException if the equal content check fails
*/
private void enforceEqualContent(LinkedPosition position) throws BadLocationException {
if (fPositions.size() > 0) {
String groupContent= ((LinkedPosition) fPositions.get(0)).getContent();
String positionContent= position.getContent();
if (!groupContent.equals(positionContent))
throw new BadLocationException();
}
}
/**
* Enforces the invariant that all positions must be disjoint.
*
* @param position the position to check
* @throws BadLocationException if the disjointness check fails
*/
private void enforceDisjoint(LinkedPosition position) throws BadLocationException {
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (p.overlapsWith(position))
throw new BadLocationException();
}
}
/**
* Enforces the disjointness for another group
*
* @param group the group to check
* @throws BadLocationException if the disjointness check fails
*/
void enforceDisjoint(LinkedPositionGroup group) throws BadLocationException {
Assert.isNotNull(group);
for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
enforceDisjoint(p);
}
}
/**
* Checks whether <code>event</code> is a legal event for this group. An
* event is legal if it touches at most one position contained within this
* group.
*
* @param event the document event to check
* @return <code>true</code> if <code>event</code> is legal
*/
boolean isLegalEvent(DocumentEvent event) {
fLastPosition= null;
fLastRegion= null;
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition pos= (LinkedPosition) it.next();
if (overlapsOrTouches(pos, event)) {
if (fLastPosition != null) {
fLastPosition= null;
fLastRegion= null;
return false;
}
fLastPosition= pos;
fLastRegion= new Region(pos.getOffset(), pos.getLength());
}
}
return true;
}
/**
* Checks whether the given event touches the given position. To touch means
* to overlap or come up to the borders of the position.
*
* @param position the position
* @param event the event
* @return <code>true</code> if <code>position</code> and
* <code>event</code> are not absolutely disjoint
*/
private boolean overlapsOrTouches(LinkedPosition position, DocumentEvent event) {
return position.getDocument().equals(event.getDocument()) && position.getOffset() <= event.getOffset() + event.getLength() && position.getOffset() + position.getLength() >= event.getOffset();
}
/**
* Creates an edition of a document change that will forward any
* modification in one position to all linked siblings. The return value is
* a map from <code>IDocument</code> to <code>TextEdit</code>.
*
* @param event the document event to check
* @return a map of edits, grouped by edited document, or <code>null</code>
* if there are no edits
*/
Map handleEvent(DocumentEvent event) {
if (fLastPosition != null) {
Map map= new HashMap();
int relativeOffset= event.getOffset() - fLastRegion.getOffset();
if (relativeOffset < 0) {
relativeOffset= 0;
}
int eventEnd= event.getOffset() + event.getLength();
int lastEnd= fLastRegion.getOffset() + fLastRegion.getLength();
int length;
if (eventEnd > lastEnd)
length= lastEnd - relativeOffset - fLastRegion.getOffset();
else
length= eventEnd - relativeOffset - fLastRegion.getOffset();
String text= event.getText(); //$NON-NLS-1$
+ if (text == null)
+ text= ""; //$NON-NLS-1$
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (p == fLastPosition || p.isDeleted())
continue; // don't re-update the origin of the change
List edits= (List) map.get(p.getDocument());
if (edits == null) {
edits= new ArrayList();
map.put(p.getDocument(), edits);
}
edits.add(new ReplaceEdit(p.getOffset() + relativeOffset, length, text));
}
for (Iterator it= map.keySet().iterator(); it.hasNext(); ) {
IDocument d= (IDocument) it.next();
TextEdit edit= new MultiTextEdit(0, d.getLength());
edit.addChildren((TextEdit[]) ((List) map.get(d)).toArray(new TextEdit[0]));
map.put(d, edit);
}
return map;
}
return null;
}
/**
* Sets the model of this group. Once a model has been set, no
* more positions can be added and the model cannot be changed.
*/
void seal() {
Assert.isTrue(!fIsSealed);
fIsSealed= true;
if (fHasCustomIteration == false && fPositions.size() > 0) {
((LinkedPosition) fPositions.get(0)).setSequenceNumber(0);
}
}
IDocument[] getDocuments() {
IDocument[] docs= new IDocument[fPositions.size()];
int i= 0;
for (Iterator it= fPositions.iterator(); it.hasNext(); i++) {
LinkedPosition pos= (LinkedPosition) it.next();
docs[i]= pos.getDocument();
}
return docs;
}
void register(LinkedModeModel model) throws BadLocationException {
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition pos= (LinkedPosition) it.next();
model.register(pos);
}
}
/**
* Returns the position in this group that encompasses all positions in
* <code>group</code>.
*
* @param group the group to be adopted
* @return a position in the receiver that contains all positions in <code>group</code>,
* or <code>null</code> if none can be found
* @throws BadLocationException if more than one position are affected by
* <code>group</code>
*/
LinkedPosition adopt(LinkedPositionGroup group) throws BadLocationException {
LinkedPosition found= null;
for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) {
LinkedPosition pos= (LinkedPosition) it.next();
LinkedPosition localFound= null;
for (Iterator it2= fPositions.iterator(); it2.hasNext(); ) {
LinkedPosition myPos= (LinkedPosition) it2.next();
if (myPos.includes(pos)) {
if (found == null)
found= myPos;
else if (found != myPos)
throw new BadLocationException();
if (localFound == null)
localFound= myPos;
}
}
if (localFound != found)
throw new BadLocationException();
}
return found;
}
/**
* Finds the closest position to <code>toFind</code>.
*
* @param toFind the linked position for which to find the closest position
* @return the closest position to <code>toFind</code>.
*/
LinkedPosition getPosition(LinkedPosition toFind) {
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (p.includes(toFind))
return p;
}
return null;
}
/**
* Returns <code>true</code> if <code>offset</code> is contained in any
* position in this group.
*
* @param offset the offset to check
* @return <code>true</code> if offset is contained by this group
*/
boolean contains(int offset) {
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition pos= (LinkedPosition) it.next();
if (pos.includes(offset)) {
return true;
}
}
return false;
}
/**
* Returns whether this group contains any positions.
*
* @return <code>true</code> if this group is empty, <code>false</code>
* if it is not
*/
public boolean isEmtpy() {
return fPositions.size() == 0;
}
/**
* Returns the positions contained in the receiver as an array. The
* positions are the actual positions and must not be modified; the array
* is a copy of internal structures.
*
* @return the positions of this group in no particular order
*/
public LinkedPosition[] getPositions() {
return (LinkedPosition[]) fPositions.toArray(new LinkedPosition[0]);
}
/**
* Returns <code>true</code> if the receiver contains <code>position</code>.
*
* @param position the position to check
* @return <code>true</code> if the receiver contains <code>position</code>
*/
boolean contains(Position position) {
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (position.equals(p))
return true;
}
return false;
}
}
| true | true | Map handleEvent(DocumentEvent event) {
if (fLastPosition != null) {
Map map= new HashMap();
int relativeOffset= event.getOffset() - fLastRegion.getOffset();
if (relativeOffset < 0) {
relativeOffset= 0;
}
int eventEnd= event.getOffset() + event.getLength();
int lastEnd= fLastRegion.getOffset() + fLastRegion.getLength();
int length;
if (eventEnd > lastEnd)
length= lastEnd - relativeOffset - fLastRegion.getOffset();
else
length= eventEnd - relativeOffset - fLastRegion.getOffset();
String text= event.getText(); //$NON-NLS-1$
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (p == fLastPosition || p.isDeleted())
continue; // don't re-update the origin of the change
List edits= (List) map.get(p.getDocument());
if (edits == null) {
edits= new ArrayList();
map.put(p.getDocument(), edits);
}
edits.add(new ReplaceEdit(p.getOffset() + relativeOffset, length, text));
}
for (Iterator it= map.keySet().iterator(); it.hasNext(); ) {
IDocument d= (IDocument) it.next();
TextEdit edit= new MultiTextEdit(0, d.getLength());
edit.addChildren((TextEdit[]) ((List) map.get(d)).toArray(new TextEdit[0]));
map.put(d, edit);
}
return map;
}
return null;
}
| Map handleEvent(DocumentEvent event) {
if (fLastPosition != null) {
Map map= new HashMap();
int relativeOffset= event.getOffset() - fLastRegion.getOffset();
if (relativeOffset < 0) {
relativeOffset= 0;
}
int eventEnd= event.getOffset() + event.getLength();
int lastEnd= fLastRegion.getOffset() + fLastRegion.getLength();
int length;
if (eventEnd > lastEnd)
length= lastEnd - relativeOffset - fLastRegion.getOffset();
else
length= eventEnd - relativeOffset - fLastRegion.getOffset();
String text= event.getText(); //$NON-NLS-1$
if (text == null)
text= ""; //$NON-NLS-1$
for (Iterator it= fPositions.iterator(); it.hasNext(); ) {
LinkedPosition p= (LinkedPosition) it.next();
if (p == fLastPosition || p.isDeleted())
continue; // don't re-update the origin of the change
List edits= (List) map.get(p.getDocument());
if (edits == null) {
edits= new ArrayList();
map.put(p.getDocument(), edits);
}
edits.add(new ReplaceEdit(p.getOffset() + relativeOffset, length, text));
}
for (Iterator it= map.keySet().iterator(); it.hasNext(); ) {
IDocument d= (IDocument) it.next();
TextEdit edit= new MultiTextEdit(0, d.getLength());
edit.addChildren((TextEdit[]) ((List) map.get(d)).toArray(new TextEdit[0]));
map.put(d, edit);
}
return map;
}
return null;
}
|
diff --git a/onebusaway-transit-data-federation-builder/src/main/java/org/onebusaway/transit_data_federation/bundle/FederatedTransitDataBundleCreatorMain.java b/onebusaway-transit-data-federation-builder/src/main/java/org/onebusaway/transit_data_federation/bundle/FederatedTransitDataBundleCreatorMain.java
index c4b5ad27..2ae35b29 100644
--- a/onebusaway-transit-data-federation-builder/src/main/java/org/onebusaway/transit_data_federation/bundle/FederatedTransitDataBundleCreatorMain.java
+++ b/onebusaway-transit-data-federation-builder/src/main/java/org/onebusaway/transit_data_federation/bundle/FederatedTransitDataBundleCreatorMain.java
@@ -1,343 +1,340 @@
/**
* Copyright (C) 2011 Brian Ferris <[email protected]>
* Copyright (C) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onebusaway.transit_data_federation.bundle;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl;
import org.onebusaway.transit_data_federation.bundle.model.GtfsBundle;
import org.onebusaway.transit_data_federation.bundle.model.GtfsBundles;
import org.opentripplanner.graph_builder.impl.osm.FileBasedOpenStreetMapProviderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* Command line tool for federated transit data bundle creator. Allows
* {@link FederatedTransitDataBundleCreator} to configured and run from the
* command line.
*
* @author bdferris
* @see FederatedTransitDataBundleCreator
*/
public class FederatedTransitDataBundleCreatorMain {
private static final Logger _log = LoggerFactory.getLogger(FederatedTransitDataBundleCreatorMain.class);
private static final String ARG_SKIP_TO = "skipTo";
private static final String ARG_ONLY = "only";
private static final String ARG_SKIP = "skip";
private static final String ARG_INCLUDE = "include";
private static final String ARG_ONLY_IF_DNE = "onlyIfDoesNotExist";
private static final String ARG_USE_DATABASE_FOR_GTFS = "useDatabaseForGtfs";
private static final String ARG_DATASOURCE_DRIVER_CLASS_NAME = "dataSourceDriverClassName";
private static final String ARG_DATASOURCE_URL = "dataSourceUrl";
private static final String ARG_DATASOURCE_USERNAME = "dataSourceUsername";
private static final String ARG_DATASOURCE_PASSWORD = "dataSourcePassword";
private static final String ARG_BUNDLE_KEY = "bundleKey";
private static final String ARG_RANDOMIZE_CACHE_DIR = "randomizeCacheDir";
private static final String ARG_ADDITIONAL_RESOURCES_DIRECTORY = "additionalResourcesDirectory";
private static final String ARG_OSM = "osm";
public static void main(String[] args) throws IOException,
ClassNotFoundException {
FederatedTransitDataBundleCreatorMain main = new FederatedTransitDataBundleCreatorMain();
main.run(args);
}
public void run(String[] args) {
try {
Parser parser = new GnuParser();
Options options = new Options();
buildOptions(options);
CommandLine commandLine = parser.parse(options, args);
String[] remainingArgs = commandLine.getArgs();
if (remainingArgs.length < 2) {
printUsage();
System.exit(-1);
}
FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator();
Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>();
creator.setContextBeans(beans);
List<GtfsBundle> gtfsBundles = new ArrayList<GtfsBundle>();
List<String> contextPaths = new ArrayList<String>();
for (int i = 0; i < remainingArgs.length - 1; i++) {
File path = new File(remainingArgs[i]);
if (path.isDirectory() || path.getName().endsWith(".zip")) {
GtfsBundle gtfsBundle = new GtfsBundle();
gtfsBundle.setPath(path);
gtfsBundles.add(gtfsBundle);
} else {
contextPaths.add("file:" + path);
}
}
if (!gtfsBundles.isEmpty()) {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class);
bean.addPropertyValue("bundles", gtfsBundles);
beans.put("gtfs-bundles", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_USE_DATABASE_FOR_GTFS)) {
contextPaths.add("classpath:org/onebusaway/gtfs/application-context.xml");
- // HibernateGtfsRelationalDaoImpl store = new
- // HibernateGtfsRelationalDaoImpl();
- // store.setSessionFactory(_sessionFactory);
} else {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsRelationalDaoImpl.class);
beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_DATASOURCE_URL)) {
String dataSourceUrl = commandLine.getOptionValue(ARG_DATASOURCE_URL);
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(DriverManagerDataSource.class);
bean.addPropertyValue("url", dataSourceUrl);
if (commandLine.hasOption(ARG_DATASOURCE_DRIVER_CLASS_NAME))
bean.addPropertyValue("driverClassName",
commandLine.getOptionValue(ARG_DATASOURCE_DRIVER_CLASS_NAME));
if (commandLine.hasOption(ARG_DATASOURCE_USERNAME))
bean.addPropertyValue("username",
commandLine.getOptionValue(ARG_DATASOURCE_USERNAME));
if (commandLine.hasOption(ARG_DATASOURCE_PASSWORD))
bean.addPropertyValue("password",
commandLine.getOptionValue(ARG_DATASOURCE_PASSWORD));
beans.put("dataSource", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_OSM)) {
File osmPath = new File(commandLine.getOptionValue(ARG_OSM));
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(FileBasedOpenStreetMapProviderImpl.class);
bean.addPropertyValue("path", osmPath);
beans.put("osmProvider", bean.getBeanDefinition());
}
File outputPath = new File(remainingArgs[remainingArgs.length - 1]);
if (commandLine.hasOption(ARG_ONLY_IF_DNE) && outputPath.exists()) {
System.err.println("Bundle path already exists. Exiting...");
System.exit(0);
}
if (commandLine.hasOption(ARG_RANDOMIZE_CACHE_DIR))
creator.setRandomizeCacheDir(true);
if (commandLine.hasOption(ARG_BUNDLE_KEY)) {
String key = commandLine.getOptionValue(ARG_BUNDLE_KEY);
creator.setBundleKey(key);
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("D")) {
Properties props = commandLine.getOptionProperties("D");
for (Object key : props.keySet()) {
String propName = (String) key;
String propValue = props.getProperty(propName);
System.setProperty(propName, propValue);
}
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("P")) {
Properties props = commandLine.getOptionProperties("P");
creator.setAdditionalBeanPropertyOverrides(props);
}
setStagesToSkip(commandLine, creator);
creator.setOutputPath(outputPath);
creator.setContextPaths(contextPaths);
try {
if (commandLine.hasOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY)) {
File additionalResourceDirectory = new File(
commandLine.getOptionValue(ARG_ADDITIONAL_RESOURCES_DIRECTORY));
copyFiles(additionalResourceDirectory, outputPath);
}
creator.run();
} catch (Exception ex) {
_log.error("error building transit data bundle", ex);
System.exit(-1);
}
} catch (ParseException ex) {
System.err.println(ex.getLocalizedMessage());
printUsage();
System.exit(-1);
}
System.exit(0);
}
protected void buildOptions(Options options) {
options.addOption(ARG_SKIP_TO, true, "");
options.addOption(ARG_ONLY, true, "");
options.addOption(ARG_SKIP, true, "");
options.addOption(ARG_INCLUDE, true, "");
options.addOption(ARG_ONLY_IF_DNE, false, "");
options.addOption(ARG_DATASOURCE_DRIVER_CLASS_NAME, true, "");
options.addOption(ARG_DATASOURCE_URL, true, "");
options.addOption(ARG_DATASOURCE_USERNAME, true, "");
options.addOption(ARG_DATASOURCE_PASSWORD, true, "");
options.addOption(ARG_BUNDLE_KEY, true, "");
options.addOption(ARG_RANDOMIZE_CACHE_DIR, false, "");
options.addOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY, true, "");
options.addOption(ARG_OSM, true, "");
Option dOption = new Option("D", "use value for given property");
dOption.setArgName("property=value");
dOption.setArgs(2);
dOption.setValueSeparator('=');
options.addOption(dOption);
Option pOption = new Option("P", "use value for given property");
pOption.setArgName("beanName.beanProperty=value");
pOption.setArgs(2);
pOption.setValueSeparator('=');
options.addOption(pOption);
}
protected void printUsage() {
InputStream is = getClass().getResourceAsStream("usage.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = reader.readLine()) != null) {
System.err.println(line);
}
} catch (IOException ex) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
}
}
protected void setStagesToSkip(CommandLine commandLine,
FederatedTransitDataBundleCreator creator) {
if (commandLine.hasOption(ARG_SKIP_TO)) {
String value = commandLine.getOptionValue(ARG_SKIP_TO);
creator.setSkipToTask(value);
}
if (commandLine.hasOption(ARG_ONLY)) {
String[] values = commandLine.getOptionValues(ARG_ONLY);
for (String value : values)
creator.addTaskToOnlyRun(value);
}
if (commandLine.hasOption(ARG_SKIP)) {
String[] values = commandLine.getOptionValues(ARG_SKIP);
for (String value : values)
creator.addTaskToSkip(value);
}
if (commandLine.hasOption(ARG_INCLUDE)) {
String[] values = commandLine.getOptionValues(ARG_INCLUDE);
for (String value : values)
creator.addTaskToInclude(value);
}
}
protected void copyFiles(File from, File to) throws IOException {
if (!from.exists())
return;
if (from.isDirectory()) {
to.mkdirs();
for (File fromChild : from.listFiles()) {
File toChild = new File(to, fromChild.getName());
copyFiles(fromChild, toChild);
}
} else {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
int byteCount = 0;
byte[] buffer = new byte[1024];
while ((byteCount = in.read(buffer)) >= 0)
out.write(buffer, 0, byteCount);
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
}
}
| true | true | public void run(String[] args) {
try {
Parser parser = new GnuParser();
Options options = new Options();
buildOptions(options);
CommandLine commandLine = parser.parse(options, args);
String[] remainingArgs = commandLine.getArgs();
if (remainingArgs.length < 2) {
printUsage();
System.exit(-1);
}
FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator();
Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>();
creator.setContextBeans(beans);
List<GtfsBundle> gtfsBundles = new ArrayList<GtfsBundle>();
List<String> contextPaths = new ArrayList<String>();
for (int i = 0; i < remainingArgs.length - 1; i++) {
File path = new File(remainingArgs[i]);
if (path.isDirectory() || path.getName().endsWith(".zip")) {
GtfsBundle gtfsBundle = new GtfsBundle();
gtfsBundle.setPath(path);
gtfsBundles.add(gtfsBundle);
} else {
contextPaths.add("file:" + path);
}
}
if (!gtfsBundles.isEmpty()) {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class);
bean.addPropertyValue("bundles", gtfsBundles);
beans.put("gtfs-bundles", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_USE_DATABASE_FOR_GTFS)) {
contextPaths.add("classpath:org/onebusaway/gtfs/application-context.xml");
// HibernateGtfsRelationalDaoImpl store = new
// HibernateGtfsRelationalDaoImpl();
// store.setSessionFactory(_sessionFactory);
} else {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsRelationalDaoImpl.class);
beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_DATASOURCE_URL)) {
String dataSourceUrl = commandLine.getOptionValue(ARG_DATASOURCE_URL);
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(DriverManagerDataSource.class);
bean.addPropertyValue("url", dataSourceUrl);
if (commandLine.hasOption(ARG_DATASOURCE_DRIVER_CLASS_NAME))
bean.addPropertyValue("driverClassName",
commandLine.getOptionValue(ARG_DATASOURCE_DRIVER_CLASS_NAME));
if (commandLine.hasOption(ARG_DATASOURCE_USERNAME))
bean.addPropertyValue("username",
commandLine.getOptionValue(ARG_DATASOURCE_USERNAME));
if (commandLine.hasOption(ARG_DATASOURCE_PASSWORD))
bean.addPropertyValue("password",
commandLine.getOptionValue(ARG_DATASOURCE_PASSWORD));
beans.put("dataSource", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_OSM)) {
File osmPath = new File(commandLine.getOptionValue(ARG_OSM));
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(FileBasedOpenStreetMapProviderImpl.class);
bean.addPropertyValue("path", osmPath);
beans.put("osmProvider", bean.getBeanDefinition());
}
File outputPath = new File(remainingArgs[remainingArgs.length - 1]);
if (commandLine.hasOption(ARG_ONLY_IF_DNE) && outputPath.exists()) {
System.err.println("Bundle path already exists. Exiting...");
System.exit(0);
}
if (commandLine.hasOption(ARG_RANDOMIZE_CACHE_DIR))
creator.setRandomizeCacheDir(true);
if (commandLine.hasOption(ARG_BUNDLE_KEY)) {
String key = commandLine.getOptionValue(ARG_BUNDLE_KEY);
creator.setBundleKey(key);
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("D")) {
Properties props = commandLine.getOptionProperties("D");
for (Object key : props.keySet()) {
String propName = (String) key;
String propValue = props.getProperty(propName);
System.setProperty(propName, propValue);
}
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("P")) {
Properties props = commandLine.getOptionProperties("P");
creator.setAdditionalBeanPropertyOverrides(props);
}
setStagesToSkip(commandLine, creator);
creator.setOutputPath(outputPath);
creator.setContextPaths(contextPaths);
try {
if (commandLine.hasOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY)) {
File additionalResourceDirectory = new File(
commandLine.getOptionValue(ARG_ADDITIONAL_RESOURCES_DIRECTORY));
copyFiles(additionalResourceDirectory, outputPath);
}
creator.run();
} catch (Exception ex) {
_log.error("error building transit data bundle", ex);
System.exit(-1);
}
} catch (ParseException ex) {
System.err.println(ex.getLocalizedMessage());
printUsage();
System.exit(-1);
}
System.exit(0);
}
| public void run(String[] args) {
try {
Parser parser = new GnuParser();
Options options = new Options();
buildOptions(options);
CommandLine commandLine = parser.parse(options, args);
String[] remainingArgs = commandLine.getArgs();
if (remainingArgs.length < 2) {
printUsage();
System.exit(-1);
}
FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator();
Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>();
creator.setContextBeans(beans);
List<GtfsBundle> gtfsBundles = new ArrayList<GtfsBundle>();
List<String> contextPaths = new ArrayList<String>();
for (int i = 0; i < remainingArgs.length - 1; i++) {
File path = new File(remainingArgs[i]);
if (path.isDirectory() || path.getName().endsWith(".zip")) {
GtfsBundle gtfsBundle = new GtfsBundle();
gtfsBundle.setPath(path);
gtfsBundles.add(gtfsBundle);
} else {
contextPaths.add("file:" + path);
}
}
if (!gtfsBundles.isEmpty()) {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class);
bean.addPropertyValue("bundles", gtfsBundles);
beans.put("gtfs-bundles", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_USE_DATABASE_FOR_GTFS)) {
contextPaths.add("classpath:org/onebusaway/gtfs/application-context.xml");
} else {
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsRelationalDaoImpl.class);
beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_DATASOURCE_URL)) {
String dataSourceUrl = commandLine.getOptionValue(ARG_DATASOURCE_URL);
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(DriverManagerDataSource.class);
bean.addPropertyValue("url", dataSourceUrl);
if (commandLine.hasOption(ARG_DATASOURCE_DRIVER_CLASS_NAME))
bean.addPropertyValue("driverClassName",
commandLine.getOptionValue(ARG_DATASOURCE_DRIVER_CLASS_NAME));
if (commandLine.hasOption(ARG_DATASOURCE_USERNAME))
bean.addPropertyValue("username",
commandLine.getOptionValue(ARG_DATASOURCE_USERNAME));
if (commandLine.hasOption(ARG_DATASOURCE_PASSWORD))
bean.addPropertyValue("password",
commandLine.getOptionValue(ARG_DATASOURCE_PASSWORD));
beans.put("dataSource", bean.getBeanDefinition());
}
if (commandLine.hasOption(ARG_OSM)) {
File osmPath = new File(commandLine.getOptionValue(ARG_OSM));
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(FileBasedOpenStreetMapProviderImpl.class);
bean.addPropertyValue("path", osmPath);
beans.put("osmProvider", bean.getBeanDefinition());
}
File outputPath = new File(remainingArgs[remainingArgs.length - 1]);
if (commandLine.hasOption(ARG_ONLY_IF_DNE) && outputPath.exists()) {
System.err.println("Bundle path already exists. Exiting...");
System.exit(0);
}
if (commandLine.hasOption(ARG_RANDOMIZE_CACHE_DIR))
creator.setRandomizeCacheDir(true);
if (commandLine.hasOption(ARG_BUNDLE_KEY)) {
String key = commandLine.getOptionValue(ARG_BUNDLE_KEY);
creator.setBundleKey(key);
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("D")) {
Properties props = commandLine.getOptionProperties("D");
for (Object key : props.keySet()) {
String propName = (String) key;
String propValue = props.getProperty(propName);
System.setProperty(propName, propValue);
}
}
/**
* Optionally override any system properties (ok this duplicates existing
* functionality, yes, but it allows for -D arguments after the main
* class)
*/
if (commandLine.hasOption("P")) {
Properties props = commandLine.getOptionProperties("P");
creator.setAdditionalBeanPropertyOverrides(props);
}
setStagesToSkip(commandLine, creator);
creator.setOutputPath(outputPath);
creator.setContextPaths(contextPaths);
try {
if (commandLine.hasOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY)) {
File additionalResourceDirectory = new File(
commandLine.getOptionValue(ARG_ADDITIONAL_RESOURCES_DIRECTORY));
copyFiles(additionalResourceDirectory, outputPath);
}
creator.run();
} catch (Exception ex) {
_log.error("error building transit data bundle", ex);
System.exit(-1);
}
} catch (ParseException ex) {
System.err.println(ex.getLocalizedMessage());
printUsage();
System.exit(-1);
}
System.exit(0);
}
|
diff --git a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/DisplayStatisticsServlet.java b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/DisplayStatisticsServlet.java
index 081de6648..7be70c7a3 100644
--- a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/DisplayStatisticsServlet.java
+++ b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/DisplayStatisticsServlet.java
@@ -1,371 +1,374 @@
/*
* DisplayStatisticsServlet.java
*
* Version: $Revision: $
*
* Date: $Date: 2009-12-03 09:00:23 +1300 (Wed, 07 Oct 2009) $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import java.io.IOException;
import java.util.List;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.dspace.authorize.AuthorizeException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import org.dspace.app.util.MetadataExposure;
import org.dspace.app.webui.util.StyleSelection;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.browse.BrowseException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.authority.MetadataAuthorityManager;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogManager;
import org.dspace.core.PluginManager;
import org.dspace.core.Utils;
import org.dspace.eperson.Group;
import org.dspace.content.DSpaceObject;
import org.dspace.handle.HandleManager;
import org.dspace.statistics.Dataset;
import org.dspace.statistics.content.DatasetDSpaceObjectGenerator;
import org.dspace.statistics.content.DatasetTimeGenerator;
import org.dspace.statistics.content.DatasetTypeGenerator;
import org.dspace.statistics.content.StatisticsDataVisits;
import org.dspace.statistics.content.StatisticsListing;
import org.dspace.statistics.content.StatisticsTable;
import org.dspace.app.webui.components.StatisticsBean;
import org.dspace.app.webui.util.JSPManager;
/**
*
*
* @author Kim Shepherd
* @version $Revision: 4386 $
*/
public class DisplayStatisticsServlet extends DSpaceServlet
{
/** log4j logger */
private static Logger log = Logger.getLogger(DisplayStatisticsServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
// is the statistics data publically viewable?
boolean privatereport = ConfigurationManager.getBooleanProperty("statistics.item.authorization.admin");
// is the user a member of the Administrator (1) group?
boolean admin = Group.isMember(context, 1);
if (!privatereport || admin)
{
displayStatistics(context, request, response);
}
else
{
throw new AuthorizeException();
}
}
protected void displayStatistics(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String handle = request.getParameter("handle");
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
+ boolean isItem = false;
StatisticsBean statsVisits = new StatisticsBean();
StatisticsBean statsMonthlyVisits = new StatisticsBean();
StatisticsBean statsFileDownloads = new StatisticsBean();
StatisticsBean statsCountryVisits = new StatisticsBean();
StatisticsBean statsCityVisits = new StatisticsBean();
try
{
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle("Total Visits");
statListing.setId("list1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statListing.addDatasetGenerator(dsoAxis);
Dataset dataset = statListing.getDataset(context);
dataset = statListing.getDataset();
if (dataset == null)
{
dataset = statListing.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsVisits.setMatrix(matrix);
statsVisits.setColLabels(colLabels);
statsVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Total Visits Per Month");
statisticsTable.setId("tab1");
DatasetTimeGenerator timeAxis = new DatasetTimeGenerator();
timeAxis.setDateInterval("month", "-6", "+1");
statisticsTable.addDatasetGenerator(timeAxis);
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsMonthlyVisits.setMatrix(matrix);
statsMonthlyVisits.setColLabels(colLabels);
statsMonthlyVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
if(dso instanceof org.dspace.content.Item)
{
+ isItem = true;
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("File Downloads");
statisticsTable.setId("tab1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(Constants.BITSTREAM, 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsFileDownloads.setMatrix(matrix);
statsFileDownloads.setColLabels(colLabels);
statsFileDownloads.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top country views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("countryCode");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCountryVisits.setMatrix(matrix);
statsCountryVisits.setColLabels(colLabels);
statsCountryVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top city views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("city");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCityVisits.setMatrix(matrix);
statsCityVisits.setColLabels(colLabels);
statsCityVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
request.setAttribute("statsVisits", statsVisits);
request.setAttribute("statsMonthlyVisits", statsMonthlyVisits);
request.setAttribute("statsFileDownloads", statsFileDownloads);
request.setAttribute("statsCountryVisits",statsCountryVisits);
request.setAttribute("statsCityVisits", statsCityVisits);
+ request.setAttribute("isItem", isItem);
JSPManager.showJSP(request, response, "display-statistics.jsp");
}
}
| false | true | protected void displayStatistics(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String handle = request.getParameter("handle");
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
StatisticsBean statsVisits = new StatisticsBean();
StatisticsBean statsMonthlyVisits = new StatisticsBean();
StatisticsBean statsFileDownloads = new StatisticsBean();
StatisticsBean statsCountryVisits = new StatisticsBean();
StatisticsBean statsCityVisits = new StatisticsBean();
try
{
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle("Total Visits");
statListing.setId("list1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statListing.addDatasetGenerator(dsoAxis);
Dataset dataset = statListing.getDataset(context);
dataset = statListing.getDataset();
if (dataset == null)
{
dataset = statListing.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsVisits.setMatrix(matrix);
statsVisits.setColLabels(colLabels);
statsVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Total Visits Per Month");
statisticsTable.setId("tab1");
DatasetTimeGenerator timeAxis = new DatasetTimeGenerator();
timeAxis.setDateInterval("month", "-6", "+1");
statisticsTable.addDatasetGenerator(timeAxis);
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsMonthlyVisits.setMatrix(matrix);
statsMonthlyVisits.setColLabels(colLabels);
statsMonthlyVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
if(dso instanceof org.dspace.content.Item)
{
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("File Downloads");
statisticsTable.setId("tab1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(Constants.BITSTREAM, 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsFileDownloads.setMatrix(matrix);
statsFileDownloads.setColLabels(colLabels);
statsFileDownloads.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top country views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("countryCode");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCountryVisits.setMatrix(matrix);
statsCountryVisits.setColLabels(colLabels);
statsCountryVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top city views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("city");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCityVisits.setMatrix(matrix);
statsCityVisits.setColLabels(colLabels);
statsCityVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
request.setAttribute("statsVisits", statsVisits);
request.setAttribute("statsMonthlyVisits", statsMonthlyVisits);
request.setAttribute("statsFileDownloads", statsFileDownloads);
request.setAttribute("statsCountryVisits",statsCountryVisits);
request.setAttribute("statsCityVisits", statsCityVisits);
JSPManager.showJSP(request, response, "display-statistics.jsp");
}
| protected void displayStatistics(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String handle = request.getParameter("handle");
DSpaceObject dso = HandleManager.resolveToObject(context, handle);
boolean isItem = false;
StatisticsBean statsVisits = new StatisticsBean();
StatisticsBean statsMonthlyVisits = new StatisticsBean();
StatisticsBean statsFileDownloads = new StatisticsBean();
StatisticsBean statsCountryVisits = new StatisticsBean();
StatisticsBean statsCityVisits = new StatisticsBean();
try
{
StatisticsListing statListing = new StatisticsListing(
new StatisticsDataVisits(dso));
statListing.setTitle("Total Visits");
statListing.setId("list1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statListing.addDatasetGenerator(dsoAxis);
Dataset dataset = statListing.getDataset(context);
dataset = statListing.getDataset();
if (dataset == null)
{
dataset = statListing.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsVisits.setMatrix(matrix);
statsVisits.setColLabels(colLabels);
statsVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Total Visits Per Month");
statisticsTable.setId("tab1");
DatasetTimeGenerator timeAxis = new DatasetTimeGenerator();
timeAxis.setDateInterval("month", "-6", "+1");
statisticsTable.addDatasetGenerator(timeAxis);
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(dso.getType(), 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsMonthlyVisits.setMatrix(matrix);
statsMonthlyVisits.setColLabels(colLabels);
statsMonthlyVisits.setRowLabels(rowLabels);
}
} catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
if(dso instanceof org.dspace.content.Item)
{
isItem = true;
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("File Downloads");
statisticsTable.setId("tab1");
DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator();
dsoAxis.addDsoChild(Constants.BITSTREAM, 10, false, -1);
statisticsTable.addDatasetGenerator(dsoAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsFileDownloads.setMatrix(matrix);
statsFileDownloads.setColLabels(colLabels);
statsFileDownloads.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top country views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("countryCode");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCountryVisits.setMatrix(matrix);
statsCountryVisits.setColLabels(colLabels);
statsCountryVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
try
{
StatisticsListing statisticsTable = new StatisticsListing(new StatisticsDataVisits(dso));
statisticsTable.setTitle("Top city views");
statisticsTable.setId("tab1");
DatasetTypeGenerator typeAxis = new DatasetTypeGenerator();
typeAxis.setType("city");
typeAxis.setMax(10);
statisticsTable.addDatasetGenerator(typeAxis);
Dataset dataset = statisticsTable.getDataset(context);
dataset = statisticsTable.getDataset();
if (dataset == null)
{
dataset = statisticsTable.getDataset(context);
}
if (dataset != null)
{
String[][] matrix = dataset.getMatrixFormatted();
List<String> colLabels = dataset.getColLabels();
List<String> rowLabels = dataset.getRowLabels();
statsCityVisits.setMatrix(matrix);
statsCityVisits.setColLabels(colLabels);
statsCityVisits.setRowLabels(rowLabels);
}
}
catch (Exception e)
{
log.error(
"Error occured while creating statistics for dso with ID: "
+ dso.getID() + " and type " + dso.getType()
+ " and handle: " + dso.getHandle(), e);
}
request.setAttribute("statsVisits", statsVisits);
request.setAttribute("statsMonthlyVisits", statsMonthlyVisits);
request.setAttribute("statsFileDownloads", statsFileDownloads);
request.setAttribute("statsCountryVisits",statsCountryVisits);
request.setAttribute("statsCityVisits", statsCityVisits);
request.setAttribute("isItem", isItem);
JSPManager.showJSP(request, response, "display-statistics.jsp");
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java b/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java
index 052aa86..2fbec86 100644
--- a/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java
+++ b/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java
@@ -1,56 +1,65 @@
package com.github.kpacha.jkata.anagram;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Anagram {
public static Set<String> generate(String source) {
Set<String> result = new HashSet<String>();
List<Character> chars = getAsCharacterList(source);
+ if (chars.size() == 4) {
+ for (int currentChar = 0; currentChar < 4; currentChar++) {
+ Character character = chars.get(currentChar);
+ for (String part : Anagram.generate(new String(getCharsToMix(
+ chars, character)))) {
+ result.add(character + part);
+ }
+ }
+ }
if (chars.size() == 3) {
for (int currentChar = 0; currentChar < 3; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 2) {
for (int currentChar = 0; currentChar < 2; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 1) {
result.add(source);
}
return result;
}
private static char[] getCharsToMix(List<Character> chars,
Character character) {
List<Character> characters = new ArrayList<Character>(chars);
characters.remove(character);
char[] charArrayToMix = new char[characters.size()];
for (int currentChar = 0; currentChar < characters.size(); currentChar++) {
charArrayToMix[currentChar] = characters.get(currentChar);
}
return charArrayToMix;
}
private static List<Character> getAsCharacterList(String source) {
List<Character> chars = new ArrayList<Character>();
for (char c : source.toCharArray()) {
chars.add(c);
}
return chars;
}
}
| true | true | public static Set<String> generate(String source) {
Set<String> result = new HashSet<String>();
List<Character> chars = getAsCharacterList(source);
if (chars.size() == 3) {
for (int currentChar = 0; currentChar < 3; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 2) {
for (int currentChar = 0; currentChar < 2; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 1) {
result.add(source);
}
return result;
}
| public static Set<String> generate(String source) {
Set<String> result = new HashSet<String>();
List<Character> chars = getAsCharacterList(source);
if (chars.size() == 4) {
for (int currentChar = 0; currentChar < 4; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 3) {
for (int currentChar = 0; currentChar < 3; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 2) {
for (int currentChar = 0; currentChar < 2; currentChar++) {
Character character = chars.get(currentChar);
for (String part : Anagram.generate(new String(getCharsToMix(
chars, character)))) {
result.add(character + part);
}
}
}
if (chars.size() == 1) {
result.add(source);
}
return result;
}
|
diff --git a/sokoban/solvers/BidirectionalIDS.java b/sokoban/solvers/BidirectionalIDS.java
index 2d8fe20..7694e22 100644
--- a/sokoban/solvers/BidirectionalIDS.java
+++ b/sokoban/solvers/BidirectionalIDS.java
@@ -1,80 +1,90 @@
package sokoban.solvers;
import java.util.HashMap;
import java.util.HashSet;
import sokoban.Board;
import sokoban.SearchInfo;
import sokoban.SearchStatus;
/**
* This solver performs a bidirectional (TODO iterative deepening DFS?) search.
*/
public class BidirectionalIDS implements Solver
{
private IDSPuller puller;
private IDSPusher pusher;
@Override
public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap, pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap, pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
// TODO implement collision check in pusher and update accordingly here (remove line)
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
for (int maxDepth = lowerBound; maxDepth < IDSCommon.DEPTH_LIMIT; maxDepth += 3) {
// Puller
if (runPuller) {
result = puller.dfs(maxDepth);
System.out.println("puller: "+result.status);
}
// Pusher
else {
result = pusher.dfs(maxDepth);
System.out.println("pusher: "+result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
else if (result.status == SearchStatus.Failed) {
if (runPuller) pullerFailed = true;
if (!runPuller) pusherFailed = true;
- System.out.println("\nSolver failed: "+(runPuller ? "Puller" : "Pusher"));
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
- // TODO: implement collision check in pusher and activate this line
- runPuller = !runPuller;
+ // Run the other solver if only one of them failed
+ // in case it failed because of a bug or hash collision
+ if (pullerFailed) {
+ runPuller = false;
+ }
+ else if (pusherFailed) {
+ runPuller = true;
+ }
+ else
+ {
+ // TODO choose the solver with the least leaf nodes?
+ runPuller = !runPuller;
+ }
}
System.out.println("Maximum depth reached!");
return null;
}
@Override
public int getIterationsCount()
{
// TODO
return pusher.getIterationsCount() + puller.getIterationsCount();
}
}
| false | true | public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap, pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap, pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
// TODO implement collision check in pusher and update accordingly here (remove line)
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
for (int maxDepth = lowerBound; maxDepth < IDSCommon.DEPTH_LIMIT; maxDepth += 3) {
// Puller
if (runPuller) {
result = puller.dfs(maxDepth);
System.out.println("puller: "+result.status);
}
// Pusher
else {
result = pusher.dfs(maxDepth);
System.out.println("pusher: "+result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
else if (result.status == SearchStatus.Failed) {
if (runPuller) pullerFailed = true;
if (!runPuller) pusherFailed = true;
System.out.println("\nSolver failed: "+(runPuller ? "Puller" : "Pusher"));
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
// TODO: implement collision check in pusher and activate this line
runPuller = !runPuller;
}
System.out.println("Maximum depth reached!");
return null;
}
| public String solve(final Board startBoard)
{
HashSet<Long> failedBoardsPuller = new HashSet<Long>();
HashSet<Long> failedBoardsPusher = new HashSet<Long>();
HashMap<Long, BoxPosDir> pullerStatesMap = new HashMap<Long, BoxPosDir>();
HashMap<Long, BoxPosDir> pusherStatesMap = new HashMap<Long, BoxPosDir>();
pusher = new IDSPusher(startBoard, failedBoardsPuller, pusherStatesMap, pullerStatesMap);
puller = new IDSPuller(startBoard, failedBoardsPusher, pullerStatesMap, pusherStatesMap);
boolean runPuller = true;
int lowerBound = IDSCommon.lowerBound(startBoard);
// TODO implement collision check in pusher and update accordingly here (remove line)
SearchInfo result;
// IDS loop
boolean pullerFailed = false;
boolean pusherFailed = false;
for (int maxDepth = lowerBound; maxDepth < IDSCommon.DEPTH_LIMIT; maxDepth += 3) {
// Puller
if (runPuller) {
result = puller.dfs(maxDepth);
System.out.println("puller: "+result.status);
}
// Pusher
else {
result = pusher.dfs(maxDepth);
System.out.println("pusher: "+result.status);
}
if (result.solution != null) {
System.out.println();
return Board.solutionToString(result.solution);
}
else if (result.status == SearchStatus.Failed) {
if (runPuller) pullerFailed = true;
if (!runPuller) pusherFailed = true;
}
if (pullerFailed && pusherFailed) {
System.out.println("no solution!");
return null;
}
// Run the other solver if only one of them failed
// in case it failed because of a bug or hash collision
if (pullerFailed) {
runPuller = false;
}
else if (pusherFailed) {
runPuller = true;
}
else
{
// TODO choose the solver with the least leaf nodes?
runPuller = !runPuller;
}
}
System.out.println("Maximum depth reached!");
return null;
}
|
diff --git a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java
index 0bcfd0b..b179b85 100644
--- a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java
+++ b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java
@@ -1,669 +1,669 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.media;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.IBinder.DeathRecipient;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.media.MediaRouter.ControlRequestCallback;
import android.util.Log;
import android.util.SparseArray;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* Maintains a connection to a particular media route provider service.
*/
final class RegisteredMediaRouteProvider extends MediaRouteProvider
implements ServiceConnection {
private static final String TAG = "MediaRouteProviderProxy"; // max. 23 chars
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private final ComponentName mComponentName;
private final PrivateHandler mPrivateHandler;
private final ArrayList<Controller> mControllers = new ArrayList<Controller>();
private boolean mStarted;
private boolean mBound;
private Connection mActiveConnection;
private boolean mConnectionReady;
public RegisteredMediaRouteProvider(Context context, ComponentName componentName) {
super(context, new ProviderMetadata(componentName.getPackageName()));
mComponentName = componentName;
mPrivateHandler = new PrivateHandler();
}
@Override
public RouteController onCreateRouteController(String routeId) {
MediaRouteProviderDescriptor descriptor = getDescriptor();
if (descriptor != null) {
List<MediaRouteDescriptor> routes = descriptor.getRoutes();
final int count = routes.size();
for (int i = 0; i < count; i++) {
final MediaRouteDescriptor route = routes.get(i);
if (route.getId().equals(routeId)) {
Controller controller = new Controller(routeId);
mControllers.add(controller);
if (mConnectionReady) {
controller.attachConnection(mActiveConnection);
}
updateBinding();
return controller;
}
}
}
return null;
}
@Override
public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) {
if (mConnectionReady) {
mActiveConnection.setDiscoveryRequest(request);
}
updateBinding();
}
public boolean hasComponentName(String packageName, String className) {
return mComponentName.getPackageName().equals(packageName)
&& mComponentName.getClassName().equals(className);
}
public void start() {
if (!mStarted) {
if (DEBUG) {
Log.d(TAG, this + ": Starting");
}
mStarted = true;
updateBinding();
}
}
public void stop() {
if (mStarted) {
if (DEBUG) {
Log.d(TAG, this + ": Stopping");
}
mStarted = false;
updateBinding();
}
}
public void rebindIfDisconnected() {
if (mActiveConnection == null && shouldBind()) {
unbind();
bind();
}
}
private void updateBinding() {
if (shouldBind()) {
bind();
} else {
unbind();
}
}
private boolean shouldBind() {
if (mStarted) {
// Bind whenever there is a discovery request.
if (getDiscoveryRequest() != null) {
return true;
}
// Bind whenever the application has an active route controller.
// This means that one of this provider's routes is selected.
if (!mControllers.isEmpty()) {
return true;
}
}
return false;
}
private void bind() {
if (!mBound) {
if (DEBUG) {
Log.d(TAG, this + ": Binding");
}
Intent service = new Intent(MediaRouteProviderService.SERVICE_INTERFACE);
service.setComponent(mComponentName);
try {
mBound = getContext().bindService(service, this, Context.BIND_AUTO_CREATE);
if (!mBound && DEBUG) {
Log.d(TAG, this + ": Bind failed");
}
} catch (SecurityException ex) {
if (DEBUG) {
Log.d(TAG, this + ": Bind failed", ex);
}
}
}
}
private void unbind() {
if (mBound) {
if (DEBUG) {
Log.d(TAG, this + ": Unbinding");
}
mBound = false;
disconnect();
getContext().unbindService(this);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (DEBUG) {
Log.d(TAG, this + ": Connected");
}
if (mBound) {
disconnect();
Messenger messenger = (service != null ? new Messenger(service) : null);
if (MediaRouteProviderService.isValidRemoteMessenger(messenger)) {
Connection connection = new Connection(messenger);
if (connection.register()) {
mActiveConnection = connection;
} else {
if (DEBUG) {
Log.d(TAG, this + ": Registration failed");
}
}
} else {
Log.e(TAG, this + ": Service returned invalid messenger binder");
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG) {
Log.d(TAG, this + ": Service disconnected");
}
disconnect();
}
private void onConnectionReady(Connection connection) {
if (mActiveConnection == connection) {
mConnectionReady = true;
attachControllersToConnection();
MediaRouteDiscoveryRequest request = getDiscoveryRequest();
if (request != null) {
mActiveConnection.setDiscoveryRequest(request);
}
}
}
private void onConnectionDied(Connection connection) {
if (mActiveConnection == connection) {
if (DEBUG) {
Log.d(TAG, this + ": Service connection died");
}
disconnect();
}
}
private void onConnectionError(Connection connection, String error) {
if (mActiveConnection == connection) {
if (DEBUG) {
Log.d(TAG, this + ": Service connection error - " + error);
}
unbind();
}
}
private void onConnectionDescriptorChanged(Connection connection,
MediaRouteProviderDescriptor descriptor) {
if (mActiveConnection == connection) {
if (DEBUG) {
Log.d(TAG, this + ": Descriptor changed, descriptor=" + descriptor);
}
setDescriptor(descriptor);
}
}
private void disconnect() {
if (mActiveConnection != null) {
setDescriptor(null);
mConnectionReady = false;
detachControllersFromConnection();
mActiveConnection.dispose();
mActiveConnection = null;
}
}
private void onControllerReleased(Controller controller) {
mControllers.remove(controller);
controller.detachConnection();
updateBinding();
}
private void attachControllersToConnection() {
int count = mControllers.size();
for (int i = 0; i < count; i++) {
mControllers.get(i).attachConnection(mActiveConnection);
}
}
private void detachControllersFromConnection() {
int count = mControllers.size();
for (int i = 0; i < count; i++) {
mControllers.get(i).detachConnection();
}
}
@Override
public String toString() {
return "Service connection " + mComponentName.flattenToShortString();
}
private final class Controller extends RouteController {
private final String mRouteId;
private boolean mSelected;
private int mPendingSetVolume = -1;
private int mPendingUpdateVolumeDelta;
private Connection mConnection;
private int mControllerId;
public Controller(String routeId) {
mRouteId = routeId;
}
public void attachConnection(Connection connection) {
mConnection = connection;
mControllerId = connection.createRouteController(mRouteId);
if (mSelected) {
connection.selectRoute(mControllerId);
if (mPendingSetVolume >= 0) {
connection.setVolume(mControllerId, mPendingSetVolume);
mPendingSetVolume = -1;
}
if (mPendingUpdateVolumeDelta != 0) {
connection.updateVolume(mControllerId, mPendingUpdateVolumeDelta);
mPendingUpdateVolumeDelta = 0;
}
}
}
public void detachConnection() {
if (mConnection != null) {
mConnection.releaseRouteController(mControllerId);
mConnection = null;
mControllerId = 0;
}
}
@Override
public void onRelease() {
onControllerReleased(this);
}
@Override
public void onSelect() {
mSelected = true;
if (mConnection != null) {
mConnection.selectRoute(mControllerId);
}
}
@Override
public void onUnselect() {
mSelected = false;
if (mConnection != null) {
mConnection.unselectRoute(mControllerId);
}
}
@Override
public void onSetVolume(int volume) {
if (mConnection != null) {
mConnection.setVolume(mControllerId, volume);
} else {
mPendingSetVolume = volume;
mPendingUpdateVolumeDelta = 0;
}
}
@Override
public void onUpdateVolume(int delta) {
if (mConnection != null) {
mConnection.updateVolume(mControllerId, delta);
} else {
mPendingUpdateVolumeDelta += delta;
}
}
@Override
public boolean onControlRequest(Intent intent, ControlRequestCallback callback) {
if (mConnection != null) {
return mConnection.sendControlRequest(mControllerId, intent, callback);
}
return false;
}
}
private final class Connection implements DeathRecipient {
private final Messenger mServiceMessenger;
private final ReceiveHandler mReceiveHandler;
private final Messenger mReceiveMessenger;
private int mNextRequestId = 1;
private int mNextControllerId = 1;
private int mServiceVersion; // non-zero when registration complete
private int mPendingRegisterRequestId;
private final SparseArray<ControlRequestCallback> mPendingCallbacks =
new SparseArray<ControlRequestCallback>();
public Connection(Messenger serviceMessenger) {
mServiceMessenger = serviceMessenger;
mReceiveHandler = new ReceiveHandler(this);
mReceiveMessenger = new Messenger(mReceiveHandler);
}
public boolean register() {
mPendingRegisterRequestId = mNextRequestId++;
if (!sendRequest(MediaRouteProviderService.CLIENT_MSG_REGISTER,
mPendingRegisterRequestId,
MediaRouteProviderService.CLIENT_VERSION_CURRENT, null, null)) {
return false;
}
try {
mServiceMessenger.getBinder().linkToDeath(this, 0);
return true;
} catch (RemoteException ex) {
binderDied();
}
return false;
}
public void dispose() {
sendRequest(MediaRouteProviderService.CLIENT_MSG_UNREGISTER, 0, 0, null, null);
mReceiveHandler.dispose();
mServiceMessenger.getBinder().unlinkToDeath(this, 0);
mPrivateHandler.post(new Runnable() {
@Override
public void run() {
failPendingCallbacks();
}
});
}
private void failPendingCallbacks() {
int count = 0;
for (int i = 0; i < mPendingCallbacks.size(); i++) {
mPendingCallbacks.valueAt(i).onError(null, null);
}
mPendingCallbacks.clear();
}
public boolean onGenericFailure(int requestId) {
if (requestId == mPendingRegisterRequestId) {
mPendingRegisterRequestId = 0;
onConnectionError(this, "Registation failed");
}
ControlRequestCallback callback = mPendingCallbacks.get(requestId);
if (callback != null) {
mPendingCallbacks.remove(requestId);
callback.onError(null, null);
}
return true;
}
public boolean onGenericSuccess(int requestId) {
return true;
}
public boolean onRegistered(int requestId, int serviceVersion,
Bundle descriptorBundle) {
if (mServiceVersion == 0
&& requestId == mPendingRegisterRequestId
&& serviceVersion >= MediaRouteProviderService.SERVICE_VERSION_1) {
mPendingRegisterRequestId = 0;
mServiceVersion = serviceVersion;
onConnectionDescriptorChanged(this,
MediaRouteProviderDescriptor.fromBundle(descriptorBundle));
onConnectionReady(this);
return true;
}
return false;
}
public boolean onDescriptorChanged(Bundle descriptorBundle) {
if (mServiceVersion != 0) {
onConnectionDescriptorChanged(this,
MediaRouteProviderDescriptor.fromBundle(descriptorBundle));
return true;
}
return false;
}
public boolean onControlRequestSucceeded(int requestId, Bundle data) {
ControlRequestCallback callback = mPendingCallbacks.get(requestId);
if (callback != null) {
mPendingCallbacks.remove(requestId);
callback.onResult(data);
return true;
}
return false;
}
public boolean onControlRequestFailed(int requestId, String error, Bundle data) {
ControlRequestCallback callback = mPendingCallbacks.get(requestId);
if (callback != null) {
mPendingCallbacks.remove(requestId);
callback.onError(error, data);
return true;
}
return false;
}
@Override
public void binderDied() {
mPrivateHandler.post(new Runnable() {
@Override
public void run() {
onConnectionDied(Connection.this);
}
});
}
public int createRouteController(String routeId) {
int controllerId = mNextControllerId++;
Bundle data = new Bundle();
data.putString(MediaRouteProviderService.CLIENT_DATA_ROUTE_ID, routeId);
sendRequest(MediaRouteProviderService.CLIENT_MSG_CREATE_ROUTE_CONTROLLER,
mNextRequestId++, controllerId, null, data);
return controllerId;
}
public void releaseRouteController(int controllerId) {
sendRequest(MediaRouteProviderService.CLIENT_MSG_RELEASE_ROUTE_CONTROLLER,
mNextRequestId++, controllerId, null, null);
}
public void selectRoute(int controllerId) {
sendRequest(MediaRouteProviderService.CLIENT_MSG_SELECT_ROUTE,
mNextRequestId++, controllerId, null, null);
}
public void unselectRoute(int controllerId) {
sendRequest(MediaRouteProviderService.CLIENT_MSG_UNSELECT_ROUTE,
mNextRequestId++, controllerId, null, null);
}
public void setVolume(int controllerId, int volume) {
Bundle data = new Bundle();
data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, volume);
sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_ROUTE_VOLUME,
mNextRequestId++, controllerId, null, data);
}
public void updateVolume(int controllerId, int delta) {
Bundle data = new Bundle();
data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, delta);
sendRequest(MediaRouteProviderService.CLIENT_MSG_UPDATE_ROUTE_VOLUME,
mNextRequestId++, controllerId, null, data);
}
public boolean sendControlRequest(int controllerId, Intent intent,
ControlRequestCallback callback) {
int requestId = mNextRequestId++;
if (sendRequest(MediaRouteProviderService.CLIENT_MSG_ROUTE_CONTROL_REQUEST,
requestId, controllerId, intent, null)) {
if (callback != null) {
mPendingCallbacks.put(requestId, callback);
}
return true;
}
return false;
}
public void setDiscoveryRequest(MediaRouteDiscoveryRequest request) {
sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_DISCOVERY_REQUEST,
mNextRequestId++, 0, request != null ? request.asBundle() : null, null);
}
private boolean sendRequest(int what, int requestId, int arg, Object obj, Bundle data) {
Message msg = Message.obtain();
msg.what = what;
msg.arg1 = requestId;
msg.arg2 = arg;
msg.obj = obj;
msg.setData(data);
msg.replyTo = mReceiveMessenger;
try {
mServiceMessenger.send(msg);
return true;
} catch (DeadObjectException ex) {
// The service died.
} catch (RemoteException ex) {
if (what != MediaRouteProviderService.CLIENT_MSG_UNREGISTER) {
Log.e(TAG, "Could not send message to service.", ex);
}
}
return false;
}
}
private final class PrivateHandler extends Handler {
}
/**
* Handler that receives messages from the server.
* <p>
* This inner class is static and only retains a weak reference to the connection
* to prevent the client from being leaked in case the service is holding an
* active reference to the client's messenger.
* </p><p>
* This handler should not be used to handle any messages other than those
* that come from the service.
* </p>
*/
private static final class ReceiveHandler extends Handler {
private final WeakReference<Connection> mConnectionRef;
public ReceiveHandler(Connection connection) {
mConnectionRef = new WeakReference<Connection>(connection);
}
public void dispose() {
mConnectionRef.clear();
}
@Override
public void handleMessage(Message msg) {
Connection connection = mConnectionRef.get();
if (connection != null) {
final int what = msg.what;
final int requestId = msg.arg1;
final int arg = msg.arg2;
final Object obj = msg.obj;
final Bundle data = msg.peekData();
if (!processMessage(connection, what, requestId, arg, obj, data)) {
if (DEBUG) {
Log.d(TAG, "Unhandled message from server: " + msg);
}
}
}
}
private boolean processMessage(Connection connection,
int what, int requestId, int arg, Object obj, Bundle data) {
switch (what) {
case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE:
connection.onGenericFailure(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS:
connection.onGenericSuccess(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_REGISTERED:
if (obj == null || obj instanceof Bundle) {
return connection.onRegistered(requestId, arg, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED:
if (obj == null || obj instanceof Bundle) {
return connection.onDescriptorChanged((Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED:
if (obj == null || obj instanceof Bundle) {
return connection.onControlRequestSucceeded(
requestId, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED:
if (obj == null || obj instanceof Bundle) {
- String error =
- data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR);
+ String error = (data == null ? null :
+ data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR));
return connection.onControlRequestFailed(
requestId, error, (Bundle)obj);
}
break;
}
return false;
}
}
}
| true | true | private boolean processMessage(Connection connection,
int what, int requestId, int arg, Object obj, Bundle data) {
switch (what) {
case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE:
connection.onGenericFailure(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS:
connection.onGenericSuccess(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_REGISTERED:
if (obj == null || obj instanceof Bundle) {
return connection.onRegistered(requestId, arg, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED:
if (obj == null || obj instanceof Bundle) {
return connection.onDescriptorChanged((Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED:
if (obj == null || obj instanceof Bundle) {
return connection.onControlRequestSucceeded(
requestId, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED:
if (obj == null || obj instanceof Bundle) {
String error =
data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR);
return connection.onControlRequestFailed(
requestId, error, (Bundle)obj);
}
break;
}
return false;
}
| private boolean processMessage(Connection connection,
int what, int requestId, int arg, Object obj, Bundle data) {
switch (what) {
case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE:
connection.onGenericFailure(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS:
connection.onGenericSuccess(requestId);
return true;
case MediaRouteProviderService.SERVICE_MSG_REGISTERED:
if (obj == null || obj instanceof Bundle) {
return connection.onRegistered(requestId, arg, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED:
if (obj == null || obj instanceof Bundle) {
return connection.onDescriptorChanged((Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED:
if (obj == null || obj instanceof Bundle) {
return connection.onControlRequestSucceeded(
requestId, (Bundle)obj);
}
break;
case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED:
if (obj == null || obj instanceof Bundle) {
String error = (data == null ? null :
data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR));
return connection.onControlRequestFailed(
requestId, error, (Bundle)obj);
}
break;
}
return false;
}
|
diff --git a/kernel/src/main/java/com/qspin/qtaste/ui/xmleditor/TestRequirementEditor.java b/kernel/src/main/java/com/qspin/qtaste/ui/xmleditor/TestRequirementEditor.java
index af0552bc..c3bc04e6 100644
--- a/kernel/src/main/java/com/qspin/qtaste/ui/xmleditor/TestRequirementEditor.java
+++ b/kernel/src/main/java/com/qspin/qtaste/ui/xmleditor/TestRequirementEditor.java
@@ -1,857 +1,858 @@
/*
Copyright 2007-2009 QSpin - www.qspin.be
This file is part of QTaste framework.
QTaste is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QTaste is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QTaste. If not, see <http://www.gnu.org/licenses/>.
*/
package com.qspin.qtaste.ui.xmleditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import com.qspin.qtaste.config.StaticConfiguration;
import com.qspin.qtaste.io.XMLFile;
import com.qspin.qtaste.testsuite.TestRequirement;
import com.qspin.qtaste.util.Log4jLoggerFactory;
/**
*
* @author simjan
*/
@SuppressWarnings("serial")
public class TestRequirementEditor extends JPanel {
private static Logger logger = Log4jLoggerFactory.getLogger(TestRequirementEditor.class);
protected TestRequirementTableModel m_TestRequirementModel;
protected JTable m_TestRequirementTable;
private String currentXMLFile = "";
private boolean isModified;
private TableModelListener tableListener;
private int ROW_HEIGHT = 20;
private MyTableColumnModelListener m_TableColumnModelListener;
private Clipboard m_systemClipboard;
public TestRequirementEditor() {
super(new BorderLayout());
m_systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
genUI();
}
public boolean isModified() {
return isModified;
}
public void setModified(boolean value) {
boolean wasAlreadyModified = isModified;
isModified = value;
if (wasAlreadyModified != isModified) {
firePropertyChange("isModified", wasAlreadyModified, isModified);
}
// recompute header and widths
computeColumnWidths();
m_TestRequirementTable.repaint();
m_TestRequirementTable.doLayout();
}
class RenameVariable extends AbstractAction {
String m_ColName;
int m_ColIndex;
public RenameVariable(String colName, int colIndex) {
super("Rename variable");
m_ColName = colName;
m_ColIndex = colIndex;
}
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
String defaultName = (String)m_TestRequirementTable.getColumnModel().getColumn(m_ColIndex).getHeaderValue();
String varName = (String) JOptionPane.showInputDialog(null,
"Give the new name of the variable '" + m_ColName + "' ?",
"TestData name",
JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
if (varName == null) {
return;
}
//
m_TestRequirementTable.getColumnModel().getColumn(m_ColIndex).setHeaderValue(varName);
m_TestRequirementTable.getTableHeader().repaint();
//computeColumnWidths();
Vector<String> v = (Vector<String>)m_TestRequirementModel.getColumnIdentifiers();
int columnIndex = m_TestRequirementTable.getColumnModel().getColumn(m_ColIndex).getModelIndex();
v.set(columnIndex, varName);
m_TestRequirementModel.setColumnIdentifiers(v);
// update requirement data ID
for ( TestRequirement req : m_TestRequirementModel.getRequirements() )
{
req.changeDataId(m_ColName, varName);
}
m_TestRequirementModel.fireTableCellUpdated(TableModelEvent.HEADER_ROW, columnIndex);
setModified(true);
}
}
class AddVariableAction extends AbstractAction {
public AddVariableAction() {
super("Add variable");
}
public void actionPerformed(ActionEvent e) {
//if (m_TestData== null) return;
String varName = JOptionPane.showInputDialog(null,
"Give the name of the new variable ?",
"TestData name",
JOptionPane.QUESTION_MESSAGE);
if (varName == null) {
return;
}
addColumn(varName);
}
@Override
public boolean isEnabled() {
return true;
}
}
public void save() {
File xmlFile = new File(currentXMLFile);
String path = xmlFile.getParent();
BufferedWriter output = null;
try {
String outputFile = path + File.separator
+ StaticConfiguration.TEST_REQUIREMENTS_FILENAME;
output = new BufferedWriter(new FileWriter(new File(outputFile)));
output.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
output.newLine();
output.write("<" + XMLFile.ROOT_ELEMENT + ">");
for (TestRequirement req : m_TestRequirementModel.getRequirements()) {
output.newLine();
output.write("\t<" + XMLFile.REQUIREMENT_ELEMENT + " ");
output.append(XMLFile.REQUIREMENT_ID + "=\"" );
output.append(req.getId());
output.append("\">");
for ( String dataId : req.getDataId() )
{
if ( dataId.equals(TestRequirement.ID) )
{
continue;
}
output.newLine();
output.append("\t\t<" + dataId.replace(" ", XMLFile.SPACE_REPLACEMENT) + ">" );
output.append(req.getData(dataId));
output.append("</" + dataId.replace(" ", XMLFile.SPACE_REPLACEMENT) + ">");
}
output.newLine();
output.append("\t</" + XMLFile.REQUIREMENT_ELEMENT + ">" );
}
output.newLine();
output.write("</" + XMLFile.ROOT_ELEMENT + ">");
output.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
} finally {
try {
if (output != null)
output.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
// reload
loadXMLFile(currentXMLFile);
setModified(false);
}
class RemoveColumnAction extends AbstractAction {
String m_ColName;
int m_ColIndex;
public RemoveColumnAction(String colName, int colIndex) {
super("Remove variable");
m_ColName = colName;
m_ColIndex = colIndex;
}
public void actionPerformed(ActionEvent e) {
removeColumn(m_ColName, m_ColIndex);
}
@Override
public boolean isEnabled() {
return !m_ColName.equals(TestRequirement.ID) ;
}
}
public void loadXMLFile(String fileName) {
try {
m_TestRequirementModel.removeTableModelListener(tableListener);
m_TestRequirementTable.getColumnModel().removeColumnModelListener(m_TableColumnModelListener);
XMLFile xmlFile = new XMLFile(fileName);
m_TestRequirementModel.setRowCount(0);
m_TestRequirementModel.setColumnCount(0);
currentXMLFile = fileName;
m_TestRequirementModel.setRequirements(xmlFile.getXMLDataSet());
Enumeration<TableColumn> columns = m_TestRequirementTable.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn hcol = columns.nextElement();
hcol.setHeaderRenderer(new MyTableHeaderRenderer());
hcol.setCellEditor(new TestDataTableCellEditor());
}
computeColumnWidths();
m_TestRequirementTable.doLayout();
m_TestRequirementModel.addTableModelListener(tableListener);
m_TestRequirementTable.getColumnModel().addColumnModelListener(m_TableColumnModelListener);
} catch (IOException ex) {
logger.error(ex.getMessage());
} catch (SAXException ex) {
logger.error(ex.getMessage());
} catch (ParserConfigurationException ex) {
logger.error(ex.getMessage());
}
}
public void setFileName(String fileName) {
currentXMLFile = fileName;
}
public void removeColumn(String header, int colIndex) {
for ( TestRequirement req : m_TestRequirementModel.getRequirements() )
{
req.removeDataId(header);
}
m_TestRequirementModel.fireTableDataChanged();
setModified(true);
}
public void addColumn(String header) {
m_TestRequirementModel.addColumn(header);
TableColumn hcol = m_TestRequirementTable.getColumn(header);
hcol.setHeaderRenderer(new MyTableHeaderRenderer());
hcol.setCellEditor(new TestDataTableCellEditor());
computeColumnWidths();
setModified(true);
// now add the needed rows
}
private void genUI() {
getActionMap().put("Save", new SaveAction());
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable = new JTable() {
@Override
public String getToolTipText(MouseEvent e) {
Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
if (colIndex == 0) {
// no tooltip on first column (row id)
return null;
} else {
return convertObjectToToolTip(getValueAt(rowIndex, colIndex));
}
}
// overwrite cell content when typing on a selected cell
@Override
public Component prepareEditor(TableCellEditor editor, int row,
int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JTextComponent) {
((JTextField) c).selectAll();
}
return c;
}
// select entire rows when selecting first column (row id)
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
if (e.getFirstIndex() == 0 && e.getValueIsAdjusting()) {
setColumnSelectionInterval(1, getColumnCount() - 1);
} else {
super.columnSelectionChanged(e);
}
}
};
m_TestRequirementTable
.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
m_TestRequirementModel = new TestRequirementTableModel();
m_TestRequirementTable.setModel(m_TestRequirementModel);
m_TableColumnModelListener = new MyTableColumnModelListener();
m_TestRequirementTable.setSurrendersFocusOnKeystroke(true);
m_TestRequirementTable.setColumnSelectionAllowed(true);
m_TestRequirementTable.addMouseListener(new TableMouseListener(
m_TestRequirementTable));
m_TestRequirementTable.getTableHeader().addMouseListener(
new TableMouseListener(m_TestRequirementTable));
m_TestRequirementTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_TestRequirementTable.getActionMap().put("Save", new SaveAction());
m_TestRequirementTable.setDefaultEditor(String.class,
new TestDataTableCellEditor());
m_TestRequirementTable.setDefaultEditor(Integer.class,
new TestDataTableCellEditor());
m_TestRequirementTable
.getTableHeader()
.getInputMap()
.put(KeyStroke
.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.setRowHeight(ROW_HEIGHT);
m_TestRequirementTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//
if (e.getKeyCode() == KeyEvent.VK_UP) {
// check if previous line is empty
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
// if current row is the last one
if (m_TestRequirementTable.getSelectedRow() == m_TestRequirementTable
.getRowCount() - 1) {
addNewRow();
}
}
if ((e.getKeyCode() == KeyEvent.VK_S) && (e.isControlDown())) {
save();
}
if ((e.getKeyCode() == KeyEvent.VK_C) && (e.isControlDown())) {
copySelectionToClipboard();
}
if ((e.getKeyCode() == KeyEvent.VK_V) && (e.isControlDown())) {
if (m_TestRequirementTable.getSelectedColumn() != 0) {
pasteSelectionFromClipboard();
}
}
}
});
- m_TestRequirementModel.addTableModelListener(new TableModelListener() {
+ tableListener = new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// build the test data
if (e.getType() == TableModelEvent.UPDATE) {
if (e.getFirstRow() >= 0) {
setModified(true);
}
}
}
- });
+ };
+ m_TestRequirementModel.addTableModelListener(tableListener);
JScrollPane sp = new JScrollPane(m_TestRequirementTable);
sp.addMouseListener(new TableMouseListener(null));
add(sp);
}
private String convertObjectToToolTip(Object obj) {
String tip = null;
if (obj != null) {
if (obj instanceof ImageIcon) { // Status column
tip = ((ImageIcon) obj).getDescription();
} else {
tip = obj.toString();
}
}
return tip;
}
public String getCurrentXMLFile() {
return currentXMLFile;
}
private void copySelectionToClipboard() {
StringBuffer stringBuffer = new StringBuffer();
int[] selectedRows = m_TestRequirementTable.getSelectedRows();
int[] selectedCols = m_TestRequirementTable.getSelectedColumns();
for (int i = 0; i < selectedRows.length; i++) {
for (int j = 0; j < selectedCols.length; j++) {
stringBuffer.append(m_TestRequirementTable.getValueAt(
selectedRows[i], selectedCols[j]));
if (j < selectedCols.length - 1) {
stringBuffer.append("\t");
}
}
stringBuffer.append("\n");
}
StringSelection stringSelection = new StringSelection(
stringBuffer.toString());
m_systemClipboard.setContents(stringSelection, stringSelection);
}
private void pasteSelectionFromClipboard() {
int startRow = (m_TestRequirementTable.getSelectedRows())[0];
int startCol = (m_TestRequirementTable.getSelectedColumns())[0];
try {
String clipboardContent = (String) (m_systemClipboard
.getContents(this).getTransferData(DataFlavor.stringFlavor));
StringTokenizer tokenizerRow = new StringTokenizer(
clipboardContent, "\n");
for (int i = 0; tokenizerRow.hasMoreTokens(); i++) {
String rowString = tokenizerRow.nextToken();
StringTokenizer tokenizerTab = new StringTokenizer(rowString,
"\t");
for (int j = 0; tokenizerTab.hasMoreTokens(); j++) {
String value = tokenizerTab.nextToken();
int row = startRow + i;
int col = startCol + j;
// add new row if necessary
if (row == m_TestRequirementTable.getRowCount()) {
addNewRow();
}
if (col < m_TestRequirementTable.getColumnCount()) {
m_TestRequirementTable.setValueAt(value, row, col);
}
}
}
} catch (Exception e) {
logger.warn(
"Error while pasting clipboard content into test requirement editor",
e);
}
}
// ///////////////////////////////////////////////////////////////////////////////////
// Inner Classes
// ///////////////////////////////////////////////////////////////////////////////////
protected class MyTableHeaderRenderer extends JLabel implements
TableCellRenderer {
// This method is called each time a column header
// using this renderer needs to be rendered.
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
// 'value' is column header value of column 'vColIndex'
// rowIndex is always -1
// isSelected is always false
// hasFocus is always false
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
// Configure the component with the specified value
setText(value.toString());
// Set tool tip if desired
setToolTipText((String) value);
// Since the renderer is a component, return itself
return this;
}
// The following methods override the defaults for performance reasons
@Override
public void validate() {
}
@Override
public void revalidate() {
}
@Override
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
}
@Override
public void firePropertyChange(String propertyName, boolean oldValue,
boolean newValue) {
}
}
public class TableMouseListener extends MouseAdapter {
protected JTable table;
public TableMouseListener(JTable table) {
this.table = table;
}
private void evaluatePopup(MouseEvent e) {
if (e.isPopupTrigger()) {
int clickedRow = -1;
int clickedColumn = -1;
if (table != null) {
// force selection of clicked cell
clickedRow = table.rowAtPoint(e.getPoint());
clickedColumn = table.columnAtPoint(e.getPoint());
table.setRowSelectionInterval(clickedRow, clickedRow);
table.setColumnSelectionInterval(clickedColumn,
clickedColumn);
}
// display the context dialog
JPopupMenu menu = new JPopupMenu();
menu.add(new AddVariableAction());
if (table != null) {
menu.add(new RenameVariable(table.getColumnName(clickedColumn), clickedColumn));
menu.add(new RemoveColumnAction(table.getColumnName(clickedColumn), clickedColumn));
}
menu.add(new AddRowAction());
if (table != null) {
menu.add(new InsertRowAction());
menu.add(new DuplicateRowAction());
menu.add(new RemoveRowAction());
}
menu.add(new SaveAction());
Point point = e.getPoint();
menu.show(e.getComponent(), point.x, point.y);
}
}
@Override
public void mousePressed(MouseEvent e) {
evaluatePopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
evaluatePopup(e);
}
}
class RemoveRowAction extends AbstractAction {
public RemoveRowAction() {
super("Remove row");
}
public void actionPerformed(ActionEvent e) {
int selectedRow = m_TestRequirementTable.getSelectedRow();
if (selectedRow == -1) {
return;
}
m_TestRequirementModel.removeRequirement(m_TestRequirementTable.convertRowIndexToModel(selectedRow));
setModified(true);
}
}
class AddRowAction extends AbstractAction {
public AddRowAction() {
super("Add row");
}
public void actionPerformed(ActionEvent e) {
addNewRow();
}
}
class InsertRowAction extends AbstractAction {
public InsertRowAction() {
super("Insert row");
}
public void actionPerformed(ActionEvent e) {
insertNewRow();
}
}
class DuplicateRowAction extends AbstractAction {
public DuplicateRowAction() {
super("Duplicate row");
}
public void actionPerformed(ActionEvent e) {
int selectedRow = m_TestRequirementTable.getSelectedRow();
if (selectedRow == -1) {
return;
}
selectedRow = m_TestRequirementTable.convertRowIndexToModel(selectedRow);
addNewRow(selectedRow);
}
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save");
}
public void actionPerformed(ActionEvent e) {
save();
}
@Override
public boolean isEnabled() {
return true;
}
}
private void addNewRow() {
addNewRow(-1);
}
private void insertNewRow() {
int rowIndex = m_TestRequirementTable.getSelectedRow();
rowIndex = m_TestRequirementTable.convertRowIndexToModel(rowIndex);
m_TestRequirementModel.addRequirement(new TestRequirement(""), rowIndex);
setModified(true);
}
private void addNewRow(int rowToCopyIndex) {
TestRequirement req;
if ( rowToCopyIndex >= 0 ) {
req = new TestRequirement(m_TestRequirementModel.getRequirements().get(rowToCopyIndex));
} else {
req = new TestRequirement("");
}
m_TestRequirementModel.addRequirement(req, m_TestRequirementModel.getRowCount());
m_TestRequirementTable.setVisible(true);
setModified(true);
}
private void computeColumnWidths() {
// horizontal spacing
int hspace = 6;
TableModel model = m_TestRequirementTable.getModel();
// rows no
int cols = model.getColumnCount();
// columns no
int rows = model.getRowCount();
// width vector
int w[] = new int[model.getColumnCount()];
// computes headers widths
for (int i = 0; i < cols; i++) {
w[i] = (int) m_TestRequirementTable
.getDefaultRenderer(String.class)
.getTableCellRendererComponent(m_TestRequirementTable,
m_TestRequirementModel.getColumnName(i), false,
false, -1, i).getPreferredSize().getWidth()
+ hspace;
TableColumn hcol = m_TestRequirementTable
.getColumn(m_TestRequirementModel.getColumnName(i));
hcol.setHeaderRenderer(new MyTableHeaderRenderer());
}
// check if cell values fit in their cells and if not
// keep in w[i] the necessary with
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Object o = model.getValueAt(i, j);
int width = 0;
if (o != null) {
width = (int) m_TestRequirementTable
.getCellRenderer(i, j)
.getTableCellRendererComponent(
m_TestRequirementTable, o, false, false, i,
j).getPreferredSize().getWidth()
+ hspace;
}
if (w[j] < width) {
w[j] = width;
}
}
}
TableColumnModel colModel = m_TestRequirementTable.getColumnModel();
// and finally setting the column widths
for (int i = 0; i < cols; i++) {
colModel.getColumn(i).setPreferredWidth(w[i]);
}
}
public class TestDataTableCellEditor extends DefaultCellEditor implements FocusListener, KeyListener {
public TestDataTableCellEditor() {
super(new JTextField());
getComponent().addFocusListener(this);
getComponent().addKeyListener(this);
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
protected void fireEditingStopped() {
if (isModified) {
super.fireEditingStopped();
} else {
super.fireEditingCanceled();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
// check if previous line is empty
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
// if current row is the last one
if (m_TestRequirementTable.getSelectedRow() ==
m_TestRequirementTable.getRowCount() - 1) {
addNewRow();
}
return;
}
if (e.isControlDown()) {
if (e.getKeyCode() == KeyEvent.VK_S) {
// validate the cell
stopCellEditing();
save();
return;
} else if (e.getKeyCode() == KeyEvent.VK_C) {
// copy
// don't set modified
return;
}
}
if ((e.getKeyCode() != KeyEvent.VK_TAB)
&& (e.getKeyCode() != KeyEvent.VK_CONTROL)
&& (e.getKeyCode() != KeyEvent.VK_ALT)
&& (e.getKeyCode() != KeyEvent.VK_ALT_GRAPH)
&& (e.getKeyCode() != KeyEvent.VK_SHIFT)
&& (e.getKeyCode() != KeyEvent.VK_CAPS_LOCK)
&& (e.getKeyCode() != KeyEvent.VK_ENTER)
&& (e.getKeyCode() != KeyEvent.VK_LEFT)
&& (e.getKeyCode() != KeyEvent.VK_RIGHT)
&& (e.getKeyCode() != KeyEvent.VK_HOME)
&& (e.getKeyCode() != KeyEvent.VK_END)
&& (e.getKeyCode() != KeyEvent.VK_PAGE_UP)
&& (e.getKeyCode() != KeyEvent.VK_PAGE_DOWN)
&& (e.getKeyCode() != KeyEvent.VK_NUM_LOCK)
&& (e.getKeyCode() != KeyEvent.VK_SCROLL_LOCK)
&& (e.getKeyCode() != KeyEvent.VK_PRINTSCREEN)
&& (e.getKeyCode() != KeyEvent.VK_PAUSE)
&& (e.getKeyCode() != KeyEvent.VK_ESCAPE)) {
setModified(true);
}
}
public void keyReleased(KeyEvent e) {
// throw new UnsupportedOperationException("Not supported yet.");
}
}
public class MyTableColumnModelListener implements TableColumnModelListener {
@Override
public void columnAdded(TableColumnModelEvent e) {
}
@Override
public void columnMarginChanged(ChangeEvent e) {
// TODO Auto-generated method stub
}
@Override
public void columnMoved(TableColumnModelEvent e) {
if (e.getFromIndex() != e.getToIndex()) {
setModified(true);
}
}
@Override
public void columnRemoved(TableColumnModelEvent e) {
}
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
}
}
}
| false | true | private void genUI() {
getActionMap().put("Save", new SaveAction());
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable = new JTable() {
@Override
public String getToolTipText(MouseEvent e) {
Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
if (colIndex == 0) {
// no tooltip on first column (row id)
return null;
} else {
return convertObjectToToolTip(getValueAt(rowIndex, colIndex));
}
}
// overwrite cell content when typing on a selected cell
@Override
public Component prepareEditor(TableCellEditor editor, int row,
int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JTextComponent) {
((JTextField) c).selectAll();
}
return c;
}
// select entire rows when selecting first column (row id)
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
if (e.getFirstIndex() == 0 && e.getValueIsAdjusting()) {
setColumnSelectionInterval(1, getColumnCount() - 1);
} else {
super.columnSelectionChanged(e);
}
}
};
m_TestRequirementTable
.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
m_TestRequirementModel = new TestRequirementTableModel();
m_TestRequirementTable.setModel(m_TestRequirementModel);
m_TableColumnModelListener = new MyTableColumnModelListener();
m_TestRequirementTable.setSurrendersFocusOnKeystroke(true);
m_TestRequirementTable.setColumnSelectionAllowed(true);
m_TestRequirementTable.addMouseListener(new TableMouseListener(
m_TestRequirementTable));
m_TestRequirementTable.getTableHeader().addMouseListener(
new TableMouseListener(m_TestRequirementTable));
m_TestRequirementTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_TestRequirementTable.getActionMap().put("Save", new SaveAction());
m_TestRequirementTable.setDefaultEditor(String.class,
new TestDataTableCellEditor());
m_TestRequirementTable.setDefaultEditor(Integer.class,
new TestDataTableCellEditor());
m_TestRequirementTable
.getTableHeader()
.getInputMap()
.put(KeyStroke
.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.setRowHeight(ROW_HEIGHT);
m_TestRequirementTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//
if (e.getKeyCode() == KeyEvent.VK_UP) {
// check if previous line is empty
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
// if current row is the last one
if (m_TestRequirementTable.getSelectedRow() == m_TestRequirementTable
.getRowCount() - 1) {
addNewRow();
}
}
if ((e.getKeyCode() == KeyEvent.VK_S) && (e.isControlDown())) {
save();
}
if ((e.getKeyCode() == KeyEvent.VK_C) && (e.isControlDown())) {
copySelectionToClipboard();
}
if ((e.getKeyCode() == KeyEvent.VK_V) && (e.isControlDown())) {
if (m_TestRequirementTable.getSelectedColumn() != 0) {
pasteSelectionFromClipboard();
}
}
}
});
m_TestRequirementModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// build the test data
if (e.getType() == TableModelEvent.UPDATE) {
if (e.getFirstRow() >= 0) {
setModified(true);
}
}
}
});
JScrollPane sp = new JScrollPane(m_TestRequirementTable);
sp.addMouseListener(new TableMouseListener(null));
add(sp);
}
| private void genUI() {
getActionMap().put("Save", new SaveAction());
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable = new JTable() {
@Override
public String getToolTipText(MouseEvent e) {
Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
if (colIndex == 0) {
// no tooltip on first column (row id)
return null;
} else {
return convertObjectToToolTip(getValueAt(rowIndex, colIndex));
}
}
// overwrite cell content when typing on a selected cell
@Override
public Component prepareEditor(TableCellEditor editor, int row,
int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JTextComponent) {
((JTextField) c).selectAll();
}
return c;
}
// select entire rows when selecting first column (row id)
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
if (e.getFirstIndex() == 0 && e.getValueIsAdjusting()) {
setColumnSelectionInterval(1, getColumnCount() - 1);
} else {
super.columnSelectionChanged(e);
}
}
};
m_TestRequirementTable
.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
m_TestRequirementModel = new TestRequirementTableModel();
m_TestRequirementTable.setModel(m_TestRequirementModel);
m_TableColumnModelListener = new MyTableColumnModelListener();
m_TestRequirementTable.setSurrendersFocusOnKeystroke(true);
m_TestRequirementTable.setColumnSelectionAllowed(true);
m_TestRequirementTable.addMouseListener(new TableMouseListener(
m_TestRequirementTable));
m_TestRequirementTable.getTableHeader().addMouseListener(
new TableMouseListener(m_TestRequirementTable));
m_TestRequirementTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_TestRequirementTable.getActionMap().put("Save", new SaveAction());
m_TestRequirementTable.setDefaultEditor(String.class,
new TestDataTableCellEditor());
m_TestRequirementTable.setDefaultEditor(Integer.class,
new TestDataTableCellEditor());
m_TestRequirementTable
.getTableHeader()
.getInputMap()
.put(KeyStroke
.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK),
"Save");
m_TestRequirementTable.setRowHeight(ROW_HEIGHT);
m_TestRequirementTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//
if (e.getKeyCode() == KeyEvent.VK_UP) {
// check if previous line is empty
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
// if current row is the last one
if (m_TestRequirementTable.getSelectedRow() == m_TestRequirementTable
.getRowCount() - 1) {
addNewRow();
}
}
if ((e.getKeyCode() == KeyEvent.VK_S) && (e.isControlDown())) {
save();
}
if ((e.getKeyCode() == KeyEvent.VK_C) && (e.isControlDown())) {
copySelectionToClipboard();
}
if ((e.getKeyCode() == KeyEvent.VK_V) && (e.isControlDown())) {
if (m_TestRequirementTable.getSelectedColumn() != 0) {
pasteSelectionFromClipboard();
}
}
}
});
tableListener = new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// build the test data
if (e.getType() == TableModelEvent.UPDATE) {
if (e.getFirstRow() >= 0) {
setModified(true);
}
}
}
};
m_TestRequirementModel.addTableModelListener(tableListener);
JScrollPane sp = new JScrollPane(m_TestRequirementTable);
sp.addMouseListener(new TableMouseListener(null));
add(sp);
}
|
diff --git a/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java b/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java
index ff6e43f..444b4ac 100644
--- a/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java
+++ b/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java
@@ -1,30 +1,30 @@
package org.onebusaway.nyc.vehicle_tracking.model;
import org.onebusaway.realtime.api.EVehiclePhase;
import org.onebusaway.realtime.api.VehicleLocationRecord;
import org.onebusaway.transit_data_federation.services.AgencyAndIdLibrary;
public class RecordLibrary {
public static NycTestLocationRecord getVehicleLocationRecordAsNycTestLocationRecord(
VehicleLocationRecord record) {
NycTestLocationRecord r = new NycTestLocationRecord();
return r;
}
public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord(
NycTestLocationRecord record) {
VehicleLocationRecord vlr = new VehicleLocationRecord();
vlr.setTimeOfRecord(record.getTimestamp());
vlr.setTimeOfLocationUpdate(record.getTimestamp());
vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId()));
vlr.setServiceDate(record.getInferredServiceDate());
vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock());
- vlr.setCurrentLocationLat(record.getInferredLat());
- vlr.setCurrentLocationLon(record.getInferredLon());
+ vlr.setCurrentLocationLat(record.getLat());
+ vlr.setCurrentLocationLon(record.getLon());
vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase()));
vlr.setStatus(record.getInferredStatus());
return vlr;
}
}
| true | true | public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord(
NycTestLocationRecord record) {
VehicleLocationRecord vlr = new VehicleLocationRecord();
vlr.setTimeOfRecord(record.getTimestamp());
vlr.setTimeOfLocationUpdate(record.getTimestamp());
vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId()));
vlr.setServiceDate(record.getInferredServiceDate());
vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock());
vlr.setCurrentLocationLat(record.getInferredLat());
vlr.setCurrentLocationLon(record.getInferredLon());
vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase()));
vlr.setStatus(record.getInferredStatus());
return vlr;
}
| public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord(
NycTestLocationRecord record) {
VehicleLocationRecord vlr = new VehicleLocationRecord();
vlr.setTimeOfRecord(record.getTimestamp());
vlr.setTimeOfLocationUpdate(record.getTimestamp());
vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId()));
vlr.setServiceDate(record.getInferredServiceDate());
vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock());
vlr.setCurrentLocationLat(record.getLat());
vlr.setCurrentLocationLon(record.getLon());
vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase()));
vlr.setStatus(record.getInferredStatus());
return vlr;
}
|
diff --git a/de.walware.statet.r.ui/src/de/walware/statet/r/ui/pkgmanager/RPkgManagerUI.java b/de.walware.statet.r.ui/src/de/walware/statet/r/ui/pkgmanager/RPkgManagerUI.java
index 66414f70..dd62b875 100644
--- a/de.walware.statet.r.ui/src/de/walware/statet/r/ui/pkgmanager/RPkgManagerUI.java
+++ b/de.walware.statet.r.ui/src/de/walware/statet/r/ui/pkgmanager/RPkgManagerUI.java
@@ -1,142 +1,142 @@
/*******************************************************************************
* Copyright (c) 2012-2013 WalWare/StatET-Project (www.walware.de/goto/statet).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.ui.pkgmanager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import de.walware.ecommons.ui.util.UIAccess;
import de.walware.statet.nico.ui.util.ToolMessageDialog;
import de.walware.rj.eclient.IRToolService;
import de.walware.statet.r.console.core.RProcess;
import de.walware.statet.r.core.pkgmanager.IRPkgManager;
import de.walware.statet.r.core.pkgmanager.IRPkgSet;
import de.walware.statet.r.core.renv.IREnv;
import de.walware.statet.r.internal.ui.pkgmanager.RPkgManagerDialog;
public class RPkgManagerUI {
private static final Map<IREnv, RPkgManagerDialog> DIALOGS = new HashMap<IREnv, RPkgManagerDialog>();
private static Shell getShell(final IShellProvider shellProvider) {
Shell shell = null;
if (shellProvider != null) {
shell = shellProvider.getShell();
}
if (shell == null) {
shell = UIAccess.getActiveWorkbenchShell(false);
}
return shell;
}
public static RPkgManagerDialog openDialog(final IRPkgManager.Ext manager,
final RProcess tool, final Shell parentShell, final StartAction startAction) {
final IREnv rEnv = manager.getREnv();
RPkgManagerDialog dialog = DIALOGS.get(rEnv);
if (dialog != null && dialog.getShell() != null && !dialog.getShell().isDisposed()) {
dialog.close();
}
dialog = new RPkgManagerDialog(manager, tool, parentShell);
dialog.setBlockOnOpen(false);
DIALOGS.put(rEnv, dialog);
dialog.open();
dialog.getShell().addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(final DisposeEvent e) {
final RPkgManagerDialog d = DIALOGS.get(rEnv);
if (d != null && d.getShell() == e.getSource()) {
DIALOGS.remove(rEnv);
}
}
});
if (startAction != null) {
dialog.start(startAction);
}
return dialog;
}
public static boolean requestRequiredRPkgs(final IRPkgManager.Ext manager,
final List<String> pkgNames,
final IRToolService r, final IProgressMonitor monitor,
final IShellProvider shellProvider, final String message,
final Runnable okRunnable, final Runnable cancelRunnable) throws CoreException {
if (manager.requiresUpdate()) {
manager.update(r, monitor);
}
- final IRPkgSet.Ext rPkgSet = manager.getExtRPkgSet();
+ final IRPkgSet rPkgSet = manager.getRPkgSet();
final List<String> missingPkgs = new ArrayList<String>(pkgNames.size());
final StringBuilder sb = new StringBuilder();
for (final String pkgName : pkgNames) {
if (rPkgSet.getInstalled().containsByName(pkgName)) {
continue;
}
missingPkgs.add(pkgName);
sb.append("\n\t"); //$NON-NLS-1$
sb.append(pkgName);
}
if (sb.length() == 0) {
return true;
}
sb.insert(0, message);
sb.append("\n\nDo you want to install the packages now?");
final RProcess tool = (RProcess) r.getTool();
final Shell shell = getShell(shellProvider);
final Display display = (shell != null) ? shell.getDisplay() : UIAccess.getDisplay();
display.asyncExec(new Runnable() {
@Override
public void run() {
final boolean yes = ToolMessageDialog.openQuestion(tool, shell,
"Required R Packages", sb.toString());
if (yes) {
final RPkgManagerDialog dialog = openDialog(manager, tool, shell,
new StartAction(StartAction.INSTALL, missingPkgs) );
if (okRunnable != null) {
dialog.getShell().addListener(SWT.Close, new Listener() {
@Override
public void handleEvent(final Event event) {
display.asyncExec(okRunnable);
}
});
}
return;
}
if (cancelRunnable != null) {
cancelRunnable.run();
}
}
});
return false;
}
}
| true | true | public static boolean requestRequiredRPkgs(final IRPkgManager.Ext manager,
final List<String> pkgNames,
final IRToolService r, final IProgressMonitor monitor,
final IShellProvider shellProvider, final String message,
final Runnable okRunnable, final Runnable cancelRunnable) throws CoreException {
if (manager.requiresUpdate()) {
manager.update(r, monitor);
}
final IRPkgSet.Ext rPkgSet = manager.getExtRPkgSet();
final List<String> missingPkgs = new ArrayList<String>(pkgNames.size());
final StringBuilder sb = new StringBuilder();
for (final String pkgName : pkgNames) {
if (rPkgSet.getInstalled().containsByName(pkgName)) {
continue;
}
missingPkgs.add(pkgName);
sb.append("\n\t"); //$NON-NLS-1$
sb.append(pkgName);
}
if (sb.length() == 0) {
return true;
}
sb.insert(0, message);
sb.append("\n\nDo you want to install the packages now?");
final RProcess tool = (RProcess) r.getTool();
final Shell shell = getShell(shellProvider);
final Display display = (shell != null) ? shell.getDisplay() : UIAccess.getDisplay();
display.asyncExec(new Runnable() {
@Override
public void run() {
final boolean yes = ToolMessageDialog.openQuestion(tool, shell,
"Required R Packages", sb.toString());
if (yes) {
final RPkgManagerDialog dialog = openDialog(manager, tool, shell,
new StartAction(StartAction.INSTALL, missingPkgs) );
if (okRunnable != null) {
dialog.getShell().addListener(SWT.Close, new Listener() {
@Override
public void handleEvent(final Event event) {
display.asyncExec(okRunnable);
}
});
}
return;
}
if (cancelRunnable != null) {
cancelRunnable.run();
}
}
});
return false;
}
| public static boolean requestRequiredRPkgs(final IRPkgManager.Ext manager,
final List<String> pkgNames,
final IRToolService r, final IProgressMonitor monitor,
final IShellProvider shellProvider, final String message,
final Runnable okRunnable, final Runnable cancelRunnable) throws CoreException {
if (manager.requiresUpdate()) {
manager.update(r, monitor);
}
final IRPkgSet rPkgSet = manager.getRPkgSet();
final List<String> missingPkgs = new ArrayList<String>(pkgNames.size());
final StringBuilder sb = new StringBuilder();
for (final String pkgName : pkgNames) {
if (rPkgSet.getInstalled().containsByName(pkgName)) {
continue;
}
missingPkgs.add(pkgName);
sb.append("\n\t"); //$NON-NLS-1$
sb.append(pkgName);
}
if (sb.length() == 0) {
return true;
}
sb.insert(0, message);
sb.append("\n\nDo you want to install the packages now?");
final RProcess tool = (RProcess) r.getTool();
final Shell shell = getShell(shellProvider);
final Display display = (shell != null) ? shell.getDisplay() : UIAccess.getDisplay();
display.asyncExec(new Runnable() {
@Override
public void run() {
final boolean yes = ToolMessageDialog.openQuestion(tool, shell,
"Required R Packages", sb.toString());
if (yes) {
final RPkgManagerDialog dialog = openDialog(manager, tool, shell,
new StartAction(StartAction.INSTALL, missingPkgs) );
if (okRunnable != null) {
dialog.getShell().addListener(SWT.Close, new Listener() {
@Override
public void handleEvent(final Event event) {
display.asyncExec(okRunnable);
}
});
}
return;
}
if (cancelRunnable != null) {
cancelRunnable.run();
}
}
});
return false;
}
|
diff --git a/testFrameworkServer/src/ch/hsr/objectCaching/testFrameworkServer/Server.java b/testFrameworkServer/src/ch/hsr/objectCaching/testFrameworkServer/Server.java
index fc95ff5..99a2e19 100644
--- a/testFrameworkServer/src/ch/hsr/objectCaching/testFrameworkServer/Server.java
+++ b/testFrameworkServer/src/ch/hsr/objectCaching/testFrameworkServer/Server.java
@@ -1,233 +1,233 @@
package ch.hsr.objectCaching.testFrameworkServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import ch.hsr.objectCaching.interfaces.Account;
import ch.hsr.objectCaching.interfaces.AccountImpl;
import ch.hsr.objectCaching.interfaces.Action;
import ch.hsr.objectCaching.interfaces.ClientInterface;
import ch.hsr.objectCaching.interfaces.Configuration;
import ch.hsr.objectCaching.interfaces.ReadAction;
import ch.hsr.objectCaching.interfaces.Scenario;
import ch.hsr.objectCaching.interfaces.ServerInterface;
import ch.hsr.objectCaching.interfaces.WriteAction;
import ch.hsr.objectCaching.testFrameworkServer.Client.Status;
public class Server implements ServerInterface
{
private ClientList clientList;
private ArrayList<TestCase> testCases;
private Dispatcher dispatcher;
private TestCase activeTestCase;
private TestCaseFactory factory;
private Configuration configuration;
private Account account;
private ConfigurationFactory configFactory;
public Server()
{
configFactory = new ConfigurationFactory();
clientList = configFactory.getClientList();
configuration = configFactory.getConfiguration();
generateTestCases();
establishClientConnection();
createRmiRegistry();
dispatcher = new Dispatcher(configuration.getServerSocketPort());
account = new AccountImpl();
new Thread(dispatcher).start();
}
private void generateTestCases()
{
factory = new TestCaseFactory();
factory.convertXML();
testCases = factory.getTestCases();
activeTestCase = testCases.get(0);
configuration.setNameOfSystemUnderTest(activeTestCase.getSystemUnderTest());
}
private void startTestCase()
{
System.out.println("Starting TestCase");
dispatcher.setSystemUnderTest(activeTestCase.getSystemUnderTest(), account);
initializeClients();
}
private void initializeClients()
{
System.out.println("initializeClients");
Scenario temp;
for(int i = 0; i < clientList.size(); i++)
{
if((temp = activeTestCase.getScenarios().get(i)) != null)
{
try {
clientList.getClient(i).getClientStub().initialize(temp, configuration);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
clientList.getClient(i).getClientStub().initialize(activeTestCase.getScenario(0), configuration);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void establishClientConnection()
{
System.out.println("establishClientConnection");
try {
for(int i = 0; i < clientList.size(); i++)
{
System.out.println(clientList.getClient(i).getIp());
ClientInterface clientStub = (ClientInterface)Naming.lookup("rmi://" + clientList.getClient(i).getIp() + ":" + configuration.getClientRmiPort() + "/Client");
clientList.getClient(i).setClientStub(clientStub);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void setReady(String ip)
{
System.out.println("Setted ready with: " + ip);
Client temp;
if((temp = clientList.getClientByIp(ip)) != null)
{
temp.setStatus(Status.READY);
}
if(checkAllReady())
{
start();
}
}
public int getSocketPort()
{
return configuration.getServerSocketPort();
}
private void start()
{
System.out.println("start");
for(int i = 0; i < clientList.size(); i++)
{
try {
clientList.getClient(i).getClientStub().startTest();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private boolean checkAllReady()
{
for(int i = 0; i < clientList.size(); i++)
{
if(clientList.getClient(i).getStatus() == Status.NOTREADY)
{
return false;
}
}
return true;
}
private void createRmiRegistry()
{
try {
LocateRegistry.createRegistry(configuration.getServerRMIPort());
ServerInterface skeleton = (ServerInterface) UnicastRemoteObject.exportObject(this, configuration.getServerRMIPort());
Registry reg = LocateRegistry.getRegistry(configuration.getServerRMIPort());
reg.rebind(configuration.getServerRegistryName(), skeleton);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void setResults(Scenario scenario, String clientIp)
{
//TODO: Auswertung der ankommenden Resultate
System.out.println("results setted");
System.out.println(scenario.getId());
for(int i = 0; i < scenario.getActionList().size(); i++)
{
Action action = scenario.getActionList().get(i);
if(action instanceof WriteAction)
{
System.out.println("Action was a Write-Action with: " + ((WriteAction)action).getValue());
}
if(action instanceof ReadAction)
{
System.out.println("Action was a Read-Action with: " + ((ReadAction)action).getBalance());
}
}
// ReportGenerator report = new ReportGenerator();
// report.addScenario(scenario);
// report.makeSummary();
for(int i = 0; i < testCases.size(); i++)
{
- if(testCases.get(i).equals(activeTestCase) && testCases.get(i + 1) != null)
+ if(testCases.get(i).equals(activeTestCase) && testCases.size() > i+1)
{
activeTestCase = testCases.get(i + 1);
startTestCase();
}
else
{
stopClient(clientIp);
}
}
}
private void stopClient(String clientIp)
{
Client temp;
try {
if((temp = clientList.getClientByIp(clientIp)) != null)
{
System.out.println("Stop Client with " + clientIp);
temp.getClientStub().shutdown();
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args)
{
Server myServer = new Server();
myServer.startTestCase();
}
}
| true | true | public void setResults(Scenario scenario, String clientIp)
{
//TODO: Auswertung der ankommenden Resultate
System.out.println("results setted");
System.out.println(scenario.getId());
for(int i = 0; i < scenario.getActionList().size(); i++)
{
Action action = scenario.getActionList().get(i);
if(action instanceof WriteAction)
{
System.out.println("Action was a Write-Action with: " + ((WriteAction)action).getValue());
}
if(action instanceof ReadAction)
{
System.out.println("Action was a Read-Action with: " + ((ReadAction)action).getBalance());
}
}
// ReportGenerator report = new ReportGenerator();
// report.addScenario(scenario);
// report.makeSummary();
for(int i = 0; i < testCases.size(); i++)
{
if(testCases.get(i).equals(activeTestCase) && testCases.get(i + 1) != null)
{
activeTestCase = testCases.get(i + 1);
startTestCase();
}
else
{
stopClient(clientIp);
}
}
}
| public void setResults(Scenario scenario, String clientIp)
{
//TODO: Auswertung der ankommenden Resultate
System.out.println("results setted");
System.out.println(scenario.getId());
for(int i = 0; i < scenario.getActionList().size(); i++)
{
Action action = scenario.getActionList().get(i);
if(action instanceof WriteAction)
{
System.out.println("Action was a Write-Action with: " + ((WriteAction)action).getValue());
}
if(action instanceof ReadAction)
{
System.out.println("Action was a Read-Action with: " + ((ReadAction)action).getBalance());
}
}
// ReportGenerator report = new ReportGenerator();
// report.addScenario(scenario);
// report.makeSummary();
for(int i = 0; i < testCases.size(); i++)
{
if(testCases.get(i).equals(activeTestCase) && testCases.size() > i+1)
{
activeTestCase = testCases.get(i + 1);
startTestCase();
}
else
{
stopClient(clientIp);
}
}
}
|
diff --git a/src/instructions/USI_TRLK.java b/src/instructions/USI_TRLK.java
index 4527457..90e7f29 100644
--- a/src/instructions/USI_TRLK.java
+++ b/src/instructions/USI_TRLK.java
@@ -1,184 +1,184 @@
package instructions;
import static assemblernator.ErrorReporting.makeError;
import assemblernator.AbstractInstruction;
import assemblernator.ErrorReporting.ErrorHandler;
import assemblernator.Instruction.Operand;
import assemblernator.Instruction;
import assemblernator.Module;
import assemblernator.OperandChecker;
/**
* The TRLK instruction.
*
* @author Generate.java
* @date Apr 08, 2012; 08:26:19
* @specRef JT5
*/
public class USI_TRLK extends AbstractInstruction {
/**
* The operation identifier of this instruction; while comments should not
* be treated as an instruction, specification says they must be included in
* the user report. Hence, we will simply give this class a semicolon as its
* instruction ID.
*/
private static final String opId = "TRLK";
/** This instruction's identifying opcode. */
private static final int opCode = 0x00000025; // 0b10010100000000000000000000000000
/** The static instance for this instruction. */
static USI_TRLK staticInstance = new USI_TRLK(true);
/** @see assemblernator.Instruction#getNewLC(int, Module) */
@Override public int getNewLC(int lc, Module mod) {
return lc+1;
}
/**
* The type of operand specifying the destination for this operation.
*/
String dest = "";
/**
* The type of operand specifying the source for this operation.
*/
String src = "";
/** @see assemblernator.Instruction#check(ErrorHandler, Module) */
@Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
//operands less than two error
if (this.operands.size() < 2){
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1);
//checks combos for 2 operands
}else if(this.operands.size() == 2){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM")){
src="FM";
//range check
Operand o1 = getOperandData("FM");
int constantSize1 = module.evaluate(o1.expression, true, hErr, this,
o1.valueStartPosition);
this.getOperandData("FM").value = constantSize1;
isValid = OperandChecker.isValidMem(constantSize1);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
//dont know if this is need but can be cut out
}else if (this.hasOperand("FL")){
src="FL";
//range check
Operand o1 = getOperandData("FL");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
this.getOperandData("FL").value = constantSize1;
isValid = OperandChecker.isValidLiteral(constantSize1,ConstantRange.RANGE_SHIFT);
if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FM or FL"), this.lineNum, -1);
}
}else{
}
//checks combos for 3 operands
}else if(this.operands.size() == 3){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM") && this.hasOperand("FX")){
src="FMFX";
//range check
Operand o1 = getOperandData("FX");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
- this.getOperandData("FR").value = constantSize1;
+ this.getOperandData("FX").value = constantSize1;
isValid = OperandChecker.isValidIndex(constantSize1);
if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1);
Operand o2 = getOperandData("FM");
int constantSize2 = module.evaluate(o2.expression, true, hErr, this,
o2.valueStartPosition);
this.getOperandData("FM").value = constantSize2;
isValid = OperandChecker.isValidMem(constantSize2);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FM and FX", "DR"), this.lineNum, -1);
}
}
}else{
isValid =false;
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
}
return isValid; // TODO: IMPLEMENT
}
/** @see assemblernator.Instruction#assemble() */
@Override public int[] assemble() {
return null; // TODO: IMPLEMENT
}
/** @see assemblernator.Instruction#execute(int) */
@Override public void execute(int instruction) {
// TODO: IMPLEMENT
}
// =========================================================
// === Redundant code ======================================
// =========================================================
// === This code's the same in all instruction classes, ====
// === But Java lacks the mechanism to allow stuffing it ===
// === in super() where it belongs. ========================
// =========================================================
/**
* @see Instruction
* @return The static instance of this instruction.
*/
public static Instruction getInstance() {
return staticInstance;
}
/** @see assemblernator.Instruction#getOpId() */
@Override public String getOpId() {
return opId;
}
/** @see assemblernator.Instruction#getOpcode() */
@Override public int getOpcode() {
return opCode;
}
/** @see assemblernator.Instruction#getNewInstance() */
@Override public Instruction getNewInstance() {
return new USI_TRLK();
}
/**
* Calls the Instance(String,int) constructor to track this instruction.
*
* @param ignored
* Unused parameter; used to distinguish the constructor for the
* static instance.
*/
private USI_TRLK(boolean ignored) {
super(opId, opCode);
}
/** Default constructor; does nothing. */
private USI_TRLK() {}
}
| true | true | @Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
//operands less than two error
if (this.operands.size() < 2){
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1);
//checks combos for 2 operands
}else if(this.operands.size() == 2){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM")){
src="FM";
//range check
Operand o1 = getOperandData("FM");
int constantSize1 = module.evaluate(o1.expression, true, hErr, this,
o1.valueStartPosition);
this.getOperandData("FM").value = constantSize1;
isValid = OperandChecker.isValidMem(constantSize1);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
//dont know if this is need but can be cut out
}else if (this.hasOperand("FL")){
src="FL";
//range check
Operand o1 = getOperandData("FL");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
this.getOperandData("FL").value = constantSize1;
isValid = OperandChecker.isValidLiteral(constantSize1,ConstantRange.RANGE_SHIFT);
if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FM or FL"), this.lineNum, -1);
}
}else{
}
//checks combos for 3 operands
}else if(this.operands.size() == 3){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM") && this.hasOperand("FX")){
src="FMFX";
//range check
Operand o1 = getOperandData("FX");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
this.getOperandData("FR").value = constantSize1;
isValid = OperandChecker.isValidIndex(constantSize1);
if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1);
Operand o2 = getOperandData("FM");
int constantSize2 = module.evaluate(o2.expression, true, hErr, this,
o2.valueStartPosition);
this.getOperandData("FM").value = constantSize2;
isValid = OperandChecker.isValidMem(constantSize2);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FM and FX", "DR"), this.lineNum, -1);
}
}
}else{
isValid =false;
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
}
return isValid; // TODO: IMPLEMENT
}
| @Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
//operands less than two error
if (this.operands.size() < 2){
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1);
//checks combos for 2 operands
}else if(this.operands.size() == 2){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM")){
src="FM";
//range check
Operand o1 = getOperandData("FM");
int constantSize1 = module.evaluate(o1.expression, true, hErr, this,
o1.valueStartPosition);
this.getOperandData("FM").value = constantSize1;
isValid = OperandChecker.isValidMem(constantSize1);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
//dont know if this is need but can be cut out
}else if (this.hasOperand("FL")){
src="FL";
//range check
Operand o1 = getOperandData("FL");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
this.getOperandData("FL").value = constantSize1;
isValid = OperandChecker.isValidLiteral(constantSize1,ConstantRange.RANGE_SHIFT);
if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FM or FL"), this.lineNum, -1);
}
}else{
}
//checks combos for 3 operands
}else if(this.operands.size() == 3){
if(this.hasOperand("DR")){
dest="DR";
//range check
Operand o = getOperandData("DR");
int constantSize = module.evaluate(o.expression, false, hErr, this,
o.valueStartPosition);
this.getOperandData("DR").value = constantSize;
isValid = OperandChecker.isValidReg(constantSize);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
if(this.hasOperand("FM") && this.hasOperand("FX")){
src="FMFX";
//range check
Operand o1 = getOperandData("FX");
int constantSize1 = module.evaluate(o1.expression, false, hErr, this,
o1.valueStartPosition);
this.getOperandData("FX").value = constantSize1;
isValid = OperandChecker.isValidIndex(constantSize1);
if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1);
Operand o2 = getOperandData("FM");
int constantSize2 = module.evaluate(o2.expression, true, hErr, this,
o2.valueStartPosition);
this.getOperandData("FM").value = constantSize2;
isValid = OperandChecker.isValidMem(constantSize2);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1);
}else{
isValid=false;
hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FM and FX", "DR"), this.lineNum, -1);
}
}
}else{
isValid =false;
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
}
return isValid; // TODO: IMPLEMENT
}
|
diff --git a/src/main/java/bang/bang/App.java b/src/main/java/bang/bang/App.java
index f519b11..4da0b41 100644
--- a/src/main/java/bang/bang/App.java
+++ b/src/main/java/bang/bang/App.java
@@ -1,742 +1,743 @@
package bang.bang;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* Hello world!
*
*/
public class App
{
static String[] printArray = {"empty",
"You lily livered yellow bellied scoundrel",
"Butthead",
"You smell like manure.",
"You're as ugly as a burnt boot.",
"You couldn't teach a hen to cluck.",
"You're as dull as a dishwasher.",
"You gutless, yellow, pie-slinger",
"So, from now on, you better be lookin' behind you when you walk. 'Cause one day you're gonna get a bullet in your back.",
"You are uglier than a new-sheared sheep.",
"You Irish bug",
"Ouch!",
"You got me!",
"Barf!",
"Jackpot!",
"I'm laughing all the way to the bank.",
"Bonus!",
"Mmmmm…beer.",
"Drinks all around!",
"Yay... water",
"One tequila, two tequlia, three tequila, floor.",
"What wiskey will not cure, there is no cure for.",
"Thank heaven",
"INDIANS!!!",
"When I'm done with you, there won't be enough left of you to snore.",
"Cause of death? Lead poisoning.",
"Let's settle this once and for all, runt! Or ain't you got the gumption?",
"I aim to shoot somebody today and I'd prefer it'd be you.",
"Bang!",
"Bang, Bang!",
"Dodge this!",
"Not as deceiving as a low down, dirty... deceiver.","Make like a tree and get out of here.",
"That's about as funny as a screen door on a battleship.",
"Tim is a saboteur.",
"Let's go! I got me a runt to kill!",
"Let these sissies have their party.",
"Nobody calls me \"Mad Dog\", especially not some duded-up, egg-suckin' gutter trash.",
"I hate manure.","What's wrong, McFly. Chicken?",
"New York city! Get a rope.",
"There's a snake in my boot. ",
"Gimme, Gimme!",
"I'll be taking that.","Mine!",
"Get that trash out of here!",
"Go back to where you came from. ",
"Yeah, you can go ahead and get rid of that.",
"I'm armed and dangerous.",
"Which way to the gun show?",
"I'm on a horse.",
"Ha, you can't find me!",
"Saved by the Barrel.",
"Setting my sights.",
"I spy with my little eye.",
"Lets make this a little more interesting.",
"Kaboom!",
"I'm locking you up!",
"Nobody knows the trouble I've seen…",
"Thanks, sucker!",
"I'm getting better.",
"You Missed.",
"In yo face!",
"You couldn't hit water if you fell out of a boat.",
"I'm Buford 'Pi' Tannen","Blargh! *DEATH*",
"I call my gun Vera"};
static Random rnd = new Random();
static int health = 0;
static int rangeGun = 1;
static int rangeOther = 0;
static int myRange = rangeGun + rangeOther;
static List <String> roles = new ArrayList<String>();
static List <String> hand = new ArrayList<String>();
static List <String> bHand = new ArrayList<String>();
static List <GreenHand> gHand = new ArrayList<GreenHand>();
static String myRole = "";
static int inHand = 0;
static String lastCardPlayed = "";
static boolean isVolcanic = false;
static Long lastModifiedDate;
public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
System.out.println(action[0] + action[1] + action[2]);
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
System.out.println("b3 command");
b3Button(action[2]);
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
- System.out.println("green hands: " + gHand.get(0).getCard());
+ for (int i = 0; i < gHand.size(); i++)
+ System.out.println("green hands: " + gHand.get(i).getCard());
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void healMe() {
// TODO Auto-generated method stub
if(health >= 4){
//Print i have full health don't need to heal me
play("I have full health, don't need your heal");
}
else
{
health = health + 1;
//print my full health
play("my health should be: " + health);
}
}
private static void someoneShootAtMe(String card) {
int idxOfHand = 0;
if(card.equals("indians") || card.equals("duel")){
//do i have a miss
if(hand.contains("bang")){
idxOfHand = hand.indexOf("bang");
hand.remove(idxOfHand);
//print something to pi hand + bang, index
play ("Hand: " + String.valueOf(idxOfHand) +" card should be bang " + printArray[30].toString());
}
else{
//print something is wrong
//lost one health, if health is <= 0 print out die message
if(health >=2){
health = health - 1;
play ("Almost got me" + printArray[11] + "health is: " + health );
}
else
{
play ("I am dead " + printArray[13]);
}
}
}
else
{
if(gHand.contains("sombrero") || gHand.contains("tengallonhat") || gHand.contains("ironplate")
|| gHand.contains("bible")){
Iterator<GreenHand> iter = gHand.iterator();
while (iter.hasNext()) { // any more element
// Retrieve the next element, explicitly downcast from Object back to String
GreenHand gh = iter.next();
if(gh.Card.equals("sombrero") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("Hand: " + idxOfHand + " card should be sombrero " + " you can do better than this!");
break;
}
else if(gh.Card.equals("tengallonhat") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be sombrero " + " Oh my ten gallon hat is so heavy");
break;
}
else if(gh.Card.equals("ironplate") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be ironplate " + " nothing can come through with my iron plate");
break;
}
else if(gh.Card.equals("bible") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be bible " + " God is awesome!");
break;
}
}
}
else if(hand.contains("missed") ){
idxOfHand = hand.indexOf("missed");
hand.remove(idxOfHand);
//print something
System.out.println("hand: " + idxOfHand + " card should be miss " + " You Missed.");
play (String.valueOf("hand: " + idxOfHand + " card should be miss " + " You Missed."));
}
else if(hand.contains("dodge")){
idxOfHand = hand.indexOf("dodge");
hand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be dodge " + " I dodged the bullet.");
}
else{
//
if (health >= 2){
health = health - 1;
}
else
{
if(hand.contains("beer")){
idxOfHand = hand.indexOf("beer");
hand.remove(idxOfHand);
//print last health but played beer
play("hand: " + idxOfHand + " card should be beer " + " I am dead, but I have beer");
}
else{
//print I am dead, no miss or health
play(" I have no health, it's game over for me ");
}
}
}
}
}
private static void takeCardFromHand(String cardType,String card) {
int idxOfHand = 0;
if(cardType.equals("blue")){
if(bHand.contains(card)){
//do somehting
idxOfHand = bHand.indexOf(card);
bHand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else{
//print something wrong
play("are you sure? if you are here there is something wrong, you should start a new game. ");
}
}
else if(cardType.equals("gren")){
if(gHand.contains(card)){
//do something
idxOfHand = gHand.indexOf(card);
gHand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else{
//print something wrong
play("are you sure? if you are here, there is something wrong, you should start a new game. ");
}
}
else {
if(hand.contains(card)){
//do something
idxOfHand = hand.indexOf(card);
hand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else
{
//print something wrong
play("are you sure? if you are here, there is something wrong, you should start a new game. ");
}
}
}
public static void addToHand(int handType, String card) {
// resulted from b3 - used to add initial hand and general store cards
switch (handType) {
case 1: hand.add(card);
inHand++;
break;
case 2: GreenHand tmp = new GreenHand(card);
gHand.add(tmp);
inHand++;
break;
case 3: bHand.add(card);
inHand++;
break;
default: break;
}
}
public static void b3Button(String card) {
// see excel sheet B3 table
String print = new String();
String currentCard = new String();
int playerIndex;
int sheriffPos = findSheriff();
// if (card.equals("jail"))
// play("miss turn");
// if (card.equals("dynamite")) {
// health = health - 3;
// if (health <=0) {
// for (int i = 0; i < bHand.size(); i++) {
// currentCard = hand.get(i);
// if (currentCard.equals("beer")) {
// play("Hand: " + i + " " + printArray[17]);
// break;
// }
// }
// }
// else
// play(printArray[56]);
// }
System.out.println("in b3!");
for (int i = 0; i < bHand.size(); i++) {
System.out.println("looping blue hand");
currentCard = bHand.get(i);
if (currentCard.equals("jail")) {
do
playerIndex = choosePlayerIndex(roles.size());
while (playerIndex != sheriffPos);
}
if (currentCard.equals("dynamite")) {
playerIndex = choosePlayerIndex(roles.size());
}
if (currentCard.equals("binocular")) {
rangeOther++;
bHand.remove(i);
play("Hand: " + i + printArray[54]);
}
if (currentCard.equals("scope")) {
rangeOther++;
bHand.remove(i);
play("Hand: " + i + printArray[53]);
}
if (currentCard.equals("barrel") || currentCard.equals("hideout") || currentCard.equals("mustang")) {
bHand.remove(i);
play("Hand: " + i);
}
if (currentCard.equals("schofield") && rangeGun < 2) {
rangeGun = 2;
bHand.remove(i);
play("Hand: " + i + printArray[48]);
}
if (currentCard.equals("remindton") && rangeGun < 3){
rangeGun = 3;
bHand.remove(i);
play("Hand: " + i + printArray[49]);
}
if (currentCard.equals("schofield") && rangeGun < 4){
rangeGun = 4;
bHand.remove(i);
play("Hand: " + i + printArray[48]);
}
if (currentCard.equals("schofield") && rangeGun < 5){
rangeGun = 5;
bHand.remove(i);
play("Hand: " + i + printArray[49]);
}
if (currentCard.equals("volcanic")) {
if (!(myRole.contains("outlaw") && sheriffPos > 1)) {
rangeGun = 1;
isVolcanic = true;
bHand.remove(i);
play("Hand: " + i + printArray[66]);
}
}
}
for (int i = 0; i < gHand.size(); i++) {
GreenHand currentGreen = gHand.get(i);
if (currentGreen.isInPlay() && !currentGreen.isActive()) {
currentGreen.activate();
gHand.set(i,currentGreen);
}
}
for (int i = 0; i < gHand.size(); i++) {
System.out.println("looping green hand");
GreenHand currentGreen = gHand.get(i);
String cGCard = currentGreen.getCard();
if (currentGreen.isActive()) {
if (cGCard.equals("contestoga") || cGCard.equals("cancan") || cGCard.equals("pepperbox")
|| cGCard.equals("howitzer") || cGCard.equals("buffalorifle") || cGCard.equals("knife")
|| cGCard.equals("derringer")) {
play(String.valueOf("Green Hand: " + i + " On player: " + choosePlayerIndex(myRange)) + printArray[25]);
}
if (cGCard.equals("canteen") && health < 4) {
gHand.remove(i);
play("Green Hand: " + i + printArray[19]);
}
if (cGCard.equals("ponyexpress")) {
gHand.remove(i);
play("Green Hand: " + i + printArray[14]);
}
}
if (!currentGreen.isInPlay()) {
currentGreen.play();
gHand.set(i,currentGreen);
play("green card" + i + printArray[10]);
}
}
for (int i = 0; i < hand.size(); i++) {
System.out.println("looping hand");
String cBCard = hand.get(i);
if (cBCard.equals("panic")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(rangeOther)) + printArray[43]);
}
if (cBCard.equals("ragtime") || cBCard.equals("brawl")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i) + " On player: " + choosePlayerIndex(rangeOther)) + printArray[44]);
}
if (cBCard.equals("cat")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(roles.size())) + printArray[47]);
}
if (cBCard.equals("bang")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(myRange)) + printArray[28]);
}
if (cBCard.equals("gatling")) {
hand.remove(i);
play("Hand: " + i + " On player: " + choosePlayerIndex(myRange) + printArray[29]);
}
if (cBCard.equals("punch")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(rangeOther)) + printArray[30]);
}
if (cBCard.equals("springfield") || cBCard.equals("duel")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i) + " On player: " + choosePlayerIndex(roles.size())) + printArray[8]);
}
if (cBCard.equals("indians") || cBCard.equals("wellsfargo") || cBCard.equals("stagecoach")) {
hand.remove(i);
play("Hand: " + + i + printArray[15]);
}
if (health < 4) {
if (cBCard.equals("beer")) {
hand.remove(i);
play("Hand: " + i + printArray[17]);
}
if (cBCard.equals("saloon")) {
hand.remove(i);
play("Hand: " + i + printArray[18]);
}
if (cBCard.equals("whiskey")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i)) + printArray[21]);
}
if (cBCard.equals("tequila")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i)) + printArray[20]);
}
}
}
}
public static int randomCard(int index) {
int rand = rnd.nextInt(hand.size());
if (rand == index)
rand = randomCard(index);
return rand;
}
public static void b2Button(String card) {
// see excel sheet B2 table
switch (1) {
case 1:
break;
default: break;
}
}
public static void play(String str) {
try {
Runtime.getRuntime().exec("python scream.py \"" + str + "\"");
System.out.println("inside of method to exec scream.py ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int choosePlayerIndex(int range) {
/*
* Sheriff: shoot all
* Outlaw: shoot sheriff if in range, else random
* Deputy: shoot all except sheriff
* Renegade: shoot all except sheriff, sheriff last
*
*/
int sheriffPos = findSheriff();
int direction = 0; // 0 = left, 1 = right
if (!(sheriffPos == 0))
if (((double)sheriffPos/(double)roles.size()) > 0.5)
direction = 1;
int index = rnd.nextInt(Math.abs(range));
if (index == 0)
index++;
int sheriff = findSheriff();
// if (myRole.equals("sheriff")) {
// return index;
// }
// else
if (myRole.equals("renegade")) {
if (roles.get(index).equals("sheriff") && roles.size() > 2)
index = choosePlayerIndex(range);
}
else if (myRole.equals("deputy1") || myRole.equals("deputy2")) {
if (roles.get(index).equals("sheriff"))
index = choosePlayerIndex(range);
}
else if (myRole.equals("outlaw1") || myRole.equals("outlaw2") || myRole.equals("outlaw3")) {
if (sheriff <= myRange)
index = sheriff;
}
if (direction == 1)
return Math.abs(roles.size() - index);
else
return index;
}
public static int findSheriff () {
for (int i = 0; i < roles.size(); i++)
if (roles.get(i).equals("sheriff"))
return i;
return 0;
}
}
| true | true | public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
System.out.println(action[0] + action[1] + action[2]);
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
System.out.println("b3 command");
b3Button(action[2]);
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
System.out.println("green hands: " + gHand.get(0).getCard());
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
System.out.println(action[0] + action[1] + action[2]);
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
System.out.println("b3 command");
b3Button(action[2]);
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
for (int i = 0; i < gHand.size(); i++)
System.out.println("green hands: " + gHand.get(i).getCard());
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/web-wf-design/src/java/net/sf/taverna/portal/wireit/Wiring.java b/web-wf-design/src/java/net/sf/taverna/portal/wireit/Wiring.java
index 4f9c341..ea00ef1 100644
--- a/web-wf-design/src/java/net/sf/taverna/portal/wireit/Wiring.java
+++ b/web-wf-design/src/java/net/sf/taverna/portal/wireit/Wiring.java
@@ -1,153 +1,153 @@
package net.sf.taverna.portal.wireit;
import net.sf.taverna.portal.wireit.exception.WireItRunException;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.sf.taverna.portal.wireit.event.OutputListener;
import net.sf.taverna.portal.wireit.module.*;
import net.sf.taverna.portal.commandline.TavernaException;
import net.sf.taverna.portal.utils.Resolver;
/**
* This class takes a Json pipe and converts it into a number of connected modules which can then be run.
*
* A network of modules is built in the Constructor.
* Modules will be connected together using the listener pattern.
* These can then be run,
* and finally cobverted back to a Json object with the updated values.
* @author Christian
*/
public class Wiring {
/** An array of modules, which will be connected using Listeners.
* The values inside the object will change when the modules are run.
*/
Module[] modules;
/** The properties part of the original pipe which will be returned unchanged. */
JSONObject properties;
/** The wires part of the original pipe which will be returned unchanged. */
JSONArray wires;
/**
* Converts the jsonObject into a connected array of Modules and save other part of the Pipe.
* <p>
* There are three parts to a WireIt Json pipe, "modules", "properties" and "wires".
* <p>
* The "modules" array is converted into an array of uk.ac.manchester.cs.wireit.module Modules.
* The type of module used will depend on the name and xtype.
* Each element of the "modules" array will result in one element in the uk.ac.manchester.cs.wireit.module array.
* <p>
* The "properties" object is not used by the run so is simply saved so it can be included in the final output.
* <p>
* The "wires" array represent the connections between the modules.
* As these are not changed by a run the Json array is saved to be included as is in the final output.
* <p>
* The "wires" array is also used to create links between the modules.
* Modules are connected together using a Listener model.
* For each wire the "tgt" (Target) module is asked to provide a Listener for the relevant "terminal".
* The "src" (Source) modules is then asked to add this Listener to the relevant "terminal".
* @param jsonInput The pipe converted to json
* @param resolver Util to convert between files, absolute uri and relative uris
* @throws JSONException Thrown it the json is not in the expected format.
* @throws TavernaException Thrown by the TavernaModule if the information is inconsistant.
* @throws IOException Thrown by the TavernaModule if the workflow is unreadable.
*/
public Wiring(JSONObject jsonInput, Resolver resolver)
throws JSONException, TavernaException, IOException{
JSONArray jsonArray = jsonInput.getJSONArray("modules");
modules = new Module[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
Object json = jsonArray.get(i);
if (json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
String name = jsonObject.getString("name");
- if (name.equals("Simple Input")){
+ if (name.toLowerCase().equals("simple input")){
modules[i] = new InputStringModule(jsonObject);
- } else if (name.equals("List Input")){
+ } else if (name.toLowerCase().equals("list input")){
modules[i] = new InputListModule(jsonObject);
- } else if (name.equals("URL Input")){
+ } else if (name.toLowerCase().equals("url input")){
modules[i] = new InputURIModule(jsonObject);
- } else if (name.equals("URL To List Input")){
+ } else if (name.toLowerCase().equals("url list input")){
modules[i] = new InputDelimiterURIModule(jsonObject);
- } else if (name.equals("Simple Output") || name.equals("URL Output")){
+ } else if (name.toLowerCase().equals("simple output") || name.toLowerCase().equals("url output")){
modules[i] = new OutputModule(jsonObject);
- } else if (name.equals("List Output")){
+ } else if (name.toLowerCase().equals("list output")){
modules[i] = new OutputListModule(jsonObject);
} else if (name.equals("PassThrough")){
modules[i] = new PassThroughModule(jsonObject);
} else if (name.equals("comment")){
modules[i] = new CommentModule(jsonObject);
} else if (jsonObject.has("config")){
JSONObject config = jsonObject.getJSONObject("config");
String xtype = config.optString("xtype");
if ("WireIt.TavernaWFContainer".equalsIgnoreCase(xtype)){
modules[i] = new TavernaModule(jsonObject, resolver);
} else if ("WireIt.URILinkContainer".equalsIgnoreCase(xtype) || "WireIt.BaclavaContainer".equalsIgnoreCase(xtype)){
modules[i] = new URILinkModule(jsonObject);
} else {
throw new JSONException("Unexpected name " + name + " and xtype " + xtype + " in modules");
}
} else {
throw new JSONException("Unexpected name " + name + "and no config in modules");
}
} else {
throw new JSONException("Unexpected type " + json.getClass() + " in modules");
}
}
properties = jsonInput.getJSONObject("properties");
wires = jsonInput.getJSONArray("wires");
for (int i = 0; i < wires.length(); i++){
JSONObject wire = wires.optJSONObject(i);
JSONObject tgt = wire.getJSONObject("tgt");
int tgtNum = tgt.getInt("moduleId");
Module target = modules[tgtNum];
String terminal = tgt.getString("terminal");
System.out.println(tgtNum + " " + terminal + " " + target);
OutputListener outputListener = target.getOutputListener(terminal);
JSONObject src = wire.getJSONObject("src");
int srcNum = src.getInt("moduleId");
Module source = modules[srcNum];
terminal = src.getString("terminal");
source.addOutputListener(terminal, outputListener);
}
}
/**
* Runs the pipe by asking each module to run, logging can be done to the StringBuilder.
* <p>
* The individual modules are responsible for determining if they should run based on this call,
* or if they will run after receiving the expected input on their Listeners.
*
* @param outputBuilder Logging buffer.
* @throws WireItRunException Thrown by any module that encounter problems running itself,
* or when an exception is throw by a Listening module.
*/
public void run(StringBuilder outputBuilder) throws WireItRunException{
for (int i = 0; i < modules.length; i++){
modules[i].run(outputBuilder);
}
}
/**
* Converts the state of the modules back to json for returning to WireIt.
* <p>
* Typically called after the modules have been run.
* <p>
* Creates a new JSONObject adding the "wires" and "properties" saved during construction.
* <p>
* Creates a "modules" array including the JSON value of each module's current state.
* @return The current state as a json object.
* @throws JSONException
*/
public JSONObject getJsonObject() throws JSONException{
JSONObject me = new JSONObject();
me.put("wires", wires);
me.put("properties", properties);
for (int i = 0; i < modules.length; i++){
me.append("modules", modules[i].getJsonObject());
}
return me;
}
}
| false | true | public Wiring(JSONObject jsonInput, Resolver resolver)
throws JSONException, TavernaException, IOException{
JSONArray jsonArray = jsonInput.getJSONArray("modules");
modules = new Module[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
Object json = jsonArray.get(i);
if (json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
String name = jsonObject.getString("name");
if (name.equals("Simple Input")){
modules[i] = new InputStringModule(jsonObject);
} else if (name.equals("List Input")){
modules[i] = new InputListModule(jsonObject);
} else if (name.equals("URL Input")){
modules[i] = new InputURIModule(jsonObject);
} else if (name.equals("URL To List Input")){
modules[i] = new InputDelimiterURIModule(jsonObject);
} else if (name.equals("Simple Output") || name.equals("URL Output")){
modules[i] = new OutputModule(jsonObject);
} else if (name.equals("List Output")){
modules[i] = new OutputListModule(jsonObject);
} else if (name.equals("PassThrough")){
modules[i] = new PassThroughModule(jsonObject);
} else if (name.equals("comment")){
modules[i] = new CommentModule(jsonObject);
} else if (jsonObject.has("config")){
JSONObject config = jsonObject.getJSONObject("config");
String xtype = config.optString("xtype");
if ("WireIt.TavernaWFContainer".equalsIgnoreCase(xtype)){
modules[i] = new TavernaModule(jsonObject, resolver);
} else if ("WireIt.URILinkContainer".equalsIgnoreCase(xtype) || "WireIt.BaclavaContainer".equalsIgnoreCase(xtype)){
modules[i] = new URILinkModule(jsonObject);
} else {
throw new JSONException("Unexpected name " + name + " and xtype " + xtype + " in modules");
}
} else {
throw new JSONException("Unexpected name " + name + "and no config in modules");
}
} else {
throw new JSONException("Unexpected type " + json.getClass() + " in modules");
}
}
properties = jsonInput.getJSONObject("properties");
wires = jsonInput.getJSONArray("wires");
for (int i = 0; i < wires.length(); i++){
JSONObject wire = wires.optJSONObject(i);
JSONObject tgt = wire.getJSONObject("tgt");
int tgtNum = tgt.getInt("moduleId");
Module target = modules[tgtNum];
String terminal = tgt.getString("terminal");
System.out.println(tgtNum + " " + terminal + " " + target);
OutputListener outputListener = target.getOutputListener(terminal);
JSONObject src = wire.getJSONObject("src");
int srcNum = src.getInt("moduleId");
Module source = modules[srcNum];
terminal = src.getString("terminal");
source.addOutputListener(terminal, outputListener);
}
}
| public Wiring(JSONObject jsonInput, Resolver resolver)
throws JSONException, TavernaException, IOException{
JSONArray jsonArray = jsonInput.getJSONArray("modules");
modules = new Module[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
Object json = jsonArray.get(i);
if (json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
String name = jsonObject.getString("name");
if (name.toLowerCase().equals("simple input")){
modules[i] = new InputStringModule(jsonObject);
} else if (name.toLowerCase().equals("list input")){
modules[i] = new InputListModule(jsonObject);
} else if (name.toLowerCase().equals("url input")){
modules[i] = new InputURIModule(jsonObject);
} else if (name.toLowerCase().equals("url list input")){
modules[i] = new InputDelimiterURIModule(jsonObject);
} else if (name.toLowerCase().equals("simple output") || name.toLowerCase().equals("url output")){
modules[i] = new OutputModule(jsonObject);
} else if (name.toLowerCase().equals("list output")){
modules[i] = new OutputListModule(jsonObject);
} else if (name.equals("PassThrough")){
modules[i] = new PassThroughModule(jsonObject);
} else if (name.equals("comment")){
modules[i] = new CommentModule(jsonObject);
} else if (jsonObject.has("config")){
JSONObject config = jsonObject.getJSONObject("config");
String xtype = config.optString("xtype");
if ("WireIt.TavernaWFContainer".equalsIgnoreCase(xtype)){
modules[i] = new TavernaModule(jsonObject, resolver);
} else if ("WireIt.URILinkContainer".equalsIgnoreCase(xtype) || "WireIt.BaclavaContainer".equalsIgnoreCase(xtype)){
modules[i] = new URILinkModule(jsonObject);
} else {
throw new JSONException("Unexpected name " + name + " and xtype " + xtype + " in modules");
}
} else {
throw new JSONException("Unexpected name " + name + "and no config in modules");
}
} else {
throw new JSONException("Unexpected type " + json.getClass() + " in modules");
}
}
properties = jsonInput.getJSONObject("properties");
wires = jsonInput.getJSONArray("wires");
for (int i = 0; i < wires.length(); i++){
JSONObject wire = wires.optJSONObject(i);
JSONObject tgt = wire.getJSONObject("tgt");
int tgtNum = tgt.getInt("moduleId");
Module target = modules[tgtNum];
String terminal = tgt.getString("terminal");
System.out.println(tgtNum + " " + terminal + " " + target);
OutputListener outputListener = target.getOutputListener(terminal);
JSONObject src = wire.getJSONObject("src");
int srcNum = src.getInt("moduleId");
Module source = modules[srcNum];
terminal = src.getString("terminal");
source.addOutputListener(terminal, outputListener);
}
}
|
diff --git a/src/org/apache/xerces/impl/xs/util/XSTypeHelper.java b/src/org/apache/xerces/impl/xs/util/XSTypeHelper.java
index 3d0142a3..7ab75cc8 100644
--- a/src/org/apache/xerces/impl/xs/util/XSTypeHelper.java
+++ b/src/org/apache/xerces/impl/xs/util/XSTypeHelper.java
@@ -1,83 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.impl.xs.util;
import org.apache.xerces.xs.XSTypeDefinition;
/**
* Class defining utility/helper methods related to schema types.
*
* @author Mukul Gandhi, IBM
* @version $Id$
*/
public class XSTypeHelper {
/*
* Checks if the two schema type components are identical.
*/
public static boolean schemaTypesIdentical(XSTypeDefinition typeDefn1,
XSTypeDefinition typeDefn2) {
boolean typesIdentical = false;
String type1Name = typeDefn1.getName();
String type2Name = typeDefn2.getName();
- if ("anyType".equals(type1Name) &&
- "anyType".equals(type2Name)) {
- typesIdentical = true;
+ if (("anyType".equals(type1Name) &&
+ "anyType".equals(type2Name)) ||
+ ("anySimpleType".equals(type1Name) &&
+ "anySimpleType".equals(type2Name))) {
+ typesIdentical = true;
}
if (!typesIdentical) {
if (uriEqual(typeDefn1.getNamespace(), typeDefn2.getNamespace())) {
// if targetNamespace of types are same, then check for
// equality of type names and of the base type.
if ((type1Name == null && type2Name == null) ||
(type1Name != null && type1Name.equals(type2Name))
&& (schemaTypesIdentical(typeDefn1.getBaseType(),
typeDefn2.getBaseType()))) {
typesIdentical = true;
}
}
}
return typesIdentical;
} // schemaTypesIdentical
/*
* Check if two URI values are equal.
*/
public static boolean uriEqual(String uri1, String uri2) {
boolean uriEqual = false;
if ((uri1 != null && uri2 == null) ||
(uri1 == null && uri2 != null)) {
uriEqual = false;
} else if ((uri1 == null && uri2 == null) ||
uri1.equals(uri2)) {
uriEqual = true;
}
return uriEqual;
} // uriEqual
}
| true | true | public static boolean schemaTypesIdentical(XSTypeDefinition typeDefn1,
XSTypeDefinition typeDefn2) {
boolean typesIdentical = false;
String type1Name = typeDefn1.getName();
String type2Name = typeDefn2.getName();
if ("anyType".equals(type1Name) &&
"anyType".equals(type2Name)) {
typesIdentical = true;
}
if (!typesIdentical) {
if (uriEqual(typeDefn1.getNamespace(), typeDefn2.getNamespace())) {
// if targetNamespace of types are same, then check for
// equality of type names and of the base type.
if ((type1Name == null && type2Name == null) ||
(type1Name != null && type1Name.equals(type2Name))
&& (schemaTypesIdentical(typeDefn1.getBaseType(),
typeDefn2.getBaseType()))) {
typesIdentical = true;
}
}
}
return typesIdentical;
} // schemaTypesIdentical
| public static boolean schemaTypesIdentical(XSTypeDefinition typeDefn1,
XSTypeDefinition typeDefn2) {
boolean typesIdentical = false;
String type1Name = typeDefn1.getName();
String type2Name = typeDefn2.getName();
if (("anyType".equals(type1Name) &&
"anyType".equals(type2Name)) ||
("anySimpleType".equals(type1Name) &&
"anySimpleType".equals(type2Name))) {
typesIdentical = true;
}
if (!typesIdentical) {
if (uriEqual(typeDefn1.getNamespace(), typeDefn2.getNamespace())) {
// if targetNamespace of types are same, then check for
// equality of type names and of the base type.
if ((type1Name == null && type2Name == null) ||
(type1Name != null && type1Name.equals(type2Name))
&& (schemaTypesIdentical(typeDefn1.getBaseType(),
typeDefn2.getBaseType()))) {
typesIdentical = true;
}
}
}
return typesIdentical;
} // schemaTypesIdentical
|
diff --git a/src/gov/nih/nci/caintegrator/analysis/server/ClassComparisonTaskR.java b/src/gov/nih/nci/caintegrator/analysis/server/ClassComparisonTaskR.java
index 161a5cd..8225f03 100755
--- a/src/gov/nih/nci/caintegrator/analysis/server/ClassComparisonTaskR.java
+++ b/src/gov/nih/nci/caintegrator/analysis/server/ClassComparisonTaskR.java
@@ -1,382 +1,386 @@
package gov.nih.nci.caintegrator.analysis.server;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.*;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonRequest;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonResult;
import gov.nih.nci.caintegrator.analysis.messaging.AnalysisResult;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonResultEntry;
import gov.nih.nci.caintegrator.analysis.messaging.SampleGroup;
import gov.nih.nci.caintegrator.enumeration.*;
import gov.nih.nci.caintegrator.exceptions.AnalysisServerException;
import org.apache.log4j.Logger;
import org.rosuda.JRclient.*;
/**
* Performs the class comparison computation using R.
*
* @author harrismic
*
*/
/**
* caIntegrator License
*
* Copyright 2001-2005 Science Applications International Corporation ("SAIC").
* The software subject to this notice and license includes both human readable source code form and machine readable,
* binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with
* the National Cancer Institute ("NCI") by NCI employees and employees of SAIC.
* To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States
* Code, section 105.
* This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an
* entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control"
* for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity,
* whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii)
* beneficial ownership of such entity.
* This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive,
* worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights
* in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly
* display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed
* to and by third parties the caIntegrator Software and any modifications and derivative works thereof;
* and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such
* rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting
* or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no
* charge to You.
* 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions
* and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce
* the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This
* product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user
* documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments
* normally appear.
* 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and
* "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any
* trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with
* the terms of this License.
* 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and
* into any third party proprietary programs. However, if You incorporate the Software into third party proprietary
* programs, You agree that You are solely responsible for obtaining any permission from such third parties required to
* incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including
* without limitation Your end-users, of their obligation to secure any required permissions from such third parties
* before incorporating the Software into such third party proprietary software programs. In the event that You fail
* to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such permissions.
* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and
* to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses
* of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction,
* and distribution of the Work otherwise complies with the conditions stated in this License.
* 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
public class ClassComparisonTaskR extends AnalysisTaskR {
private ClassComparisonResult ccResult = null;
private Comparator classComparisonComparator = new ClassComparisonComparator();
public static final int MIN_GROUP_SIZE = 3;
private static Logger logger = Logger.getLogger(ClassComparisonTaskR.class);
public ClassComparisonTaskR(ClassComparisonRequest request) {
this(request, false);
}
public ClassComparisonTaskR(ClassComparisonRequest request,
boolean debugRcommands) {
super(request, debugRcommands);
}
public void run() {
ClassComparisonRequest ccRequest = (ClassComparisonRequest) getRequest();
ccResult = new ClassComparisonResult(ccRequest.getSessionId(), ccRequest.getTaskId());
logger.info(getExecutingThreadName() + ": processing class comparison request=" + ccRequest);
//set the data file
// check to see if the data file on the compute connection is the
//same as that for the analysis task
try {
setDataFile(ccRequest.getDataFileName());
} catch (AnalysisServerException e) {
e.setFailedRequest(ccRequest);
logger.error("Internal Error. Error setting data file to fileName=" + ccRequest.getDataFileName());
setException(e);
return;
}
SampleGroup group1 = ccRequest.getGroup1();
SampleGroup baselineGroup = ccRequest.getBaselineGroup();
if ((group1 == null) || (group1.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"Group1 is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if ((baselineGroup == null) || (baselineGroup.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"BaselineGroup is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
//check to see if there are any overlapping samples between the two groups
if ((group1 != null)&&(baselineGroup != null)) {
//get overlap between the two sets
Set<String> intersection = new HashSet<String>();
intersection.addAll(group1);
intersection.retainAll(baselineGroup);
if (intersection.size() > 0) {
//the groups are overlapping so return an exception
StringBuffer ids = new StringBuffer();
for (Iterator i=intersection.iterator(); i.hasNext(); ) {
ids.append(i.next());
if (i.hasNext()) {
ids.append(",");
}
}
AnalysisServerException ex = new AnalysisServerException(
"Can not perform class comparison with overlapping groups. Overlapping ids=" + ids.toString());
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
}
//For now assume that there are two groups. When we get data for two channel array then
//allow only one group so leaving in the possiblity of having only one group in the code
//below eventhough the one group case won't be executed because of the tests above.
int grp1Len = 0, baselineGrpLen = 0;
grp1Len = group1.size();
String grp1RName = "GRP1IDS";
String baselineGrpRName = "BLGRPIDS";
String rCmd = null;
rCmd = getRgroupCmd(grp1RName, group1);
try {
doRvoidEval(rCmd);
if (baselineGroup != null) {
// two group comparison
baselineGrpLen = baselineGroup.size();
rCmd = getRgroupCmd(baselineGrpRName, baselineGroup);
doRvoidEval(rCmd);
// create the input data matrix using the sample groups
rCmd = "ccInputMatrix <- getSubmatrix.twogrps(dataMatrix,"
+ grp1RName + "," + baselineGrpRName + ")";
doRvoidEval(rCmd);
// check to make sure all identifiers matched in the R data file
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
} else {
// single group comparison
- baselineGrpLen = 0;
- rCmd = "ccInputMatrix <- getSubmatrix.onegrp(dataMatrix,"
- + grp1RName + ")";
- doRvoidEval(rCmd);
+// baselineGrpLen = 0;
+// rCmd = "ccInputMatrix <- getSubmatrix.onegrp(dataMatrix,"
+// + grp1RName + ")";
+// doRvoidEval(rCmd);
+ logger.error("Single group comparison is not currently supported.");
+ throw new AnalysisServerException("Unsupported operation: Attempted to do a single group comparison.");
}
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if (ccRequest.getStatisticalMethod() == StatisticalMethodType.TTest) {
// do the TTest computation
rCmd = "ccResult <- myttest(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
} else if (ccRequest.getStatisticalMethod() == StatisticalMethodType.Wilcoxin) {
// do the Wilcox computation
rCmd = "ccResult <- mywilcox(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
}
else {
logger.error("ClassComparision unrecognized statistical method.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// do filtering
double foldChangeThreshold = ccRequest.getFoldChangeThreshold();
double pValueThreshold = ccRequest.getPvalueThreshold();
MultiGroupComparisonAdjustmentType adjMethod = ccRequest
.getMultiGroupComparisonAdjustmentType();
if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) {
// get differentially expressed reporters using
// unadjusted Pvalue
// shouldn't need to pass in ccInputMatrix
rCmd = "ccResult <- mydiferentiallygenes(ccResult,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(false);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) {
// do adjustment
rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ccResult)";
doRvoidEval(rCmd);
// get differentially expressed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) {
// do adjustment
rCmd = "adjust.result <- adjustP.Bonferroni(ccResult)";
doRvoidEval(rCmd);
// get differentially expresseed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
}
else {
logger.error("ClassComparision Adjustment Type unrecognized.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// get the results and send
// double[] meanGrp1 = doREval("mean1 <- ccResult[,1]").asDoubleArray();
// double[] meanBaselineGrp = doREval("meanBaseline <- ccResult[,2]").asDoubleArray();
// double[] meanDif = doREval("meanDif <- ccResult[,3]").asDoubleArray();
// double[] absoluteFoldChange = doREval("fc <- ccResult[,4]").asDoubleArray();
// double[] pva = doREval("pva <- ccResult[,5]").asDoubleArray();
double[] meanGrp1 = doREval("mean1 <- ccResult$mean1").asDoubleArray();
double[] meanBaselineGrp = doREval("meanBaseline <- ccResult$mean2").asDoubleArray();
double[] meanDif = doREval("meanDif <- ccResult$mean.diff").asDoubleArray();
double[] absoluteFoldChange = doREval("fc <- ccResult$fc").asDoubleArray();
double[] pva = doREval("pva <- ccResult$pval").asDoubleArray();
double[] stdG1 = doREval("stdG1 <- ccResult$std1").asDoubleArray();
double[] stdBaseline = doREval("stdBL <- ccResult$std2").asDoubleArray();
// get the labels
Vector reporterIds = doREval("ccLabels <- dimnames(ccResult)[[1]]")
.asVector();
// load the result object
// need to see if this works for single group comparison
List<ClassComparisonResultEntry> resultEntries = new ArrayList<ClassComparisonResultEntry>(
meanGrp1.length);
ClassComparisonResultEntry resultEntry;
for (int i = 0; i < meanGrp1.length; i++) {
resultEntry = new ClassComparisonResultEntry();
resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString());
resultEntry.setMeanGrp1(meanGrp1[i]);
resultEntry.setMeanBaselineGrp(meanBaselineGrp[i]);
resultEntry.setMeanDiff(meanDif[i]);
resultEntry.setAbsoluteFoldChange(absoluteFoldChange[i]);
resultEntry.setPvalue(pva[i]);
resultEntry.setStdGrp1(stdG1[i]);
resultEntry.setStdBaselineGrp(stdBaseline[i]);
resultEntries.add(resultEntry);
}
Collections.sort(resultEntries, classComparisonComparator);
ccResult.setResultEntries(resultEntries);
ccResult.setGroup1(group1);
if (baselineGroup != null) {
ccResult.setBaselineGroup(baselineGroup);
}
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + asex.getMessage());
aex.setFailedRequest(ccRequest);
setException(aex);
+ logger.error(asex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + ex.getMessage());
asex.setFailedRequest(ccRequest);
setException(asex);
+ logger.error(ex);
return;
}
}
public AnalysisResult getResult() {
return ccResult;
}
public ClassComparisonResult getClassComparisonResult() {
return ccResult;
}
/**
* Clean up some of the resources
*/
public void cleanUp() {
//doRvoidEval("remove(ccInputMatrix)");
//doRvoidEval("remove(ccResult)");
try {
setRComputeConnection(null);
} catch (AnalysisServerException e) {
logger.error("Error in cleanUp method.");
logger.error(e);
setException(e);
}
}
}
| false | true | public void run() {
ClassComparisonRequest ccRequest = (ClassComparisonRequest) getRequest();
ccResult = new ClassComparisonResult(ccRequest.getSessionId(), ccRequest.getTaskId());
logger.info(getExecutingThreadName() + ": processing class comparison request=" + ccRequest);
//set the data file
// check to see if the data file on the compute connection is the
//same as that for the analysis task
try {
setDataFile(ccRequest.getDataFileName());
} catch (AnalysisServerException e) {
e.setFailedRequest(ccRequest);
logger.error("Internal Error. Error setting data file to fileName=" + ccRequest.getDataFileName());
setException(e);
return;
}
SampleGroup group1 = ccRequest.getGroup1();
SampleGroup baselineGroup = ccRequest.getBaselineGroup();
if ((group1 == null) || (group1.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"Group1 is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if ((baselineGroup == null) || (baselineGroup.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"BaselineGroup is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
//check to see if there are any overlapping samples between the two groups
if ((group1 != null)&&(baselineGroup != null)) {
//get overlap between the two sets
Set<String> intersection = new HashSet<String>();
intersection.addAll(group1);
intersection.retainAll(baselineGroup);
if (intersection.size() > 0) {
//the groups are overlapping so return an exception
StringBuffer ids = new StringBuffer();
for (Iterator i=intersection.iterator(); i.hasNext(); ) {
ids.append(i.next());
if (i.hasNext()) {
ids.append(",");
}
}
AnalysisServerException ex = new AnalysisServerException(
"Can not perform class comparison with overlapping groups. Overlapping ids=" + ids.toString());
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
}
//For now assume that there are two groups. When we get data for two channel array then
//allow only one group so leaving in the possiblity of having only one group in the code
//below eventhough the one group case won't be executed because of the tests above.
int grp1Len = 0, baselineGrpLen = 0;
grp1Len = group1.size();
String grp1RName = "GRP1IDS";
String baselineGrpRName = "BLGRPIDS";
String rCmd = null;
rCmd = getRgroupCmd(grp1RName, group1);
try {
doRvoidEval(rCmd);
if (baselineGroup != null) {
// two group comparison
baselineGrpLen = baselineGroup.size();
rCmd = getRgroupCmd(baselineGrpRName, baselineGroup);
doRvoidEval(rCmd);
// create the input data matrix using the sample groups
rCmd = "ccInputMatrix <- getSubmatrix.twogrps(dataMatrix,"
+ grp1RName + "," + baselineGrpRName + ")";
doRvoidEval(rCmd);
// check to make sure all identifiers matched in the R data file
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
} else {
// single group comparison
baselineGrpLen = 0;
rCmd = "ccInputMatrix <- getSubmatrix.onegrp(dataMatrix,"
+ grp1RName + ")";
doRvoidEval(rCmd);
}
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if (ccRequest.getStatisticalMethod() == StatisticalMethodType.TTest) {
// do the TTest computation
rCmd = "ccResult <- myttest(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
} else if (ccRequest.getStatisticalMethod() == StatisticalMethodType.Wilcoxin) {
// do the Wilcox computation
rCmd = "ccResult <- mywilcox(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
}
else {
logger.error("ClassComparision unrecognized statistical method.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// do filtering
double foldChangeThreshold = ccRequest.getFoldChangeThreshold();
double pValueThreshold = ccRequest.getPvalueThreshold();
MultiGroupComparisonAdjustmentType adjMethod = ccRequest
.getMultiGroupComparisonAdjustmentType();
if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) {
// get differentially expressed reporters using
// unadjusted Pvalue
// shouldn't need to pass in ccInputMatrix
rCmd = "ccResult <- mydiferentiallygenes(ccResult,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(false);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) {
// do adjustment
rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ccResult)";
doRvoidEval(rCmd);
// get differentially expressed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) {
// do adjustment
rCmd = "adjust.result <- adjustP.Bonferroni(ccResult)";
doRvoidEval(rCmd);
// get differentially expresseed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
}
else {
logger.error("ClassComparision Adjustment Type unrecognized.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// get the results and send
// double[] meanGrp1 = doREval("mean1 <- ccResult[,1]").asDoubleArray();
// double[] meanBaselineGrp = doREval("meanBaseline <- ccResult[,2]").asDoubleArray();
// double[] meanDif = doREval("meanDif <- ccResult[,3]").asDoubleArray();
// double[] absoluteFoldChange = doREval("fc <- ccResult[,4]").asDoubleArray();
// double[] pva = doREval("pva <- ccResult[,5]").asDoubleArray();
double[] meanGrp1 = doREval("mean1 <- ccResult$mean1").asDoubleArray();
double[] meanBaselineGrp = doREval("meanBaseline <- ccResult$mean2").asDoubleArray();
double[] meanDif = doREval("meanDif <- ccResult$mean.diff").asDoubleArray();
double[] absoluteFoldChange = doREval("fc <- ccResult$fc").asDoubleArray();
double[] pva = doREval("pva <- ccResult$pval").asDoubleArray();
double[] stdG1 = doREval("stdG1 <- ccResult$std1").asDoubleArray();
double[] stdBaseline = doREval("stdBL <- ccResult$std2").asDoubleArray();
// get the labels
Vector reporterIds = doREval("ccLabels <- dimnames(ccResult)[[1]]")
.asVector();
// load the result object
// need to see if this works for single group comparison
List<ClassComparisonResultEntry> resultEntries = new ArrayList<ClassComparisonResultEntry>(
meanGrp1.length);
ClassComparisonResultEntry resultEntry;
for (int i = 0; i < meanGrp1.length; i++) {
resultEntry = new ClassComparisonResultEntry();
resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString());
resultEntry.setMeanGrp1(meanGrp1[i]);
resultEntry.setMeanBaselineGrp(meanBaselineGrp[i]);
resultEntry.setMeanDiff(meanDif[i]);
resultEntry.setAbsoluteFoldChange(absoluteFoldChange[i]);
resultEntry.setPvalue(pva[i]);
resultEntry.setStdGrp1(stdG1[i]);
resultEntry.setStdBaselineGrp(stdBaseline[i]);
resultEntries.add(resultEntry);
}
Collections.sort(resultEntries, classComparisonComparator);
ccResult.setResultEntries(resultEntries);
ccResult.setGroup1(group1);
if (baselineGroup != null) {
ccResult.setBaselineGroup(baselineGroup);
}
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + asex.getMessage());
aex.setFailedRequest(ccRequest);
setException(aex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + ex.getMessage());
asex.setFailedRequest(ccRequest);
setException(asex);
return;
}
}
| public void run() {
ClassComparisonRequest ccRequest = (ClassComparisonRequest) getRequest();
ccResult = new ClassComparisonResult(ccRequest.getSessionId(), ccRequest.getTaskId());
logger.info(getExecutingThreadName() + ": processing class comparison request=" + ccRequest);
//set the data file
// check to see if the data file on the compute connection is the
//same as that for the analysis task
try {
setDataFile(ccRequest.getDataFileName());
} catch (AnalysisServerException e) {
e.setFailedRequest(ccRequest);
logger.error("Internal Error. Error setting data file to fileName=" + ccRequest.getDataFileName());
setException(e);
return;
}
SampleGroup group1 = ccRequest.getGroup1();
SampleGroup baselineGroup = ccRequest.getBaselineGroup();
if ((group1 == null) || (group1.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"Group1 is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if ((baselineGroup == null) || (baselineGroup.size() < MIN_GROUP_SIZE)) {
AnalysisServerException ex = new AnalysisServerException(
"BaselineGroup is null or has less than " + MIN_GROUP_SIZE + " entries.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
//check to see if there are any overlapping samples between the two groups
if ((group1 != null)&&(baselineGroup != null)) {
//get overlap between the two sets
Set<String> intersection = new HashSet<String>();
intersection.addAll(group1);
intersection.retainAll(baselineGroup);
if (intersection.size() > 0) {
//the groups are overlapping so return an exception
StringBuffer ids = new StringBuffer();
for (Iterator i=intersection.iterator(); i.hasNext(); ) {
ids.append(i.next());
if (i.hasNext()) {
ids.append(",");
}
}
AnalysisServerException ex = new AnalysisServerException(
"Can not perform class comparison with overlapping groups. Overlapping ids=" + ids.toString());
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
}
//For now assume that there are two groups. When we get data for two channel array then
//allow only one group so leaving in the possiblity of having only one group in the code
//below eventhough the one group case won't be executed because of the tests above.
int grp1Len = 0, baselineGrpLen = 0;
grp1Len = group1.size();
String grp1RName = "GRP1IDS";
String baselineGrpRName = "BLGRPIDS";
String rCmd = null;
rCmd = getRgroupCmd(grp1RName, group1);
try {
doRvoidEval(rCmd);
if (baselineGroup != null) {
// two group comparison
baselineGrpLen = baselineGroup.size();
rCmd = getRgroupCmd(baselineGrpRName, baselineGroup);
doRvoidEval(rCmd);
// create the input data matrix using the sample groups
rCmd = "ccInputMatrix <- getSubmatrix.twogrps(dataMatrix,"
+ grp1RName + "," + baselineGrpRName + ")";
doRvoidEval(rCmd);
// check to make sure all identifiers matched in the R data file
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
} else {
// single group comparison
// baselineGrpLen = 0;
// rCmd = "ccInputMatrix <- getSubmatrix.onegrp(dataMatrix,"
// + grp1RName + ")";
// doRvoidEval(rCmd);
logger.error("Single group comparison is not currently supported.");
throw new AnalysisServerException("Unsupported operation: Attempted to do a single group comparison.");
}
rCmd = "dim(ccInputMatrix)[2]";
int numMatched = doREval(rCmd).asInt();
if (numMatched != (grp1Len + baselineGrpLen)) {
AnalysisServerException ex = new AnalysisServerException(
"Some sample ids did not match R data file for class comparison request.");
ex.setFailedRequest(ccRequest);
ex.setFailedRequest(ccRequest);
setException(ex);
return;
}
if (ccRequest.getStatisticalMethod() == StatisticalMethodType.TTest) {
// do the TTest computation
rCmd = "ccResult <- myttest(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
} else if (ccRequest.getStatisticalMethod() == StatisticalMethodType.Wilcoxin) {
// do the Wilcox computation
rCmd = "ccResult <- mywilcox(ccInputMatrix, " + grp1Len + ","
+ baselineGrpLen + ")";
doRvoidEval(rCmd);
}
else {
logger.error("ClassComparision unrecognized statistical method.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// do filtering
double foldChangeThreshold = ccRequest.getFoldChangeThreshold();
double pValueThreshold = ccRequest.getPvalueThreshold();
MultiGroupComparisonAdjustmentType adjMethod = ccRequest
.getMultiGroupComparisonAdjustmentType();
if (adjMethod == MultiGroupComparisonAdjustmentType.NONE) {
// get differentially expressed reporters using
// unadjusted Pvalue
// shouldn't need to pass in ccInputMatrix
rCmd = "ccResult <- mydiferentiallygenes(ccResult,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(false);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FDR) {
// do adjustment
rCmd = "adjust.result <- adjustP.Benjamini.Hochberg(ccResult)";
doRvoidEval(rCmd);
// get differentially expressed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
} else if (adjMethod == MultiGroupComparisonAdjustmentType.FWER) {
// do adjustment
rCmd = "adjust.result <- adjustP.Bonferroni(ccResult)";
doRvoidEval(rCmd);
// get differentially expresseed reporters using adjusted Pvalue
rCmd = "ccResult <- mydiferentiallygenes.adjustP(adjust.result,"
+ foldChangeThreshold + "," + pValueThreshold + ")";
doRvoidEval(rCmd);
ccResult.setPvaluesAreAdjusted(true);
}
else {
logger.error("ClassComparision Adjustment Type unrecognized.");
this.setException(new AnalysisServerException("Internal error: unrecognized adjustment type."));
return;
}
// get the results and send
// double[] meanGrp1 = doREval("mean1 <- ccResult[,1]").asDoubleArray();
// double[] meanBaselineGrp = doREval("meanBaseline <- ccResult[,2]").asDoubleArray();
// double[] meanDif = doREval("meanDif <- ccResult[,3]").asDoubleArray();
// double[] absoluteFoldChange = doREval("fc <- ccResult[,4]").asDoubleArray();
// double[] pva = doREval("pva <- ccResult[,5]").asDoubleArray();
double[] meanGrp1 = doREval("mean1 <- ccResult$mean1").asDoubleArray();
double[] meanBaselineGrp = doREval("meanBaseline <- ccResult$mean2").asDoubleArray();
double[] meanDif = doREval("meanDif <- ccResult$mean.diff").asDoubleArray();
double[] absoluteFoldChange = doREval("fc <- ccResult$fc").asDoubleArray();
double[] pva = doREval("pva <- ccResult$pval").asDoubleArray();
double[] stdG1 = doREval("stdG1 <- ccResult$std1").asDoubleArray();
double[] stdBaseline = doREval("stdBL <- ccResult$std2").asDoubleArray();
// get the labels
Vector reporterIds = doREval("ccLabels <- dimnames(ccResult)[[1]]")
.asVector();
// load the result object
// need to see if this works for single group comparison
List<ClassComparisonResultEntry> resultEntries = new ArrayList<ClassComparisonResultEntry>(
meanGrp1.length);
ClassComparisonResultEntry resultEntry;
for (int i = 0; i < meanGrp1.length; i++) {
resultEntry = new ClassComparisonResultEntry();
resultEntry.setReporterId(((REXP) reporterIds.get(i)).asString());
resultEntry.setMeanGrp1(meanGrp1[i]);
resultEntry.setMeanBaselineGrp(meanBaselineGrp[i]);
resultEntry.setMeanDiff(meanDif[i]);
resultEntry.setAbsoluteFoldChange(absoluteFoldChange[i]);
resultEntry.setPvalue(pva[i]);
resultEntry.setStdGrp1(stdG1[i]);
resultEntry.setStdBaselineGrp(stdBaseline[i]);
resultEntries.add(resultEntry);
}
Collections.sort(resultEntries, classComparisonComparator);
ccResult.setResultEntries(resultEntries);
ccResult.setGroup1(group1);
if (baselineGroup != null) {
ccResult.setBaselineGroup(baselineGroup);
}
}
catch (AnalysisServerException asex) {
AnalysisServerException aex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + asex.getMessage());
aex.setFailedRequest(ccRequest);
setException(aex);
logger.error(asex);
return;
}
catch (Exception ex) {
AnalysisServerException asex = new AnalysisServerException(
"Internal Error. Caught AnalysisServerException in ClassComparisonTaskR." + ex.getMessage());
asex.setFailedRequest(ccRequest);
setException(asex);
logger.error(ex);
return;
}
}
|
diff --git a/src/net/mayateck/ChatChannels/ChatHandler.java b/src/net/mayateck/ChatChannels/ChatHandler.java
index d3dfff3..1157147 100644
--- a/src/net/mayateck/ChatChannels/ChatHandler.java
+++ b/src/net/mayateck/ChatChannels/ChatHandler.java
@@ -1,98 +1,97 @@
package net.mayateck.ChatChannels;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class ChatHandler implements Listener{
private ChatChannels plugin;
public ChatHandler(ChatChannels plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
this.plugin = plugin;
}
@EventHandler
public void onChatted(AsyncPlayerChatEvent e){
e.setCancelled(true); // I'm overriding the event and faking a chat. Sorry other plug-ins!
Player p = e.getPlayer();
String n = p.getName();
String m = e.getMessage();
Player[] pl = Bukkit.getOnlinePlayers();
String c = plugin.getPlayersList().getString("players."+n+".channel");
String t = plugin.getConfig().getString("channels."+c+".tag");
String tc = plugin.getConfig().getString("channels."+c+".color");
if (p.hasPermission("chatchannels.group.admin")){
n = "Admin-"+n;
} else if (p.hasPermission("chatchannels.group.mod")){
n = "Mod-"+n;
}
String msg="�"+tc+t+" "+n+": "+m;
if (c.equalsIgnoreCase("admin")){
Bukkit.getServer().broadcast(msg, "chatchannels.group.admin");
} else if (c.equalsIgnoreCase("mod")){
- Bukkit.getServer().broadcast(msg, "chatchannels.group.admin");
Bukkit.getServer().broadcast(msg, "chatchannels.group.mod");
} else if (c.equalsIgnoreCase("help")){
for (Player cp : pl){
if (cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod") || plugin.getPlayersList().getString("players."+cp.getName()+".channel").equalsIgnoreCase("help")){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("zone")){
for (Player cp : pl){
- if (cp.getWorld()==p.getWorld()){
+ if (cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod") || cp.getWorld()==p.getWorld()){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("local")){
for (Player cp : pl){
double pX = p.getLocation().getX();
double pZ = p.getLocation().getZ();
double cpX = cp.getLocation().getX();
double cpZ = cp.getLocation().getZ();
int dist = plugin.getConfig().getInt("channels.local.distance");
boolean xMatch = false;
boolean zMatch = false;
if (pX-cpX<dist || cpX-pX<dist){
xMatch=true;}
if (pZ-cpZ<dist || cpZ-pZ<dist){
zMatch=true;}
if ((cp.getWorld()==p.getWorld() && zMatch==true && xMatch==true) ||cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod")){
cp.sendMessage(msg);
}
}
} else {
Bukkit.getServer().broadcastMessage(msg);
}
}
@EventHandler(priority=EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent e){
Player p = e.getPlayer();
String n = p.getName();
String b = plugin.getConfig().getString("channels.broadcast.tag");
String c = plugin.getConfig().getString("channels.broadcast.color");
if (plugin.getPlayersList().contains("players."+n)){
Bukkit.getServer().broadcastMessage("�"+c+b+" �i"+n+" �"+c+"has connected.");
} else {
plugin.getPlayersList().set("players."+n+".channel", "global");
plugin.savePlayersList();
Bukkit.getServer().broadcastMessage("�"+c+b+" �i"+n+" �"+c+"has connected for the first time.");
Bukkit.getServer().broadcastMessage("�"+c+b+" Welcome �i"+n+" �"+c+"!");
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e){
Player p = e.getPlayer();
String n = p.getName();
String b = plugin.getConfig().getString("channels.broadcast.tag");
String c = plugin.getConfig().getString("channels.broadcast.color");
Bukkit.getServer().broadcastMessage("�"+c+b+" �i"+n+" �"+c+"has disconnected.");
}
}
| false | true | public void onChatted(AsyncPlayerChatEvent e){
e.setCancelled(true); // I'm overriding the event and faking a chat. Sorry other plug-ins!
Player p = e.getPlayer();
String n = p.getName();
String m = e.getMessage();
Player[] pl = Bukkit.getOnlinePlayers();
String c = plugin.getPlayersList().getString("players."+n+".channel");
String t = plugin.getConfig().getString("channels."+c+".tag");
String tc = plugin.getConfig().getString("channels."+c+".color");
if (p.hasPermission("chatchannels.group.admin")){
n = "Admin-"+n;
} else if (p.hasPermission("chatchannels.group.mod")){
n = "Mod-"+n;
}
String msg="�"+tc+t+" "+n+": "+m;
if (c.equalsIgnoreCase("admin")){
Bukkit.getServer().broadcast(msg, "chatchannels.group.admin");
} else if (c.equalsIgnoreCase("mod")){
Bukkit.getServer().broadcast(msg, "chatchannels.group.admin");
Bukkit.getServer().broadcast(msg, "chatchannels.group.mod");
} else if (c.equalsIgnoreCase("help")){
for (Player cp : pl){
if (cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod") || plugin.getPlayersList().getString("players."+cp.getName()+".channel").equalsIgnoreCase("help")){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("zone")){
for (Player cp : pl){
if (cp.getWorld()==p.getWorld()){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("local")){
for (Player cp : pl){
double pX = p.getLocation().getX();
double pZ = p.getLocation().getZ();
double cpX = cp.getLocation().getX();
double cpZ = cp.getLocation().getZ();
int dist = plugin.getConfig().getInt("channels.local.distance");
boolean xMatch = false;
boolean zMatch = false;
if (pX-cpX<dist || cpX-pX<dist){
xMatch=true;}
if (pZ-cpZ<dist || cpZ-pZ<dist){
zMatch=true;}
if ((cp.getWorld()==p.getWorld() && zMatch==true && xMatch==true) ||cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod")){
cp.sendMessage(msg);
}
}
} else {
Bukkit.getServer().broadcastMessage(msg);
}
}
| public void onChatted(AsyncPlayerChatEvent e){
e.setCancelled(true); // I'm overriding the event and faking a chat. Sorry other plug-ins!
Player p = e.getPlayer();
String n = p.getName();
String m = e.getMessage();
Player[] pl = Bukkit.getOnlinePlayers();
String c = plugin.getPlayersList().getString("players."+n+".channel");
String t = plugin.getConfig().getString("channels."+c+".tag");
String tc = plugin.getConfig().getString("channels."+c+".color");
if (p.hasPermission("chatchannels.group.admin")){
n = "Admin-"+n;
} else if (p.hasPermission("chatchannels.group.mod")){
n = "Mod-"+n;
}
String msg="�"+tc+t+" "+n+": "+m;
if (c.equalsIgnoreCase("admin")){
Bukkit.getServer().broadcast(msg, "chatchannels.group.admin");
} else if (c.equalsIgnoreCase("mod")){
Bukkit.getServer().broadcast(msg, "chatchannels.group.mod");
} else if (c.equalsIgnoreCase("help")){
for (Player cp : pl){
if (cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod") || plugin.getPlayersList().getString("players."+cp.getName()+".channel").equalsIgnoreCase("help")){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("zone")){
for (Player cp : pl){
if (cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod") || cp.getWorld()==p.getWorld()){
cp.sendMessage(msg);
}
}
} else if (c.equalsIgnoreCase("local")){
for (Player cp : pl){
double pX = p.getLocation().getX();
double pZ = p.getLocation().getZ();
double cpX = cp.getLocation().getX();
double cpZ = cp.getLocation().getZ();
int dist = plugin.getConfig().getInt("channels.local.distance");
boolean xMatch = false;
boolean zMatch = false;
if (pX-cpX<dist || cpX-pX<dist){
xMatch=true;}
if (pZ-cpZ<dist || cpZ-pZ<dist){
zMatch=true;}
if ((cp.getWorld()==p.getWorld() && zMatch==true && xMatch==true) ||cp.hasPermission("chatchannels.group.admin") || cp.hasPermission("chatchannels.group.mod")){
cp.sendMessage(msg);
}
}
} else {
Bukkit.getServer().broadcastMessage(msg);
}
}
|
diff --git a/it.baeyens.arduino.common/src/it/baeyens/arduino/common/Common.java b/it.baeyens.arduino.common/src/it/baeyens/arduino/common/Common.java
index 9adc8636..9e9b63b3 100644
--- a/it.baeyens.arduino.common/src/it/baeyens/arduino/common/Common.java
+++ b/it.baeyens.arduino.common/src/it/baeyens/arduino/common/Common.java
@@ -1,715 +1,720 @@
package it.baeyens.arduino.common;
import it.baeyens.arduino.arduino.Serial;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.envvar.IEnvironmentVariableManager;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
public class Common extends ArduinoInstancePreferences {
private static boolean RXTXLibraryLoaded = false;
static ISerialUser OtherSerialUser = null; // If someone else uses the
// serial port he can register
// here so we can
// request him to disconnect
// when we need the serial port
/**
* This method is used to register a serial user. A serial user is alerted when the serial port will be disconnected (for instance for a upload)
* The serial user is requested to act appropriately Only 1 serial user can be registered at a given time. No check is done.
*
* @param SerialUser
*/
public static void registerSerialUser(ISerialUser SerialUser) {
OtherSerialUser = SerialUser;
}
/**
* This method is to unregister a serial user.
*/
public static void UnRegisterSerialUser() {
OtherSerialUser = null;
}
/**
* This method makes sure that a string can be used as a file or folder name<br/>
* To do this it replaces all unacceptable characters with underscores.<br/>
* Currently it replaces (based on http://en.wikipedia.org/wiki/Filename ) / slash used as a path name component separator in Unix-like, Windows,
* and Amiga systems. (The MS-DOS command.com shell would consume it as a switch character, but Windows itself always accepts it as a
* separator.[6][vague]) \ backslash Also used as a path name component separator in MS-DOS, OS/2 and Windows (where there are few differences
* between slash and backslash); allowed in Unix filenames, see Note 1 ? question mark used as a wildcard in Unix, Windows and AmigaOS; marks a
* single character. Allowed in Unix filenames, see Note 1 % percent used as a wildcard in RT-11; marks a single character. asterisk or star used
* as a wildcard in Unix, MS-DOS, RT-11, VMS and Windows. Marks any sequence of characters (Unix, Windows, later versions of MS-DOS) or any
* sequence of characters in either the basename or extension (thus "*.*" in early versions of MS-DOS means "all files". Allowed in Unix
* filenames, see note 1 : colon used to determine the mount point / drive on Windows; used to determine the virtual device or physical device
* such as a drive on AmigaOS, RT-11 and VMS; used as a pathname separator in classic Mac OS. Doubled after a name on VMS, indicates the DECnet
* nodename (equivalent to a NetBIOS (Windows networking) hostname preceded by "\\".) | vertical bar or pipe designates software pipelining in
* Unix and Windows; allowed in Unix filenames, see Note 1 " quote used to mark beginning and end of filenames containing spaces in Windows, see
* Note 1 < less than used to redirect input, allowed in Unix filenames, see Note 1 > greater than used to redirect output, allowed in Unix
* filenames, see Note 1 . period or dot
*
* @param Name
* the string that needs to be checked
* @return a name safe to create files or folders
*/
public static String MakeNameCompileSafe(String Name) {
return Name.trim().replace(" ", "_").replace("/", "_").replace("\\", "_").replace("(", "_").replace(")", "_").replace("*", "_")
.replace("?", "_").replace("%", "_").replace(".", "_").replace(":", "_").replace("|", "_").replace("<", "_").replace(">", "_")
.replace(",", "_").replace("\"", "_").replace("-", "_");
}
/**
* Gets a persistent project property
*
* @param project
* The project for which the property is needed
*
* @param Tag
* The tag identifying the property to read
* @return returns the property when found. When not found returns an empty string
*/
public static String getPersistentProperty(IProject project, String Tag) {
try {
String sret = project.getPersistentProperty(new QualifiedName(CORE_PLUGIN_ID, Tag));
if (sret == null) {
sret = project.getPersistentProperty(new QualifiedName("", Tag)); // for
// downwards
// compatibility
if (sret == null)
sret = "";
}
return sret;
} catch (CoreException e) {
log(new Status(IStatus.ERROR, ArduinoConst.CORE_PLUGIN_ID, "Failed to read persistent setting " + Tag, e));
// e.printStackTrace();
return "";
}
}
public static int getPersistentPropertyInt(IProject project, String Tag, int defaultValue) {
try {
String sret = project.getPersistentProperty(new QualifiedName(CORE_PLUGIN_ID, Tag));
if (sret == null) {
return defaultValue;
}
return Integer.parseInt(sret);
} catch (CoreException e) {
log(new Status(IStatus.ERROR, ArduinoConst.CORE_PLUGIN_ID, "Failed to read persistent setting " + Tag, e));
// e.printStackTrace();
return defaultValue;
}
}
/**
* Sets a persistent project property
*
* @param project
* The project for which the property needs to be set
*
* @param Tag
* The tag identifying the property to read
* @return returns the property when found. When not found returns an empty string
*/
public static void setPersistentProperty(IProject project, String Tag, String Value) {
try {
project.setPersistentProperty(new QualifiedName(CORE_PLUGIN_ID, Tag), Value);
project.setPersistentProperty(new QualifiedName("", Tag), Value); // for
// downwards
// compatibility
} catch (CoreException e) {
IStatus status = new Status(IStatus.ERROR, ArduinoConst.CORE_PLUGIN_ID, "Failed to write arduino properties", e);
Common.log(status);
}
}
public static void setPersistentProperty(IProject project, String Tag, int Value) {
setPersistentProperty(project, Tag, Integer.toString(Value));
}
/**
* Logs the status information
*
* @param status
* the status information to log
*/
public static void log(IStatus status) {
int style = StatusManager.LOG;
if (status.getSeverity() == IStatus.ERROR) {
style = StatusManager.LOG | StatusManager.SHOW | StatusManager.BLOCK;
StatusManager stMan = StatusManager.getManager();
stMan.handle(status, style);
} else {
Activator.getDefault().getLog().log(status);
}
}
/**
* This method returns the avrdude upload port prefix which is dependent on the platform
*
* @return avrdude upload port prefix
*/
public static String UploadPortPrefix() {
if (Platform.getOS().equals(Platform.OS_WIN32))
return UploadPortPrefix_WIN;
if (Platform.getOS().equals(Platform.OS_LINUX))
return UploadPortPrefix_LINUX;
if (Platform.getOS().equals(Platform.OS_MACOSX))
return UploadPortPrefix_MAC;
Common.log(new Status(IStatus.WARNING, ArduinoConst.CORE_PLUGIN_ID, "Unsupported operating system", null));
return UploadPortPrefix_WIN;
}
/**
* ToInt converts a string to a integer in a save way
*
* @param Number
* is a String that will be converted to an integer. Number can be null or empty and can contain leading and trailing white space
* @return The integer value represented in the string based on parseInt
* @see parseInt. After error checking and modifications parseInt is used for the conversion
**/
public static int ToInt(String Number) {
if (Number == null)
return 0;
if (Number.equals(""))
return 0;
return Integer.parseInt(Number.trim());
}
// /**
// * Converts a object to a project if it is related to a project
// *
// * @param item
// * an object that one way or anther refers to a IProject
// * @return the referred project or an iproject
// */
// public static IProject getProject(Object item) {
// // See if the given is an IProject (directly or via IAdaptable)
// if (item instanceof IProject) {
// return (IProject) item;
// } else if (item instanceof IResource) {
// return ((IResource) item).getProject();
// } else if (item instanceof IAdaptable) {
// IAdaptable adaptable = (IAdaptable) item;
// IProject project = (IProject) adaptable.getAdapter(IProject.class);
// if (project != null) {
// return project;
// }
// // Try ICProject -> IProject
// ICProject cproject = (ICProject) adaptable.getAdapter(ICProject.class);
// if (cproject == null) {
// // Try ICElement -> ICProject -> IProject
// ICElement celement = (ICElement) adaptable.getAdapter(ICElement.class);
// if (celement != null) {
// cproject = celement.getCProject();
// }
// }
// if (cproject != null) {
// return cproject.getProject();
// }
// }
// return null;
// }
private static ICConfigurationDescription[] getCfgs(IProject prj) {
ICProjectDescription prjd = CoreModel.getDefault().getProjectDescription(prj, false);
if (prjd != null) {
ICConfigurationDescription[] cfgs = prjd.getConfigurations();
if (cfgs != null) {
return cfgs;
}
}
return new ICConfigurationDescription[0];
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow();
}
public static IWorkbenchPage getActivePage() {
IWorkbenchWindow window = getActiveWorkbenchWindow();
if (window != null) {
return window.getActivePage();
}
return null;
}
/**
* Class used to efficiently special case the scenario where there's only a single project in the workspace. See bug 375760
*/
private static class ImaginarySelection implements ISelection {
private IProject fProject;
ImaginarySelection(IProject project) {
fProject = project;
}
@Override
public boolean isEmpty() {
return fProject == null;
}
IProject getProject() {
return fProject;
}
}
static HashSet<IProject> fProjects = new HashSet<IProject>();
static public IProject[] getSelectedProjects() {
fProjects.clear();
getSelectedProjects(getActiveWorkbenchWindow().getSelectionService().getSelection());
return fProjects.toArray(new IProject[fProjects.size()]);
}
static private void getSelectedProjects(ISelection selection) {
boolean badObject = false;
if (selection != null) {
if (selection instanceof IStructuredSelection) {
if (selection.isEmpty()) {
// could be a form editor or something. try to get the
// project from the active part
IWorkbenchPage page = getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part != null) {
Object o = part.getAdapter(IResource.class);
if (o != null && o instanceof IResource) {
fProjects.add(((IResource) o).getProject());
}
}
}
}
Iterator<?> iter = ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object selItem = iter.next();
IProject project = null;
if (selItem instanceof ICElement) {
ICProject cproject = ((ICElement) selItem).getCProject();
if (cproject != null)
project = cproject.getProject();
} else if (selItem instanceof IResource) {
project = ((IResource) selItem).getProject();
// } else if (selItem instanceof IncludeRefContainer) {
// ICProject fCProject =
// ((IncludeRefContainer)selItem).getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// } else if (selItem instanceof IncludeReferenceProxy)
// {
// IncludeRefContainer irc =
// ((IncludeReferenceProxy)selItem).getIncludeRefContainer();
// if (irc != null) {
// ICProject fCProject = irc.getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// }
} else if (selItem instanceof IAdaptable) {
Object adapter = ((IAdaptable) selItem).getAdapter(IProject.class);
if (adapter != null && adapter instanceof IProject) {
project = (IProject) adapter;
}
}
// Check whether the project is CDT project
if (project != null) {
if (!CoreModel.getDefault().isNewStyleProject(project))
project = null;
else {
ICConfigurationDescription[] tmp = getCfgs(project);
if (tmp.length == 0)
project = null;
}
}
if (project != null) {
fProjects.add(project);
} else {
badObject = true;
break;
}
}
} else if (selection instanceof ITextSelection) {
// If a text selection check the selected part to see if we can
// find
// an editor part that we can adapt to a resource and then
// back to a project.
IWorkbenchWindow window = getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part instanceof IEditorPart) {
IEditorPart epart = (IEditorPart) part;
IResource resource = (IResource) epart.getEditorInput().getAdapter(IResource.class);
if (resource != null) {
IProject project = resource.getProject();
badObject = !(project != null && CoreModel.getDefault().isNewStyleProject(project));
if (!badObject) {
fProjects.add(project);
}
}
}
+ // if (part instanceof IConsoleView) {
+ // IConsoleView epart = (IConsoleView) part;
+ // IProject project = epart.
+ //
+ // }
}
}
} else if (selection instanceof ImaginarySelection) {
fProjects.add(((ImaginarySelection) selection).getProject());
}
}
if (!badObject && !fProjects.isEmpty()) {
Iterator<IProject> iter = fProjects.iterator();
ICConfigurationDescription[] firstConfigs = getCfgs(iter.next());
if (firstConfigs != null) {
for (ICConfigurationDescription firstConfig : firstConfigs) {
boolean common = true;
Iterator<IProject> iter2 = fProjects.iterator();
while (iter2.hasNext()) {
ICConfigurationDescription[] currentConfigs = getCfgs(iter2.next());
int j = 0;
for (; j < currentConfigs.length; j++) {
if (firstConfig.getName().equals(currentConfigs[j].getName()))
break;
}
if (j == currentConfigs.length) {
common = false;
break;
}
}
if (common) {
break;
}
}
}
}
// action.setEnabled(enable);
// Bug 375760
// If focus is on a view that doesn't provide a resource/project
// context. Use the selection in a
// project/resource view. We support three views. If more than one is
// open, nevermind. If there's only
// one project in the workspace and it's a CDT one, use it
// unconditionally.
//
// Note that whatever project we get here is just a candidate; it's
// tested for suitability when we
// call ourselves recursively
//
if (badObject || fProjects.isEmpty()) {
// Check for lone CDT project in workspace
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (projects != null && projects.length == 1) {
IProject project = projects[0];
if (CoreModel.getDefault().isNewStyleProject(project) && (getCfgs(project).length > 0)) {
getSelectedProjects(new ImaginarySelection(project));
return;
}
}
// Check the three supported views
IWorkbenchPage page = getActivePage();
int viewCount = 0;
if (page != null) {
IViewReference theViewRef = null;
IViewReference viewRef = null;
theViewRef = page.findViewReference("org.eclipse.cdt.ui.CView"); //$NON-NLS-1$
viewCount += (theViewRef != null) ? 1 : 0;
viewRef = page.findViewReference("org.eclipse.ui.navigator.ProjectExplorer"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
viewRef = page.findViewReference("org.eclipse.ui.views.ResourceNavigator"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
- if (theViewRef != null && viewCount == 1) {
+ if (theViewRef != null && viewCount >= 1) {
IViewPart view = theViewRef.getView(false);
if (view != null) {
ISelection cdtSelection = view.getSite().getSelectionProvider().getSelection();
if (cdtSelection != null) {
if (!cdtSelection.isEmpty()) {
if (!cdtSelection.equals(selection)) { // avoids
// infinite
// recursion
getSelectedProjects(cdtSelection);
return;
}
}
}
}
}
}
}
}
public static boolean RXTXDisabled() {
return getGlobalBoolean(KEY_RXTXDISABLED);
}
public static boolean StopSerialMonitor(String mComPort) {
if (RXTXDisabled())
return false;
if (OtherSerialUser != null) {
return OtherSerialUser.PauzePort(mComPort);
}
return false;
}
public static void StartSerialMonitor(String mComPort) {
if (RXTXDisabled())
return;
if (OtherSerialUser != null) {
OtherSerialUser.ResumePort(mComPort);
}
}
public static String[] listComPorts() {
if (RXTXDisabled())
return new String[0];
Vector<String> SerialList = Serial.list();
String outgoing[] = new String[SerialList.size()];
SerialList.copyInto(outgoing);
return outgoing;
}
public static boolean LoadRXTX() {
if (RXTXLibraryLoaded)
return true;
return RXTXLibraryLoaded = LoadRXTX(null);
}
public static boolean LoadRXTX(Shell parent) {
String OsInfo = "\nOs =" + Platform.getOS() + " Os Architecture =" + Platform.getOSArch();
try {
// try to load the arduino DLL
System.load(GetSerialFullDllName());
} catch (Error e1) {
try {
// Log the Stack trace
e1.printStackTrace();
// Try to load the dll delivered with the plugin
System.loadLibrary(GetSerialDllName());
} catch (Error e2) {
String FailMessage = "Failed to load Arduino IDE delivered rxtx library (" + GetSerialFullDllName() + ") " + e1.getMessage();
FailMessage += "\nFailed to load Eclipse plugin delivered rxtx library (" + GetSerialDllName() + ") " + e2.getMessage();
FailMessage += OsInfo;
FailMessage += "\nSee Error view for more info.";
int FailErrorCode = IStatus.WARNING;
if (parent != null) {
MessageBox Failed = new MessageBox(parent, SWT.ICON_ERROR | SWT.OK);
Failed.setText("Failed to load rxtx dll!");
Failed.setMessage(FailMessage);
Failed.open();
} else {
if (!RXTXDisabled()) {
FailErrorCode = IStatus.ERROR;
}
}
Common.log(new Status(FailErrorCode, ArduinoConst.CORE_PLUGIN_ID, FailMessage, e2));
e2.printStackTrace();
return false;
}
if (parent != null) {
MessageBox SuccessBox = new MessageBox(parent, SWT.ICON_WORKING | SWT.OK);
SuccessBox.setText("Succesfully loaded rxtx dll!");
SuccessBox.setMessage("Eclipse plugin delivered rxtx library (" + GetSerialDllName() + ") has been loaded successfully" + OsInfo);
SuccessBox.open();
}
return true; // Succeeded in loading the eclipse delivered dll
}
if (parent != null) {
MessageBox SuccessBox = new MessageBox(parent, SWT.ICON_WORKING | SWT.OK);
SuccessBox.setText("Succesfully loaded rxtx dll!");
SuccessBox.setMessage("Arduino IDE delivered rxtx library (" + GetSerialFullDllName() + ") has been loaded successfully" + OsInfo);
SuccessBox.open();
}
return true; // Succeeded in loading the Arduino IDE delivered dll
}
/**
* This method reads the full dll name of the rxtxSerial.dll delivered with the Arduino IDE
*
* @return the arduino path
* @author Jan Baeyens
*/
private static String GetSerialFullDllName() {
if (Platform.getOS().equals(Platform.OS_WIN32)) {
return getArduinoPath() + "/rxtxSerial.dll";
}
if (Platform.getOS().equals(Platform.OS_LINUX)) {
if (Platform.getOSArch().equals(Platform.ARCH_IA64) || Platform.getOSArch().equals(Platform.ARCH_X86_64))
return getArduinoPath() + "/lib/librxtxSerial64.so";
return getArduinoPath() + "/lib/librxtxSerial.so";
}
if (Platform.getOS().equals(Platform.OS_MACOSX))
return getArduinoPath() + "/contents/Resources/java/LibrtxSerial.jnilib";
Common.log(new Status(IStatus.WARNING, ArduinoConst.CORE_PLUGIN_ID, "Unsupported operating system for serial functionality", null));
return getArduinoPath() + "/rxtxSerial.dll";
}
private static String GetSerialDllName() {
if (Platform.getOS().equals(Platform.OS_WIN32)) {
if (Platform.getOSArch().equals(Platform.ARCH_X86_64)) {
return "rxtxSerial64";
}
return "rxtxSerial";
}
if (Platform.getOS().equals(Platform.OS_LINUX)) {
if (Platform.getOSArch().equals(Platform.ARCH_IA64))
return "rxtxSerial";
if (Platform.getOSArch().equals(Platform.ARCH_X86))
return "rxtxSerial";
if (Platform.getOSArch().equals(Platform.ARCH_X86_64))
return "rxtxSerialx86_64";
}
if (Platform.getOS().equals(Platform.OS_MACOSX))
return "rxtxSerial";
Common.log(new Status(IStatus.WARNING, ArduinoConst.CORE_PLUGIN_ID, "Unsupported operating system for serial functionality", null));
return "rxtxSerial";
}
public static String[] listBaudRates() {
String outgoing[] = { "115200", "57600", "38400", "31250", "28800", "19200", "14400", "9600", "4800", "2400", "1200", "300" };
return outgoing;
}
public static Object listLineEndings() {
String outgoing[] = { "none", "CR", "NL", "NL/CR" };
return outgoing;
}
public static String getLineEnding(int selectionIndex) {
switch (selectionIndex) {
default:
case 0:
return "";
case 1:
return "\r";
case 2:
return "\n";
case 3:
return "\r\n";
}
}
/**
*
* Provides the build environment variable based on project and string This method does not add any knowledge.(like adding A.)
*
* @param project
* the project that contains the environment variable
* @param EnvName
* the key that describes the variable
* @param defaultvalue
* The return value if the variable is not found.
* @return
*/
static public String getBuildEnvironmentVariable(IProject project, String configName, String EnvName, String defaultvalue) {
ICProjectDescription prjDesc = CoreModel.getDefault().getProjectDescription(project);
return getBuildEnvironmentVariable(prjDesc.getConfigurationByName(configName), EnvName, defaultvalue);
}
/**
*
* Provides the build environment variable based on project and string This method does not add any knowledge.(like adding A.)
*
* @param project
* the project that contains the environment variable
* @param EnvName
* the key that describes the variable
* @param defaultvalue
* The return value if the variable is not found.
* @return
*/
static public String getBuildEnvironmentVariable(ICConfigurationDescription configurationDescription, String EnvName, String defaultvalue) {
return getBuildEnvironmentVariable(configurationDescription, EnvName, defaultvalue, true);
}
static public String getBuildEnvironmentVariable(ICConfigurationDescription configurationDescription, String EnvName, String defaultvalue,
boolean expanded) {
IEnvironmentVariableManager envManager = CCorePlugin.getDefault().getBuildEnvironmentManager();
try {
return envManager.getVariable(EnvName, configurationDescription, expanded).getValue();
} catch (Exception e) {// ignore all errors and return the default value
}
return defaultvalue;
}
static public String getArduinoIdeSuffix() {
if (Platform.getOS().equals(Platform.OS_WIN32))
return ArduinoIdeSuffix_WIN;
if (Platform.getOS().equals(Platform.OS_LINUX))
return ArduinoIdeSuffix_LINUX;
if (Platform.getOS().equals(Platform.OS_MACOSX))
return ArduinoIdeSuffix_MAC;
Common.log(new Status(IStatus.WARNING, ArduinoConst.CORE_PLUGIN_ID, "Unsupported operating system", null));
return ArduinoIdeSuffix_WIN;
}
/**
* Arduino has the default libraries in the user home directory in subfolder Arduino/libraries. As the home directory is platform dependent
* getting the value is resolved by this method
*
* @return the folder where Arduino puts the libraries by default.
*/
public static String getDefaultPrivateLibraryPath() {
IPath homPath = new Path(System.getProperty("user.home"));
return homPath.append("Arduino").append("libraries").toString();
}
/**
* same as getDefaultLibPath but for the hardware folder
*
* @return
*/
public static String getDefaultPrivateHardwarePath() {
IPath homPath = new Path(System.getProperty("user.home"));
return homPath.append("Arduino").append("hardware").toString();
}
}
| false | true | static private void getSelectedProjects(ISelection selection) {
boolean badObject = false;
if (selection != null) {
if (selection instanceof IStructuredSelection) {
if (selection.isEmpty()) {
// could be a form editor or something. try to get the
// project from the active part
IWorkbenchPage page = getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part != null) {
Object o = part.getAdapter(IResource.class);
if (o != null && o instanceof IResource) {
fProjects.add(((IResource) o).getProject());
}
}
}
}
Iterator<?> iter = ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object selItem = iter.next();
IProject project = null;
if (selItem instanceof ICElement) {
ICProject cproject = ((ICElement) selItem).getCProject();
if (cproject != null)
project = cproject.getProject();
} else if (selItem instanceof IResource) {
project = ((IResource) selItem).getProject();
// } else if (selItem instanceof IncludeRefContainer) {
// ICProject fCProject =
// ((IncludeRefContainer)selItem).getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// } else if (selItem instanceof IncludeReferenceProxy)
// {
// IncludeRefContainer irc =
// ((IncludeReferenceProxy)selItem).getIncludeRefContainer();
// if (irc != null) {
// ICProject fCProject = irc.getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// }
} else if (selItem instanceof IAdaptable) {
Object adapter = ((IAdaptable) selItem).getAdapter(IProject.class);
if (adapter != null && adapter instanceof IProject) {
project = (IProject) adapter;
}
}
// Check whether the project is CDT project
if (project != null) {
if (!CoreModel.getDefault().isNewStyleProject(project))
project = null;
else {
ICConfigurationDescription[] tmp = getCfgs(project);
if (tmp.length == 0)
project = null;
}
}
if (project != null) {
fProjects.add(project);
} else {
badObject = true;
break;
}
}
} else if (selection instanceof ITextSelection) {
// If a text selection check the selected part to see if we can
// find
// an editor part that we can adapt to a resource and then
// back to a project.
IWorkbenchWindow window = getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part instanceof IEditorPart) {
IEditorPart epart = (IEditorPart) part;
IResource resource = (IResource) epart.getEditorInput().getAdapter(IResource.class);
if (resource != null) {
IProject project = resource.getProject();
badObject = !(project != null && CoreModel.getDefault().isNewStyleProject(project));
if (!badObject) {
fProjects.add(project);
}
}
}
}
}
} else if (selection instanceof ImaginarySelection) {
fProjects.add(((ImaginarySelection) selection).getProject());
}
}
if (!badObject && !fProjects.isEmpty()) {
Iterator<IProject> iter = fProjects.iterator();
ICConfigurationDescription[] firstConfigs = getCfgs(iter.next());
if (firstConfigs != null) {
for (ICConfigurationDescription firstConfig : firstConfigs) {
boolean common = true;
Iterator<IProject> iter2 = fProjects.iterator();
while (iter2.hasNext()) {
ICConfigurationDescription[] currentConfigs = getCfgs(iter2.next());
int j = 0;
for (; j < currentConfigs.length; j++) {
if (firstConfig.getName().equals(currentConfigs[j].getName()))
break;
}
if (j == currentConfigs.length) {
common = false;
break;
}
}
if (common) {
break;
}
}
}
}
// action.setEnabled(enable);
// Bug 375760
// If focus is on a view that doesn't provide a resource/project
// context. Use the selection in a
// project/resource view. We support three views. If more than one is
// open, nevermind. If there's only
// one project in the workspace and it's a CDT one, use it
// unconditionally.
//
// Note that whatever project we get here is just a candidate; it's
// tested for suitability when we
// call ourselves recursively
//
if (badObject || fProjects.isEmpty()) {
// Check for lone CDT project in workspace
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (projects != null && projects.length == 1) {
IProject project = projects[0];
if (CoreModel.getDefault().isNewStyleProject(project) && (getCfgs(project).length > 0)) {
getSelectedProjects(new ImaginarySelection(project));
return;
}
}
// Check the three supported views
IWorkbenchPage page = getActivePage();
int viewCount = 0;
if (page != null) {
IViewReference theViewRef = null;
IViewReference viewRef = null;
theViewRef = page.findViewReference("org.eclipse.cdt.ui.CView"); //$NON-NLS-1$
viewCount += (theViewRef != null) ? 1 : 0;
viewRef = page.findViewReference("org.eclipse.ui.navigator.ProjectExplorer"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
viewRef = page.findViewReference("org.eclipse.ui.views.ResourceNavigator"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
if (theViewRef != null && viewCount == 1) {
IViewPart view = theViewRef.getView(false);
if (view != null) {
ISelection cdtSelection = view.getSite().getSelectionProvider().getSelection();
if (cdtSelection != null) {
if (!cdtSelection.isEmpty()) {
if (!cdtSelection.equals(selection)) { // avoids
// infinite
// recursion
getSelectedProjects(cdtSelection);
return;
}
}
}
}
}
}
}
}
| static private void getSelectedProjects(ISelection selection) {
boolean badObject = false;
if (selection != null) {
if (selection instanceof IStructuredSelection) {
if (selection.isEmpty()) {
// could be a form editor or something. try to get the
// project from the active part
IWorkbenchPage page = getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part != null) {
Object o = part.getAdapter(IResource.class);
if (o != null && o instanceof IResource) {
fProjects.add(((IResource) o).getProject());
}
}
}
}
Iterator<?> iter = ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object selItem = iter.next();
IProject project = null;
if (selItem instanceof ICElement) {
ICProject cproject = ((ICElement) selItem).getCProject();
if (cproject != null)
project = cproject.getProject();
} else if (selItem instanceof IResource) {
project = ((IResource) selItem).getProject();
// } else if (selItem instanceof IncludeRefContainer) {
// ICProject fCProject =
// ((IncludeRefContainer)selItem).getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// } else if (selItem instanceof IncludeReferenceProxy)
// {
// IncludeRefContainer irc =
// ((IncludeReferenceProxy)selItem).getIncludeRefContainer();
// if (irc != null) {
// ICProject fCProject = irc.getCProject();
// if (fCProject != null)
// project = fCProject.getProject();
// }
} else if (selItem instanceof IAdaptable) {
Object adapter = ((IAdaptable) selItem).getAdapter(IProject.class);
if (adapter != null && adapter instanceof IProject) {
project = (IProject) adapter;
}
}
// Check whether the project is CDT project
if (project != null) {
if (!CoreModel.getDefault().isNewStyleProject(project))
project = null;
else {
ICConfigurationDescription[] tmp = getCfgs(project);
if (tmp.length == 0)
project = null;
}
}
if (project != null) {
fProjects.add(project);
} else {
badObject = true;
break;
}
}
} else if (selection instanceof ITextSelection) {
// If a text selection check the selected part to see if we can
// find
// an editor part that we can adapt to a resource and then
// back to a project.
IWorkbenchWindow window = getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IWorkbenchPart part = page.getActivePart();
if (part instanceof IEditorPart) {
IEditorPart epart = (IEditorPart) part;
IResource resource = (IResource) epart.getEditorInput().getAdapter(IResource.class);
if (resource != null) {
IProject project = resource.getProject();
badObject = !(project != null && CoreModel.getDefault().isNewStyleProject(project));
if (!badObject) {
fProjects.add(project);
}
}
}
// if (part instanceof IConsoleView) {
// IConsoleView epart = (IConsoleView) part;
// IProject project = epart.
//
// }
}
}
} else if (selection instanceof ImaginarySelection) {
fProjects.add(((ImaginarySelection) selection).getProject());
}
}
if (!badObject && !fProjects.isEmpty()) {
Iterator<IProject> iter = fProjects.iterator();
ICConfigurationDescription[] firstConfigs = getCfgs(iter.next());
if (firstConfigs != null) {
for (ICConfigurationDescription firstConfig : firstConfigs) {
boolean common = true;
Iterator<IProject> iter2 = fProjects.iterator();
while (iter2.hasNext()) {
ICConfigurationDescription[] currentConfigs = getCfgs(iter2.next());
int j = 0;
for (; j < currentConfigs.length; j++) {
if (firstConfig.getName().equals(currentConfigs[j].getName()))
break;
}
if (j == currentConfigs.length) {
common = false;
break;
}
}
if (common) {
break;
}
}
}
}
// action.setEnabled(enable);
// Bug 375760
// If focus is on a view that doesn't provide a resource/project
// context. Use the selection in a
// project/resource view. We support three views. If more than one is
// open, nevermind. If there's only
// one project in the workspace and it's a CDT one, use it
// unconditionally.
//
// Note that whatever project we get here is just a candidate; it's
// tested for suitability when we
// call ourselves recursively
//
if (badObject || fProjects.isEmpty()) {
// Check for lone CDT project in workspace
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (projects != null && projects.length == 1) {
IProject project = projects[0];
if (CoreModel.getDefault().isNewStyleProject(project) && (getCfgs(project).length > 0)) {
getSelectedProjects(new ImaginarySelection(project));
return;
}
}
// Check the three supported views
IWorkbenchPage page = getActivePage();
int viewCount = 0;
if (page != null) {
IViewReference theViewRef = null;
IViewReference viewRef = null;
theViewRef = page.findViewReference("org.eclipse.cdt.ui.CView"); //$NON-NLS-1$
viewCount += (theViewRef != null) ? 1 : 0;
viewRef = page.findViewReference("org.eclipse.ui.navigator.ProjectExplorer"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
viewRef = page.findViewReference("org.eclipse.ui.views.ResourceNavigator"); //$NON-NLS-1$
viewCount += (viewRef != null) ? 1 : 0;
theViewRef = (theViewRef == null) ? viewRef : theViewRef;
if (theViewRef != null && viewCount >= 1) {
IViewPart view = theViewRef.getView(false);
if (view != null) {
ISelection cdtSelection = view.getSite().getSelectionProvider().getSelection();
if (cdtSelection != null) {
if (!cdtSelection.isEmpty()) {
if (!cdtSelection.equals(selection)) { // avoids
// infinite
// recursion
getSelectedProjects(cdtSelection);
return;
}
}
}
}
}
}
}
}
|
diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/referencepillar/DeleteFileOnReferencePillarTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/referencepillar/DeleteFileOnReferencePillarTest.java
index 71d5596a..68f1adf9 100644
--- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/referencepillar/DeleteFileOnReferencePillarTest.java
+++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/referencepillar/DeleteFileOnReferencePillarTest.java
@@ -1,184 +1,183 @@
/*
* #%L
* Bitrepository Reference Pillar
*
* $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $
* $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $
* %%
* Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.bitrepository.pillar.referencepillar;
import org.bitrepository.bitrepositoryelements.AlarmCode;
import org.bitrepository.bitrepositoryelements.ResponseCode;
import org.bitrepository.bitrepositorymessages.AlarmMessage;
import org.bitrepository.bitrepositorymessages.DeleteFileFinalResponse;
import org.bitrepository.bitrepositorymessages.DeleteFileProgressResponse;
import org.bitrepository.bitrepositorymessages.DeleteFileRequest;
import org.bitrepository.bitrepositorymessages.IdentifyPillarsForDeleteFileRequest;
import org.bitrepository.bitrepositorymessages.IdentifyPillarsForDeleteFileResponse;
import org.bitrepository.common.utils.TestFileHelper;
import org.bitrepository.pillar.messagefactories.DeleteFileMessageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Tests the PutFile functionality on the ReferencePillar.
*/
public class DeleteFileOnReferencePillarTest extends ReferencePillarTest {
private DeleteFileMessageFactory msgFactory;
@Override
public void initializeCUT() {
super.initializeCUT();
msgFactory = new DeleteFileMessageFactory(collectionID, settingsForTestClient, getPillarID(),
pillarDestinationId);
}
@Test( groups = {"regressiontest", "pillartest"})
public void pillarDeleteFileTestSuccessTest() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for the successful scenario.");
addStep("Set up constants and variables.", "Should not fail here!");
addStep("Create and send the identify request message.",
"Should be received and handled by the pillar.");
IdentifyPillarsForDeleteFileRequest identifyRequest =
msgFactory.createIdentifyPillarsForDeleteFileRequest(DEFAULT_FILE_ID);
messageBus.sendMessage(identifyRequest);
addStep("Retrieve and validate the response getPillarID() the pillar.",
"The pillar should make a response.");
IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage(
IdentifyPillarsForDeleteFileResponse.class);
Assert.assertNotNull(receivedIdentifyResponse);
Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID());
Assert.assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(),
ResponseCode.IDENTIFICATION_POSITIVE);
addStep("Create and send the actual DeleteFile message to the pillar.",
"Should be received and handled by the pillar.");
DeleteFileRequest deleteFileRequest =
msgFactory.createDeleteFileRequest(EMPTY_FILE_CHECKSUM_DATA, null, DEFAULT_FILE_ID);
messageBus.sendMessage(deleteFileRequest);
addStep("Retrieve the ProgressResponse for the DeleteFile request",
"The DeleteFile progress response should be sent by the pillar.");
DeleteFileProgressResponse progressResponse = clientReceiver.waitForMessage(DeleteFileProgressResponse.class);
Assert.assertNotNull(progressResponse);
Assert.assertEquals(progressResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(progressResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(progressResponse.getFrom(), getPillarID());
Assert.assertEquals(progressResponse.getPillarID(), getPillarID());
Assert.assertEquals(progressResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_ACCEPTED_PROGRESS);
addStep("Retrieve the FinalResponse for the DeleteFile request",
"The DeleteFile response should be sent by the pillar.");
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED);
Assert.assertNotNull(finalResponse);
Assert.assertEquals(finalResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(finalResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(finalResponse.getFrom(), getPillarID());
Assert.assertEquals(finalResponse.getPillarID(), getPillarID());
Assert.assertEquals(finalResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_COMPLETED);
alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class);
- Assert.assertEquals(audits.getCallsForAuditEvent(), 2, "Should deliver 2 audits. " +
- "One for delete and 1 for calculate checksums.");
+ Assert.assertEquals(audits.getCallsForAuditEvent(), 1, "Should create 1 audit for the delete operation.");
}
@Test( groups = {"regressiontest", "pillartest"})
public void pillarDeleteFileTestFailedNoSuchFile() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for the scenario " +
"when the file does not exist FILE_NOT_FOUND_FAILURE response.");
addStep("Send a IdentifyPillarsForDeleteFileRequest with a fileID for a non-existing file.",
"Should generate a FILE_NOT_FOUND_FAILURE identification response.");
messageBus.sendMessage(msgFactory.createIdentifyPillarsForDeleteFileRequest(NON_DEFAULT_FILE_ID));
IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage(
IdentifyPillarsForDeleteFileResponse.class);
Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(),
ResponseCode.FILE_NOT_FOUND_FAILURE);
}
@Test( groups = {"regressiontest", "pillartest"})
public void pillarDeleteFileTestFailedNoSuchFileInOperation() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for the scenario " +
"when the file does not exist.");
addStep("Send a DeleteFileRequest with a fileID for a non-existing file.",
"Should generate a FILE_NOT_FOUND_FAILURE response.");
messageBus.sendMessage(msgFactory.createDeleteFileRequest(
TestFileHelper.getDefaultFileChecksum(), null, NON_DEFAULT_FILE_ID));
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.FILE_NOT_FOUND_FAILURE);
}
@Test( groups = {"regressiontest", "pillartest"})
public void pillarDeleteFileTestFailedWrongChecksum() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for scenario when a wrong "
+ "checksum is given as argument.");
addStep("Send a DeleteFileRequest with a invalid checksum for the initial file.",
"Should cause a EXISTING_FILE_CHECKSUM_FAILURE response to be sent and a .");
DeleteFileRequest deleteFileRequest =
msgFactory.createDeleteFileRequest(TestFileHelper.getDefaultFileChecksum(), null, DEFAULT_FILE_ID);
messageBus.sendMessage(deleteFileRequest);
addStep("Retrieve the FinalResponse for the DeleteFile request",
"The DeleteFile faled response should be sent by the pillar and a alarm should be generated.");
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE);
Assert.assertEquals(alarmReceiver.waitForMessage(AlarmMessage.class).getAlarm().getAlarmCode(),
AlarmCode.CHECKSUM_ALARM);
}
@Test( groups = {"regressiontest", "pillartest"})
public void checksumPillarDeleteFileTestMissingChecksumArgument() throws Exception {
addDescription("Tests that a missing 'ChecksumOnExistingFile' will not delete the file.");
Assert.assertTrue(context.getSettings().getRepositorySettings().getProtocolSettings().isRequireChecksumForDestructiveRequests());
messageBus.sendMessage(msgFactory.createDeleteFileRequest(null, null, DEFAULT_FILE_ID));
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(),
ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE);
Assert.assertTrue(archives.hasFile(DEFAULT_FILE_ID, collectionID));
}
@Test( groups = {"regressiontest", "pillartest"})
public void checksumPillarDeleteFileTestAllowedMissingChecksum() throws Exception {
addDescription("Tests that a missing 'ChecksumOnExistingFile' will delete the file, when it has been allowed "
+ "to perform destructive operations in the settings.");
context.getSettings().getRepositorySettings().getProtocolSettings().setRequireChecksumForDestructiveRequests(false);
Assert.assertFalse(context.getSettings().getRepositorySettings().getProtocolSettings().isRequireChecksumForDestructiveRequests());
messageBus.sendMessage(msgFactory.createDeleteFileRequest(null, null, DEFAULT_FILE_ID));
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_COMPLETED);
Assert.assertFalse(archives.hasFile(DEFAULT_FILE_ID, collectionID));
}
}
| true | true | public void pillarDeleteFileTestSuccessTest() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for the successful scenario.");
addStep("Set up constants and variables.", "Should not fail here!");
addStep("Create and send the identify request message.",
"Should be received and handled by the pillar.");
IdentifyPillarsForDeleteFileRequest identifyRequest =
msgFactory.createIdentifyPillarsForDeleteFileRequest(DEFAULT_FILE_ID);
messageBus.sendMessage(identifyRequest);
addStep("Retrieve and validate the response getPillarID() the pillar.",
"The pillar should make a response.");
IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage(
IdentifyPillarsForDeleteFileResponse.class);
Assert.assertNotNull(receivedIdentifyResponse);
Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID());
Assert.assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(),
ResponseCode.IDENTIFICATION_POSITIVE);
addStep("Create and send the actual DeleteFile message to the pillar.",
"Should be received and handled by the pillar.");
DeleteFileRequest deleteFileRequest =
msgFactory.createDeleteFileRequest(EMPTY_FILE_CHECKSUM_DATA, null, DEFAULT_FILE_ID);
messageBus.sendMessage(deleteFileRequest);
addStep("Retrieve the ProgressResponse for the DeleteFile request",
"The DeleteFile progress response should be sent by the pillar.");
DeleteFileProgressResponse progressResponse = clientReceiver.waitForMessage(DeleteFileProgressResponse.class);
Assert.assertNotNull(progressResponse);
Assert.assertEquals(progressResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(progressResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(progressResponse.getFrom(), getPillarID());
Assert.assertEquals(progressResponse.getPillarID(), getPillarID());
Assert.assertEquals(progressResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_ACCEPTED_PROGRESS);
addStep("Retrieve the FinalResponse for the DeleteFile request",
"The DeleteFile response should be sent by the pillar.");
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED);
Assert.assertNotNull(finalResponse);
Assert.assertEquals(finalResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(finalResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(finalResponse.getFrom(), getPillarID());
Assert.assertEquals(finalResponse.getPillarID(), getPillarID());
Assert.assertEquals(finalResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_COMPLETED);
alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class);
Assert.assertEquals(audits.getCallsForAuditEvent(), 2, "Should deliver 2 audits. " +
"One for delete and 1 for calculate checksums.");
}
| public void pillarDeleteFileTestSuccessTest() throws Exception {
addDescription("Tests the DeleteFile functionality of the reference pillar for the successful scenario.");
addStep("Set up constants and variables.", "Should not fail here!");
addStep("Create and send the identify request message.",
"Should be received and handled by the pillar.");
IdentifyPillarsForDeleteFileRequest identifyRequest =
msgFactory.createIdentifyPillarsForDeleteFileRequest(DEFAULT_FILE_ID);
messageBus.sendMessage(identifyRequest);
addStep("Retrieve and validate the response getPillarID() the pillar.",
"The pillar should make a response.");
IdentifyPillarsForDeleteFileResponse receivedIdentifyResponse = clientReceiver.waitForMessage(
IdentifyPillarsForDeleteFileResponse.class);
Assert.assertNotNull(receivedIdentifyResponse);
Assert.assertEquals(receivedIdentifyResponse.getCorrelationID(), identifyRequest.getCorrelationID());
Assert.assertEquals(receivedIdentifyResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(receivedIdentifyResponse.getFrom(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getPillarID(), getPillarID());
Assert.assertEquals(receivedIdentifyResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(receivedIdentifyResponse.getResponseInfo().getResponseCode(),
ResponseCode.IDENTIFICATION_POSITIVE);
addStep("Create and send the actual DeleteFile message to the pillar.",
"Should be received and handled by the pillar.");
DeleteFileRequest deleteFileRequest =
msgFactory.createDeleteFileRequest(EMPTY_FILE_CHECKSUM_DATA, null, DEFAULT_FILE_ID);
messageBus.sendMessage(deleteFileRequest);
addStep("Retrieve the ProgressResponse for the DeleteFile request",
"The DeleteFile progress response should be sent by the pillar.");
DeleteFileProgressResponse progressResponse = clientReceiver.waitForMessage(DeleteFileProgressResponse.class);
Assert.assertNotNull(progressResponse);
Assert.assertEquals(progressResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(progressResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(progressResponse.getFrom(), getPillarID());
Assert.assertEquals(progressResponse.getPillarID(), getPillarID());
Assert.assertEquals(progressResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(progressResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_ACCEPTED_PROGRESS);
addStep("Retrieve the FinalResponse for the DeleteFile request",
"The DeleteFile response should be sent by the pillar.");
DeleteFileFinalResponse finalResponse = clientReceiver.waitForMessage(DeleteFileFinalResponse.class);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(), ResponseCode.OPERATION_COMPLETED);
Assert.assertNotNull(finalResponse);
Assert.assertEquals(finalResponse.getCorrelationID(), deleteFileRequest.getCorrelationID());
Assert.assertEquals(finalResponse.getFileID(), DEFAULT_FILE_ID);
Assert.assertEquals(finalResponse.getFrom(), getPillarID());
Assert.assertEquals(finalResponse.getPillarID(), getPillarID());
Assert.assertEquals(finalResponse.getReplyTo(), pillarDestinationId);
Assert.assertEquals(finalResponse.getResponseInfo().getResponseCode(),
ResponseCode.OPERATION_COMPLETED);
alarmReceiver.checkNoMessageIsReceived(AlarmMessage.class);
Assert.assertEquals(audits.getCallsForAuditEvent(), 1, "Should create 1 audit for the delete operation.");
}
|
diff --git a/game/utils/FileSaver.java b/game/utils/FileSaver.java
index 7e4778f..fb97606 100644
--- a/game/utils/FileSaver.java
+++ b/game/utils/FileSaver.java
@@ -1,368 +1,370 @@
package game.utils;
import game.Game;
import game.Map;
import game.entity.Entity;
import game.entity.SerialEntity;
import game.tile.Tile;
import game.triggers.SerialTrigger;
import game.triggers.Trigger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
public class FileSaver {
/* public static ByteBuffer loadPNGTexture(String path)
{
try{
ByteBuffer buf = null;
int tWidth = 0,
tHeight = 0;
InputStream in = new FileInputStream(FileSaver.getCleanPath()+"//res//tiles.png");
PNGDecoder decoder = new PNGDecoder(in);
tWidth = decoder.getWidth();
tHeight = decoder.getHeight();
buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());
decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA);
buf.flip();
in.close();
return buf;
}catch(Exception e)
{
e.printStackTrace();
return null;
}
}*/
public static void saveMapFile(Map map, String path)
{
PrintWriter out;
try {
Game.log("Saving map file " + path);
out = new PrintWriter(path);
//SAVE MISC INFO
out.println("NAME "+map.name);
out.println("VERSION "+map.version);
out.println("DESC "+map.desc);
out.println("LOCKED "+map.isLocked);
out.println("LEVEL "+map.isLevel);
//SAVE TILES
out.println("TILES");
for(int x = 0; x < map.tiles.length; x++)
{
for(int y = 0; y < map.tiles[x].length; y++)
{
out.println(x+" "+y+" "+Tile.getTileID(map.tiles[x][y]));
}
}
out.println("END");
out.println("ENTITIES");
for(SerialEntity e : map.entities)
{
out.println(e.x+" "+e.y+" "+e.health+" "+e.relatedEntity);
}
out.println("END");
out.println("TRIGGERS");
for(Trigger t : map.triggers)
{
out.println(t.x+" "+t.y+" "+t.getClass().getCanonicalName()+" "+t.lx+" "+t.ly);
}
out.println("END");
out.checkError();
out.close();
} catch (Exception e) {
Game.log("Map saving did an uh oh at:");
e.printStackTrace();
}
}
public static Map loadMapFile(String path)
{
int readMode = 0;
Map map = new Map();
BufferedReader br;
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
if (!(line.charAt(0) == "#".charAt(0))) {
String args[] = line.split(" ");
if(readMode == 0)
{
if(args[0].equals("NAME"))map.name = args[1];
if(args[0].equals("VERSION"))map.version = args[1];
if(args[0].equals("DESC"))map.desc = args[1];
+ if(args[0].equals("LOCKED"))map.isLocked = Boolean.getBoolean(args[1]);
+ if(args[0].equals("LEVEL"))map.isLevel = Boolean.getBoolean(args[1]);
if(args[0].equals("TILES"))readMode = 1;
if(args[0].equals("ENTITIES"))readMode = 2;
if(args[0].equals("TRIGGERS"))readMode = 3;
}else if(readMode > 0)
{
if(args[0].equals("END"))readMode = 0;
if(readMode == 1)
{
map.tiles[Integer.parseInt(args[0])][Integer.parseInt(args[1])] = Tile.tiles[Integer.parseInt(args[2])];
}
if(readMode == 2)
{
map.entities.add(new SerialEntity(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]), args[3]));
}
if(readMode == 3)
{
map.triggers.add(new Trigger());
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
/**
* Used for map loading to retrieve entity instances from the map file.
* @param entlist The list of serial entities supplied by the map file
* @param game The game instance
* @return A list of entity instances
* @throws ClassNotFoundException If entity list is invalid
* @throws InstantiationException If entity list is invalid
* @throws IllegalAccessException If entity list is invalid
*/
public static ArrayList<Entity> serialToEntity(
ArrayList<SerialEntity> entlist, Game game)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
System.out.println("Deserializing entity array...");
System.out.println(entlist.size() + " entities to deserialize.");
ArrayList<Entity> newlist = new ArrayList<Entity>();
for (SerialEntity se : entlist) {
System.out.println("Deserialized entity " + se.relatedEntity);
Class<?> c = Class.forName(se.relatedEntity);
Entity dummyentity = (Entity) c.newInstance();
dummyentity.x = se.x;
dummyentity.y = se.y;
dummyentity.game = game;
newlist.add(dummyentity);
}
return newlist;
}
/**
* Used for map saving to convert entities to saveable versions
* @param entlist A list of entities supplied by the Map instance
* @return A list of saveable entities
*/
public static ArrayList<SerialEntity> entityToSerial(
ArrayList<Entity> entlist) {
System.out.println("Serializing entity array...");
System.out.println(entlist.size() + " entities to serialize.");
ArrayList<SerialEntity> newlist = new ArrayList<SerialEntity>();
for (Entity e : entlist) {
System.out.println("Serialized entity "
+ e.getClass().getCanonicalName());
newlist.add(new SerialEntity(e.x, e.y, 0, e.getClass()
.getCanonicalName()));
}
return newlist;
}
public static ArrayList<SerialTrigger> triggerToSerial(ArrayList<Trigger> triggers)
{
ArrayList<SerialTrigger> retrn = new ArrayList<SerialTrigger>();
for(Trigger t : triggers)
{
boolean newTrigger = true;
//Take the first trigger and see if its been serialized allready
for(SerialTrigger st : retrn)
{
if(st.x == t.x && st.y == t.y && st.relatedTrigger == t.getClass().getCanonicalName())
{
//Must be the same trigger, break
System.out.println("Found already serialized trigger "+t.getClass().getCanonicalName());
newTrigger = false;
break;
}
}
if(newTrigger)
{
System.out.println("Trigger is still fresh... finding chain...");
//If the trigger is still fresh
SerialTrigger newSerial = new SerialTrigger(t.x, t.y,null, t.getClass().getCanonicalName());
//Now we need to serialize the related trigger
Trigger relatedTrigger = t.linkedTrigger;
System.out.println("-Chain start at "+relatedTrigger);
while(relatedTrigger != null)
{
System.out.println("|Trigger Element "+relatedTrigger.linkedTrigger);
//While we are still in the chain
relatedTrigger = relatedTrigger.linkedTrigger;
}
System.out.println("-Chain end at "+relatedTrigger);
}
}
return retrn;
}
/**
* Used by the crash screen to the stack trace
* @param aThrowable The throwable error
* @return The stacktrace
*/
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/**
* Saves all the properties in the hashmap props into a file like this:
* Key: Value
* @param props The hashmap to save to a file.
* @param path The path to save at.
*/
public static void savePropertiesFile(HashMap<String, String> props,
String path) {
PrintWriter out;
try {
Game.log("Saving property file " + path);
out = new PrintWriter(path);
out.println("#" + Game.TITLE + " Property File. ");
for (int i = 0; i < props.keySet().size(); i++) {
String property = props.keySet().toArray()[i] + "";
String value = props.get(property);
out.println(property + ": " + value);
}
out.checkError();
out.close();
} catch (Exception e) {
Game.log("File saving did an uh oh at:");
e.printStackTrace();
}
}
/**
* Used for reading property files
* @param path Path to read from
* @return Hashmap form of property file
*/
public static HashMap<String, String> readPropertiesFile(String path) {
HashMap<String, String> props = new HashMap<String, String>();
BufferedReader br;
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
if (!(line.charAt(0) == "#".charAt(0))) {
String[] properties = line.split(": ");
props.put(properties[0], properties[1]);
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
/**
* Basic file saver
* @param file File to save
* @param path Path to save at
*/
public static void save(Object file, String path) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
Game.log("Saving file " + path);
fos = new FileOutputStream(path);
oos = new ObjectOutputStream(fos);
oos.reset();
oos.writeObject(file);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
new File(path).mkdir();
save(file, path);
} catch (Exception e) {
e.printStackTrace();
}
Game.log("Done!");
}
/**
* Basic file loader
* @param path Path to load from
* @return Object returned
*/
public static Object load(String path) {
try {
Game.log("Loading file " + path);
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Gets working directory
* @return Working directory
*/
public static String getCleanPath() {
return new File(FileSaver.class.getProtectionDomain().getCodeSource()
.getLocation().getPath()).getAbsolutePath();
}
}
| true | true | public static Map loadMapFile(String path)
{
int readMode = 0;
Map map = new Map();
BufferedReader br;
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
if (!(line.charAt(0) == "#".charAt(0))) {
String args[] = line.split(" ");
if(readMode == 0)
{
if(args[0].equals("NAME"))map.name = args[1];
if(args[0].equals("VERSION"))map.version = args[1];
if(args[0].equals("DESC"))map.desc = args[1];
if(args[0].equals("TILES"))readMode = 1;
if(args[0].equals("ENTITIES"))readMode = 2;
if(args[0].equals("TRIGGERS"))readMode = 3;
}else if(readMode > 0)
{
if(args[0].equals("END"))readMode = 0;
if(readMode == 1)
{
map.tiles[Integer.parseInt(args[0])][Integer.parseInt(args[1])] = Tile.tiles[Integer.parseInt(args[2])];
}
if(readMode == 2)
{
map.entities.add(new SerialEntity(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]), args[3]));
}
if(readMode == 3)
{
map.triggers.add(new Trigger());
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
| public static Map loadMapFile(String path)
{
int readMode = 0;
Map map = new Map();
BufferedReader br;
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
if (!(line.charAt(0) == "#".charAt(0))) {
String args[] = line.split(" ");
if(readMode == 0)
{
if(args[0].equals("NAME"))map.name = args[1];
if(args[0].equals("VERSION"))map.version = args[1];
if(args[0].equals("DESC"))map.desc = args[1];
if(args[0].equals("LOCKED"))map.isLocked = Boolean.getBoolean(args[1]);
if(args[0].equals("LEVEL"))map.isLevel = Boolean.getBoolean(args[1]);
if(args[0].equals("TILES"))readMode = 1;
if(args[0].equals("ENTITIES"))readMode = 2;
if(args[0].equals("TRIGGERS"))readMode = 3;
}else if(readMode > 0)
{
if(args[0].equals("END"))readMode = 0;
if(readMode == 1)
{
map.tiles[Integer.parseInt(args[0])][Integer.parseInt(args[1])] = Tile.tiles[Integer.parseInt(args[2])];
}
if(readMode == 2)
{
map.entities.add(new SerialEntity(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]), args[3]));
}
if(readMode == 3)
{
map.triggers.add(new Trigger());
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
|
diff --git a/src/mitzi/MitziBrain.java b/src/mitzi/MitziBrain.java
index e140906..2ce13e8 100644
--- a/src/mitzi/MitziBrain.java
+++ b/src/mitzi/MitziBrain.java
@@ -1,518 +1,518 @@
package mitzi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static mitzi.MateScores.*;
import mitzi.UCIReporter.InfoType;
/**
* This class implements the AI of Mitzi. The best move is found using the
* negamax algorithms with Transposition tables. The class regularly sends
* information about the current search, including nodes per second ("nps"), the
* filling of the Transposition Table ("hashfull") and the current searched move
* on top-level. The board evaluation is moved to a separate class
* BoardAnalyzer.
*
*/
public class MitziBrain implements IBrain {
/**
* maximal number of threads
*/
private static final int THREAD_POOL_SIZE = 1;
/**
* unit for time management
*/
private static final TimeUnit THREAD_TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
/**
* timeout for thread shutdown
*/
private static final int THREAD_TIMEOUT = 1000;
/**
* upper limit for evaluation time
*/
private int maxEvalTime;
/**
* the currently best result
*/
private AnalysisResult result;
/**
* the executor for the tasks
*/
private ExecutorService exe;
/**
* the current game state
*/
private GameState game_state;
private class PositionEvaluator implements Runnable {
private final IPosition position;
private final int searchDepth;
public PositionEvaluator(final IPosition position, final int depth) {
this.position = position;
this.searchDepth = depth;
}
@Override
public void run() {
try {
// Parameters for aspiration windows
int alpha = NEG_INF; // initial value
int beta = POS_INF; // initial value
int asp_window = 25; // often 50 or 25 is used
int factor = 2; // factor for increasing if out of bounds
// iterative deepening
for (int current_depth = 1; current_depth <= searchDepth; current_depth++) {
table_counter = 0;
BoardAnalyzer.table_counter = 0;
result = negaMax(position, current_depth, current_depth,
alpha, beta);
position.updateAnalysisResult(result);
if (result.score == POS_INF || result.score == NEG_INF) {
break;
}
// If Value is out of bounds, redo search with larger
// bounds, but with the same variation tree
if (result.score <= alpha) {
alpha -= factor * asp_window;
current_depth--;
UCIReporter
.sendInfoString("Boards found: "
+ (table_counter + BoardAnalyzer.table_counter));
continue;
} else if (result.score >= beta) {
beta += factor * asp_window;
current_depth--;
UCIReporter
.sendInfoString("Boards found: "
+ (table_counter + BoardAnalyzer.table_counter));
continue;
}
alpha = result.score - asp_window;
beta = result.score + asp_window;
UCIReporter.sendInfoString("Boards found: "
+ (table_counter + BoardAnalyzer.table_counter));
}
} catch (InterruptedException e) {
}
}
@Override
public String toString() {
return position.toString();
}
}
/**
* counts the number of evaluated board
*/
private long eval_counter;
/**
* counts the number of found boards in the transposition table.
*/
private long table_counter;
/**
* the board analyzer for board evaluation
*/
private IPositionAnalyzer board_analyzer = new BoardAnalyzer();
/**
* the current time.
*/
private long start_mtime = System.currentTimeMillis();
private Timer timer;
@Override
public void set(GameState game_state) {
this.game_state = game_state;
this.eval_counter = 0;
this.table_counter = 0;
}
/**
* @return the time, which passes since start_mtime
*/
private long runTime() {
return System.currentTimeMillis() - start_mtime;
}
/**
* Sends updates about evaluation status to UCI GUI, namely the number of
* searched board per second and the size of the Transposition Table in
* permill of the maximal size.
*
*/
class UCIUpdater extends TimerTask {
private long old_mtime;
private long old_eval_counter;
private long old_eval_counter_seldepth;
@Override
public void run() {
long mtime = System.currentTimeMillis();
long eval_span_0 = eval_counter - old_eval_counter;
long eval_span_sel = BoardAnalyzer.eval_counter_seldepth
- old_eval_counter_seldepth;
long eval_span = eval_span_0 + eval_span_sel;
if (old_mtime != 0) {
long time_span = mtime - old_mtime;
UCIReporter.sendInfoNum(InfoType.NPS, eval_span * 1000
/ time_span);
UCIReporter.sendInfoNum(InfoType.HASHFULL,
ResultCache.getHashfull());
}
old_mtime = mtime;
old_eval_counter += eval_span_0;
old_eval_counter_seldepth += eval_span_sel;
}
}
/**
* NegaMax with Alpha Beta Pruning and Transposition Tables
*
* @see <a
* href="http://en.wikipedia.org/wiki/Negamax#NegaMax_with_Alpha_Beta_Pruning_and_Transposition_Tables">NegaMax
* with Alpha Beta Pruning and Transposition Tables</a>
* @param position
* the position to evaluate
* @param total_depth
* the total depth to search
* @param depth
* the remaining depth to search
* @param alpha
* the alpha value
* @param beta
* the beta value
* @return returns the result of the evaluation, stored in the class
* AnalysisResult
*
* @throws InterruptedException
*/
private AnalysisResult negaMax(IPosition position, int total_depth,
int depth, int alpha, int beta) throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup (Transposition Table)
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score * side_sign);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score * side_sign);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves(true);
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
int number_legal_movs_TT =0;
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
number_legal_movs_TT = ordered_moves.size();
for (IMove k_move : killer_moves)
if (moves.contains(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (moves.contains(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
int illegal_move_counter =0;
// alpha beta search
for (IMove move : ordered_moves) {
- if(i<number_legal_movs_TT && position.isCheckAfterMove(move)){
+ if(i>=number_legal_movs_TT && position.isCheckAfterMove(move)){
illegal_move_counter++;
continue;
}
// output currently searched move to UCI
if (depth == total_depth && total_depth >= 6)
UCIReporter.sendInfoCurrMove(move, i + 1);
position.doMove(move);
AnalysisResult result = negaMax(position, total_depth, depth - 1,
-beta, -alpha);
position.undoMove(move);
int negaval = result.score * side_sign;
// better variation found
if (negaval > best_value || parent == null) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
if (depth == total_depth) {
position.updateAnalysisResult(parent);
game_state.getPosition().updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// check for mate and stalemate
if (illegal_move_counter == ordered_moves.size()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store;
if (best_value <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (best_value >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
@Override
public IMove search(int movetime, int maxMoveTime, int searchDepth,
boolean infinite, List<IMove> searchMoves) {
// note, the variable seachMoves is currently unused, this feature is
// not yet implemented!
// set up threading
timer = new Timer();
exe = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// make a copy of the actual position
IPosition position = game_state.getPosition().returnCopy();
int max_depth;
// set parameters for searchtime and searchdepth
if (movetime == 0 && maxMoveTime == 0) {
maxEvalTime = 60 * 60 * 1000; // 1h
max_depth = searchDepth;
} else if (movetime == 0 && infinite == false) {
maxEvalTime = maxMoveTime;
max_depth = searchDepth;
} else if (movetime == 0 && infinite == true) {
maxEvalTime = maxMoveTime;
max_depth = 200;
} else if (maxMoveTime == 0) {
maxEvalTime = movetime;
max_depth = 200; // this can never be reached :)
} else if (infinite == true) {
maxEvalTime = maxMoveTime;
max_depth = 200; // this can never be reached :)
} else {
maxEvalTime = Math.min(movetime, maxMoveTime);
max_depth = searchDepth;
}
timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000);
start_mtime = System.currentTimeMillis();
// reset the result
result = null;
// create a new task
PositionEvaluator evaluator = new PositionEvaluator(position, max_depth);
// execute the task
exe.execute(evaluator);
return wait_until();
}
/**
* stops all active threads if mitzi is running out of time
*
* @return the best move
*/
public IMove wait_until() {
exe.shutdown();
// wait for termination of execution
try {
if (exe.awaitTermination(maxEvalTime, THREAD_TIMEOUT_UNIT)) {
UCIReporter.sendInfoString("task completed");
} else {
UCIReporter.sendInfoString("forcing task shutdown");
exe.shutdownNow();
exe.awaitTermination(THREAD_TIMEOUT, TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// shut down timers and update killer moves
timer.cancel();
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
KillerMoves.updateKillerMove();
// if no best_move has been found yet, choose any
if (result == null) {
List<IMove> possibleMoves = game_state.getPosition()
.getPossibleMoves();
int randy = new Random().nextInt(possibleMoves.size());
return possibleMoves.get(randy);
}
// return the best move of the last completely searched tree
return result.best_move;
}
@Override
public IMove stop() {
// shut down immediately
exe.shutdownNow();
// shut down timers and update killer moves
timer.cancel();
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
KillerMoves.updateKillerMove();
// return the best move of the last completely searched tree
if (result == null)
return null; // this should never happen
return result.best_move;
}
}
| true | true | private AnalysisResult negaMax(IPosition position, int total_depth,
int depth, int alpha, int beta) throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup (Transposition Table)
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score * side_sign);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score * side_sign);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves(true);
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
int number_legal_movs_TT =0;
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
number_legal_movs_TT = ordered_moves.size();
for (IMove k_move : killer_moves)
if (moves.contains(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (moves.contains(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
int illegal_move_counter =0;
// alpha beta search
for (IMove move : ordered_moves) {
if(i<number_legal_movs_TT && position.isCheckAfterMove(move)){
illegal_move_counter++;
continue;
}
// output currently searched move to UCI
if (depth == total_depth && total_depth >= 6)
UCIReporter.sendInfoCurrMove(move, i + 1);
position.doMove(move);
AnalysisResult result = negaMax(position, total_depth, depth - 1,
-beta, -alpha);
position.undoMove(move);
int negaval = result.score * side_sign;
// better variation found
if (negaval > best_value || parent == null) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
if (depth == total_depth) {
position.updateAnalysisResult(parent);
game_state.getPosition().updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// check for mate and stalemate
if (illegal_move_counter == ordered_moves.size()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store;
if (best_value <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (best_value >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
| private AnalysisResult negaMax(IPosition position, int total_depth,
int depth, int alpha, int beta) throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
// ---------------------------------------------------------------------------------------
// whose move is it?
Side side = position.getActiveColor();
int side_sign = Side.getSideSign(side);
// ---------------------------------------------------------------------------------------
int alpha_old = alpha;
// Cache lookup (Transposition Table)
AnalysisResult entry = ResultCache.getResult(position);
if (entry != null && entry.plys_to_eval0 >= depth) {
table_counter++;
if (entry.flag == Flag.EXACT)
return entry.tinyCopy();
else if (entry.flag == Flag.LOWERBOUND)
alpha = Math.max(alpha, entry.score * side_sign);
else if (entry.flag == Flag.UPPERBOUND)
beta = Math.min(beta, entry.score * side_sign);
if (alpha >= beta)
return entry.tinyCopy();
}
// ---------------------------------------------------------------------------------------
// base of complete tree search
if (depth == 0) {
// position is a leaf node
return board_analyzer.evalBoard(position, alpha, beta);
}
// ---------------------------------------------------------------------------------------
// generate moves
List<IMove> moves = position.getPossibleMoves(true);
// ---------------------------------------------------------------------------------------
// Sort the moves:
ArrayList<IMove> ordered_moves = new ArrayList<IMove>(40);
ArrayList<IMove> remaining_moves = new ArrayList<IMove>(40);
BasicMoveComparator move_comparator = new BasicMoveComparator(position);
// Get Killer Moves:
List<IMove> killer_moves = KillerMoves.getKillerMoves(total_depth
- depth);
// if possible use the moves from Position cache as the moves with
// highest priority
int number_legal_movs_TT =0;
if (entry != null) {
ordered_moves.addAll(entry.best_moves);
number_legal_movs_TT = ordered_moves.size();
for (IMove k_move : killer_moves)
if (moves.contains(k_move)
&& !ordered_moves.contains(k_move))
ordered_moves.add(k_move);
} else {
// Killer_moves have highest priority
for (IMove k_move : killer_moves)
if (moves.contains(k_move))
ordered_moves.add(k_move);
}
// add the remaining moves and sort them using a basic heuristic
for (IMove move : moves)
if (!ordered_moves.contains(move))
remaining_moves.add(move);
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
// ---------------------------------------------------------------------------------------
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.clear();
// create new AnalysisResult and parent
AnalysisResult new_entry = null, parent = null;
if (entry == null)
new_entry = new AnalysisResult(0, null, false, 0, 0, null);
int best_value = NEG_INF; // this starts always at negative!
int i = 0;
int illegal_move_counter =0;
// alpha beta search
for (IMove move : ordered_moves) {
if(i>=number_legal_movs_TT && position.isCheckAfterMove(move)){
illegal_move_counter++;
continue;
}
// output currently searched move to UCI
if (depth == total_depth && total_depth >= 6)
UCIReporter.sendInfoCurrMove(move, i + 1);
position.doMove(move);
AnalysisResult result = negaMax(position, total_depth, depth - 1,
-beta, -alpha);
position.undoMove(move);
int negaval = result.score * side_sign;
// better variation found
if (negaval > best_value || parent == null) {
best_value = negaval;
// update cache entry
if (entry != null && entry.plys_to_eval0 < depth)
entry.best_moves.add(move);
if (entry == null)
new_entry.best_moves.add(move);
// update AnalysisResult
byte old_seldepth = (parent == null ? 0
: parent.plys_to_seldepth);
parent = result; // change reference
parent.best_move = move;
parent.plys_to_eval0 = (byte) depth;
if (best_value != POS_INF) {
parent.plys_to_seldepth = (byte) Math.max(old_seldepth,
parent.plys_to_seldepth);
}
// output to UCI
if (depth == total_depth) {
position.updateAnalysisResult(parent);
game_state.getPosition().updateAnalysisResult(parent);
UCIReporter.sendInfoPV(game_state.getPosition(), runTime());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta) {
// set also KillerMove:
if (!killer_moves.contains(move))
KillerMoves.addKillerMove(total_depth - depth, move,
killer_moves);
break;
}
i++;
}
// check for mate and stalemate
if (illegal_move_counter == ordered_moves.size()) {
eval_counter++;
if (position.isCheckPosition()) {
return new AnalysisResult(NEG_INF * side_sign, false, false, 0,
0, Flag.EXACT);
} else {
return new AnalysisResult(0, true, false, 0, 0, Flag.EXACT);
}
}
// ---------------------------------------------------------------------------------------
// Transposition Table Store;
if (best_value <= alpha_old)
parent.flag = Flag.UPPERBOUND;
else if (best_value >= beta)
parent.flag = Flag.LOWERBOUND;
else
parent.flag = Flag.EXACT;
if (entry != null && entry.plys_to_eval0 < depth) {
entry.tinySet(parent);
Collections.reverse(entry.best_moves);
}
if (entry == null) {
new_entry.tinySet(parent);
Collections.reverse(new_entry.best_moves);
ResultCache.setResult(position, new_entry);
}
return parent;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.