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/Couch25K.java b/src/Couch25K.java
index 0cbf689..a74baf1 100644
--- a/src/Couch25K.java
+++ b/src/Couch25K.java
@@ -1,230 +1,230 @@
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class Couch25K extends MIDlet implements CommandListener {
private static final int STATE_SELECT_WEEK = 1;
private static final int STATE_SELECT_WORKOUT = 2;
private static final int STATE_WORKOUT_SELECTED = 3;
private static final int STATE_WORKOUT = 4;
private static final int STATE_WORKOUT_PAUSED = 5;
private static final int STATE_WORKOUT_COMPLETE = 6;
private int state;
private int selectedWeek;
private int selectedWorkout;
private Workout workout;
private WorkoutState workoutState;
private Display display;
private List selectWeekScreen;
private Command selectWeekCommand = new Command("Select", Command.ITEM, 1);
private List selectWorkoutScreen;
private Command selectWorkoutCommand = new Command("Select", Command.ITEM, 1);
private Form workoutScreen;
private Command startWorkoutCommand = new Command("Start", Command.SCREEN, 1);
private Command pauseWorkoutCommand = new Command("Pause", Command.SCREEN, 2);
private Command resumeWorkoutCommand = new Command("Resume", Command.SCREEN, 3);
private StringItem action;
private Gauge stepProgress;
private StringItem timeDisplay;
private Gauge workoutProgress;
private Form workoutCompleteScreen;
// Workout timing
private Timer workoutTimer;
// MIDlet API --------------------------------------------------------------
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
display = Display.getDisplay(this);
// Week selection screen setup
- selectWeekScreen = new List("Select Week", Choice.EXCLUSIVE, new String[] {
+ selectWeekScreen = new List("Select Week", Choice.IMPLICIT, new String[] {
"Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6",
"Week 7", "Week 8", "Week 9"
}, null);
selectWeekScreen.addCommand(selectWeekCommand);
selectWeekScreen.setCommandListener(this);
// Workout selection screen setup
- selectWorkoutScreen = new List("Select Workout", Choice.EXCLUSIVE, new String[] {
+ selectWorkoutScreen = new List("Select Workout", Choice.IMPLICIT, new String[] {
"Workout 1", "Workout 2", "Workout 3"
}, null);
selectWorkoutScreen.addCommand(selectWorkoutCommand);
selectWorkoutScreen.setCommandListener(this);
// Workout screen setup
workoutScreen = new Form("");
workoutScreen.setCommandListener(this);
action = new StringItem(null, "");
stepProgress = new Gauge("Step", false, -1, 0);
timeDisplay = new StringItem(null, "");
workoutProgress = new Gauge("Workout", false, -1, 0);
workoutScreen.append(action);
workoutScreen.append(stepProgress);
workoutScreen.append(timeDisplay);
workoutScreen.append(workoutProgress);
workoutCompleteScreen = new Form("Workout Complete");
workoutCompleteScreen.setCommandListener(this);
}
if (state == STATE_WORKOUT_PAUSED) {
startWorkout();
} else {
init();
}
}
protected void pauseApp() {
if (state == STATE_WORKOUT) {
pauseWorkout();
}
}
protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
}
// CommandListener API -----------------------------------------------------
public void commandAction(Command c, Displayable d) {
switch (state) {
case STATE_SELECT_WEEK:
if (c == selectWeekCommand) selectWeek();
break;
case STATE_SELECT_WORKOUT:
if (c == selectWorkoutCommand) selectWorkout();
break;
case STATE_WORKOUT_SELECTED:
if (c == startWorkoutCommand) startWorkout();
break;
case STATE_WORKOUT:
if (c == pauseWorkoutCommand) pauseWorkout();
break;
case STATE_WORKOUT_PAUSED:
if (c == resumeWorkoutCommand) resumeWorkout();
break;
default:
throw new IllegalStateException("Command " + c + " not expected in state " + state);
}
}
// State transitions -------------------------------------------------------
public void init() {
display.setCurrent(selectWeekScreen);
state = STATE_SELECT_WEEK;
}
public void selectWeek() {
selectedWeek = selectWeekScreen.getSelectedIndex() + 1;
display.setCurrent(selectWorkoutScreen);
state = STATE_SELECT_WORKOUT;
}
public void selectWorkout() {
selectedWorkout = selectWorkoutScreen.getSelectedIndex() + 1;
workout = Workouts.getWorkout(selectedWeek, selectedWorkout);
workoutScreen.setTitle("Week " + selectedWeek + ", Workout " + selectedWorkout);
workoutProgress.setMaxValue(workout.totalDuration);
workoutProgress.setValue(0);
workoutScreen.addCommand(startWorkoutCommand);
display.setCurrent(workoutScreen);
workoutState = new WorkoutState(this, workout);
state = STATE_WORKOUT_SELECTED;
}
public void startWorkout() {
workoutScreen.removeCommand(startWorkoutCommand);
workoutScreen.addCommand(pauseWorkoutCommand);
trackWorkoutState(workoutState);
state = STATE_WORKOUT;
}
public void pauseWorkout() {
workoutTimer.cancel();
workoutTimer = null;
workoutScreen.removeCommand(pauseWorkoutCommand);
workoutScreen.addCommand(resumeWorkoutCommand);
state = STATE_WORKOUT_PAUSED;
}
public void resumeWorkout() {
workoutScreen.removeCommand(resumeWorkoutCommand);
workoutScreen.addCommand(pauseWorkoutCommand);
trackWorkoutState(workoutState);
state = STATE_WORKOUT;
}
public void finishWorkout() {
workoutTimer.cancel();
display.setCurrent(workoutCompleteScreen);
playSound("finished");
state = STATE_WORKOUT_COMPLETE;
}
// Status update API -------------------------------------------------------
public void updateStep(int stepNum, WorkoutStep step) {
action.setText(step.action + " (" + stepNum + "/" + workout.steps.length + ")");
stepProgress.setValue(0);
stepProgress.setMaxValue(step.duration);
if (stepNum > 1) {
playSound(step.action.toLowerCase());
}
}
public void updateProgress(int progress, int totalTime) {
stepProgress.setValue(progress);
int minutes = totalTime / 60;
int seconds = totalTime % 60;
timeDisplay.setText(pad(minutes) + ":" + pad(seconds));
workoutProgress.setValue(totalTime);
}
// Utilities ---------------------------------------------------------------
private void trackWorkoutState(final WorkoutState workoutState) {
workoutTimer = new Timer();
workoutTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
workoutState.increment();
}
}, 0, 1000);
}
private void playSound(String file) {
try {
Manager.createPlayer(
getClass().getResourceAsStream("/" + file + ".wav"),
"audio/x-wav"
).start();
} catch (MediaException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String pad(int n) {
if (n < 10) {
return "0" + n;
}
return "" + n;
}
}
| false | true | protected void startApp() throws MIDletStateChangeException {
if (display == null) {
display = Display.getDisplay(this);
// Week selection screen setup
selectWeekScreen = new List("Select Week", Choice.EXCLUSIVE, new String[] {
"Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6",
"Week 7", "Week 8", "Week 9"
}, null);
selectWeekScreen.addCommand(selectWeekCommand);
selectWeekScreen.setCommandListener(this);
// Workout selection screen setup
selectWorkoutScreen = new List("Select Workout", Choice.EXCLUSIVE, new String[] {
"Workout 1", "Workout 2", "Workout 3"
}, null);
selectWorkoutScreen.addCommand(selectWorkoutCommand);
selectWorkoutScreen.setCommandListener(this);
// Workout screen setup
workoutScreen = new Form("");
workoutScreen.setCommandListener(this);
action = new StringItem(null, "");
stepProgress = new Gauge("Step", false, -1, 0);
timeDisplay = new StringItem(null, "");
workoutProgress = new Gauge("Workout", false, -1, 0);
workoutScreen.append(action);
workoutScreen.append(stepProgress);
workoutScreen.append(timeDisplay);
workoutScreen.append(workoutProgress);
workoutCompleteScreen = new Form("Workout Complete");
workoutCompleteScreen.setCommandListener(this);
}
if (state == STATE_WORKOUT_PAUSED) {
startWorkout();
} else {
init();
}
}
| protected void startApp() throws MIDletStateChangeException {
if (display == null) {
display = Display.getDisplay(this);
// Week selection screen setup
selectWeekScreen = new List("Select Week", Choice.IMPLICIT, new String[] {
"Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6",
"Week 7", "Week 8", "Week 9"
}, null);
selectWeekScreen.addCommand(selectWeekCommand);
selectWeekScreen.setCommandListener(this);
// Workout selection screen setup
selectWorkoutScreen = new List("Select Workout", Choice.IMPLICIT, new String[] {
"Workout 1", "Workout 2", "Workout 3"
}, null);
selectWorkoutScreen.addCommand(selectWorkoutCommand);
selectWorkoutScreen.setCommandListener(this);
// Workout screen setup
workoutScreen = new Form("");
workoutScreen.setCommandListener(this);
action = new StringItem(null, "");
stepProgress = new Gauge("Step", false, -1, 0);
timeDisplay = new StringItem(null, "");
workoutProgress = new Gauge("Workout", false, -1, 0);
workoutScreen.append(action);
workoutScreen.append(stepProgress);
workoutScreen.append(timeDisplay);
workoutScreen.append(workoutProgress);
workoutCompleteScreen = new Form("Workout Complete");
workoutCompleteScreen.setCommandListener(this);
}
if (state == STATE_WORKOUT_PAUSED) {
startWorkout();
} else {
init();
}
}
|
diff --git a/SmartPaymentGenerator/src/com/smartpaymentformat/string/SmartPayment.java b/SmartPaymentGenerator/src/com/smartpaymentformat/string/SmartPayment.java
index 069d053..7787598 100644
--- a/SmartPaymentGenerator/src/com/smartpaymentformat/string/SmartPayment.java
+++ b/SmartPaymentGenerator/src/com/smartpaymentformat/string/SmartPayment.java
@@ -1,83 +1,83 @@
/**
* Copyright (c) 2012, SmartPayment (www.SmartPayment.com).
*/
package com.smartpaymentformat.string;
import com.smartpaymentformat.account.BankAccount;
import java.text.SimpleDateFormat;
import net.sf.junidecode.Junidecode;
/**
*
* @author petrdvorak
*/
public class SmartPayment {
private static String protocolVersion = "1.0";
public static String paymentStringFromAccount(SmartPaymentParameters parameters, SmartPaymentMap extendedParameters, boolean transliterateParams) {
- String paymentString = "PAY*" + protocolVersion + "*";
+ String paymentString = "SPD*" + protocolVersion + "*";
if (parameters.getBankAccount().getIBAN() != null) {
paymentString += "ACC:" + parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
paymentString += "*";
}
if (parameters.getAlternateAccounts() != null && !parameters.getAlternateAccounts().isEmpty()) {
paymentString += "ALT-ACC:";
boolean firstItem = true;
for (BankAccount bankAccount : parameters.getAlternateAccounts()) {
if (!firstItem) {
paymentString += ",";
} else {
firstItem = false;
}
paymentString += parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
}
paymentString += "*";
}
if (parameters.getAmount() != null) {
paymentString += "AM:" + parameters.getAmount() + "*";
}
if (parameters.getCurrency() != null) {
paymentString += "CC:" + parameters.getCurrency() + "*";
}
if (parameters.getSendersReference() != null) {
paymentString += "RF:" + parameters.getSendersReference() + "*";
}
if (parameters.getRecipientName() != null) {
paymentString += "RN:" + (transliterateParams
? Junidecode.unidecode(parameters.getRecipientName().toUpperCase())
: parameters.getRecipientName()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getDate() != null) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
paymentString += "DT:" + simpleDateFormat.format(parameters.getDate()) + "*";
}
if (parameters.getMessage() != null) {
paymentString += "MSG:" + (transliterateParams
? Junidecode.unidecode(parameters.getMessage().toUpperCase())
: parameters.getMessage()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getNotificationType() != null) {
if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.email) {
paymentString += "NT:E*";
} else if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.phone) {
paymentString += "NT:P*";
}
}
if (parameters.getNotificationValue() != null) {
- paymentString += "NV:" + parameters.getNotificationValue() + "*";
+ paymentString += "NTA:" + parameters.getNotificationValue() + "*";
}
if (extendedParameters != null && !extendedParameters.isEmpty()) {
paymentString += (transliterateParams
? Junidecode.unidecode(extendedParameters.toExtendedParams().toUpperCase())
: extendedParameters.toExtendedParams()).replaceAll("\\*", "%2A");
}
return paymentString.substring(0, paymentString.length() - 1);
}
}
| false | true | public static String paymentStringFromAccount(SmartPaymentParameters parameters, SmartPaymentMap extendedParameters, boolean transliterateParams) {
String paymentString = "PAY*" + protocolVersion + "*";
if (parameters.getBankAccount().getIBAN() != null) {
paymentString += "ACC:" + parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
paymentString += "*";
}
if (parameters.getAlternateAccounts() != null && !parameters.getAlternateAccounts().isEmpty()) {
paymentString += "ALT-ACC:";
boolean firstItem = true;
for (BankAccount bankAccount : parameters.getAlternateAccounts()) {
if (!firstItem) {
paymentString += ",";
} else {
firstItem = false;
}
paymentString += parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
}
paymentString += "*";
}
if (parameters.getAmount() != null) {
paymentString += "AM:" + parameters.getAmount() + "*";
}
if (parameters.getCurrency() != null) {
paymentString += "CC:" + parameters.getCurrency() + "*";
}
if (parameters.getSendersReference() != null) {
paymentString += "RF:" + parameters.getSendersReference() + "*";
}
if (parameters.getRecipientName() != null) {
paymentString += "RN:" + (transliterateParams
? Junidecode.unidecode(parameters.getRecipientName().toUpperCase())
: parameters.getRecipientName()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getDate() != null) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
paymentString += "DT:" + simpleDateFormat.format(parameters.getDate()) + "*";
}
if (parameters.getMessage() != null) {
paymentString += "MSG:" + (transliterateParams
? Junidecode.unidecode(parameters.getMessage().toUpperCase())
: parameters.getMessage()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getNotificationType() != null) {
if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.email) {
paymentString += "NT:E*";
} else if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.phone) {
paymentString += "NT:P*";
}
}
if (parameters.getNotificationValue() != null) {
paymentString += "NV:" + parameters.getNotificationValue() + "*";
}
if (extendedParameters != null && !extendedParameters.isEmpty()) {
paymentString += (transliterateParams
? Junidecode.unidecode(extendedParameters.toExtendedParams().toUpperCase())
: extendedParameters.toExtendedParams()).replaceAll("\\*", "%2A");
}
return paymentString.substring(0, paymentString.length() - 1);
}
| public static String paymentStringFromAccount(SmartPaymentParameters parameters, SmartPaymentMap extendedParameters, boolean transliterateParams) {
String paymentString = "SPD*" + protocolVersion + "*";
if (parameters.getBankAccount().getIBAN() != null) {
paymentString += "ACC:" + parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
paymentString += "*";
}
if (parameters.getAlternateAccounts() != null && !parameters.getAlternateAccounts().isEmpty()) {
paymentString += "ALT-ACC:";
boolean firstItem = true;
for (BankAccount bankAccount : parameters.getAlternateAccounts()) {
if (!firstItem) {
paymentString += ",";
} else {
firstItem = false;
}
paymentString += parameters.getBankAccount().getIBAN();
if (parameters.getBankAccount().getBIC() != null) {
paymentString += "+" + parameters.getBankAccount().getBIC();
}
}
paymentString += "*";
}
if (parameters.getAmount() != null) {
paymentString += "AM:" + parameters.getAmount() + "*";
}
if (parameters.getCurrency() != null) {
paymentString += "CC:" + parameters.getCurrency() + "*";
}
if (parameters.getSendersReference() != null) {
paymentString += "RF:" + parameters.getSendersReference() + "*";
}
if (parameters.getRecipientName() != null) {
paymentString += "RN:" + (transliterateParams
? Junidecode.unidecode(parameters.getRecipientName().toUpperCase())
: parameters.getRecipientName()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getDate() != null) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
paymentString += "DT:" + simpleDateFormat.format(parameters.getDate()) + "*";
}
if (parameters.getMessage() != null) {
paymentString += "MSG:" + (transliterateParams
? Junidecode.unidecode(parameters.getMessage().toUpperCase())
: parameters.getMessage()).replaceAll("\\*", "%2A") + "*";
}
if (parameters.getNotificationType() != null) {
if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.email) {
paymentString += "NT:E*";
} else if (parameters.getNotificationType() == SmartPaymentParameters.PaymentNotificationType.phone) {
paymentString += "NT:P*";
}
}
if (parameters.getNotificationValue() != null) {
paymentString += "NTA:" + parameters.getNotificationValue() + "*";
}
if (extendedParameters != null && !extendedParameters.isEmpty()) {
paymentString += (transliterateParams
? Junidecode.unidecode(extendedParameters.toExtendedParams().toUpperCase())
: extendedParameters.toExtendedParams()).replaceAll("\\*", "%2A");
}
return paymentString.substring(0, paymentString.length() - 1);
}
|
diff --git a/src/groovy/org/pillarone/riskanalytics/application/ui/resultnavigator/view/CategoryConfigurationDialog.java b/src/groovy/org/pillarone/riskanalytics/application/ui/resultnavigator/view/CategoryConfigurationDialog.java
index eaa6ef18..0afcc775 100644
--- a/src/groovy/org/pillarone/riskanalytics/application/ui/resultnavigator/view/CategoryConfigurationDialog.java
+++ b/src/groovy/org/pillarone/riskanalytics/application/ui/resultnavigator/view/CategoryConfigurationDialog.java
@@ -1,279 +1,281 @@
package org.pillarone.riskanalytics.application.ui.resultnavigator.view;
import com.ulcjava.base.application.*;
import com.ulcjava.base.application.event.*;
import com.ulcjava.base.application.tree.TreePath;
import com.ulcjava.base.application.util.Color;
import org.pillarone.riskanalytics.application.ui.resultnavigator.categories.CategoryMapping;
import org.pillarone.riskanalytics.application.ui.resultnavigator.categories.ICategoryChangeListener;
import org.pillarone.riskanalytics.application.ui.resultnavigator.categories.ICategoryResolver;
import org.pillarone.riskanalytics.application.ui.resultnavigator.categories.resolver.CategoryResolverFactory;
import org.pillarone.riskanalytics.application.ui.resultnavigator.categories.resolver.CategoryResolverTreeNode;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Dialog to inspect and possibly edit the CategoryMapping.
*
* @author martin.melchior
*/
public class CategoryConfigurationDialog extends ULCDialog {
private CategoryMapping categoryMapping;
private ULCCardPane matcherTreePane;
private ULCCardPane matcherConfigPane;
// cache for a pane with the tree defined per category - each node in this tree consists of a resolver
private Map<String,ULCScrollPane> resolverTreeCache;
// cache that contains for each resolver an associated view
private Map<ICategoryResolver,ULCBoxPane> resolverCache;
public CategoryConfigurationDialog(ULCWindow parent) {
super(parent);
// look & feel, title, size, etc.
boolean metalLookAndFeel = "Metal".equals(ClientContext.getLookAndFeelName());
if (!metalLookAndFeel && ClientContext.getLookAndFeelSupportsWindowDecorations()) {
setUndecorated(false);
setWindowDecorationStyle(ULCDialog.INFORMATION_DIALOG);
}
setTitle("Configure Categories");
setLocationRelativeTo(parent);
setSize(800, 600);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new IWindowListener() {
public void windowClosing(WindowEvent event) {
setVisible(false);
}
});
}
/**
* Create the contents of the dialog for the given category mapping
* @param categoryMapping
*/
@SuppressWarnings("serial")
public void createContent(final CategoryMapping categoryMapping) {
this.categoryMapping = categoryMapping;
// initialize the caches
resolverTreeCache = new HashMap<String,ULCScrollPane>();
resolverCache = new HashMap<ICategoryResolver,ULCBoxPane>();
CategoryListModel categoryListModel = new CategoryListModel();
categoryListModel.addAll(categoryMapping.getCategories());
// initialize components
ULCBoxPane contentPane = new ULCBoxPane(true);
ULCBoxPane categoryListPane = new ULCBoxPane(true);
categoryListPane.setBorder(BorderFactory.createTitledBorder("Categories"));
CategoryList categoryList = new CategoryList();
categoryList.setModel(categoryListModel);
categoryList.setSelectedIndex(0);
// ULCBoxPane addCategoryPane = new ULCBoxPane(false);
// addCategoryPane.setBorder(BorderFactory.createTitledBorder("Add Category"));
// final ULCTextField categorySpec = new ULCTextField(40);
// categorySpec.setEditable(true);
// ULCButton addCategoryButton = new ULCButton("Add");
matcherTreePane = new ULCCardPane();
matcherTreePane.setBorder(BorderFactory.createTitledBorder("How to Match Members"));
matcherConfigPane = new ULCCardPane();
matcherConfigPane.setBorder(BorderFactory.createTitledBorder("Matcher Specification"));
ULCSplitPane matcherEditArea = new ULCSplitPane(ULCSplitPane.VERTICAL_SPLIT);
matcherEditArea.setOneTouchExpandable(true);
matcherEditArea.setDividerLocation(0.6);
matcherEditArea.setDividerSize(10);
ULCSplitPane splitPane = new ULCSplitPane(ULCSplitPane.HORIZONTAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(0.4);
splitPane.setDividerSize(10);
// layout them
categoryListPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, categoryList);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, categorySpec);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, addCategoryButton);
// categoryListPane.add(ULCBoxPane.BOX_LEFT_BOTTOM,addCategoryPane);
matcherEditArea.setTopComponent(matcherTreePane);
matcherEditArea.setBottomComponent(matcherConfigPane);
splitPane.setLeftComponent(categoryListPane);
splitPane.setRightComponent(matcherEditArea);
contentPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, splitPane);
this.add(contentPane);
pack();
// attach listeners
categoryMapping.addCategoryChangeListener(categoryList);
//addCategoryButton.addActionListener(new IActionListener() {
// public void actionPerformed(ActionEvent actionEvent) {
// String newCategory = categorySpec.getText();
// categoryMapping.addCategory(newCategory);
// }
//});
categoryList.addListSelectionListener(new IListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int index = ((ULCListSelectionModel) event.getSource()).getSelectedIndices()[0];
String selectedCategory = categoryMapping.getCategories().get(index);
showCategoryResolverTree(selectedCategory);
}
});
// prepare the initial view - selected category in the list and associated resolver tree
- String selectedCategory = categoryMapping.getCategories().get(0);
- showCategoryResolverTree(selectedCategory);
+ if (!categoryMapping.getCategories().isEmpty()) {
+ String selectedCategory = categoryMapping.getCategories().get(0);
+ showCategoryResolverTree(selectedCategory);
+ }
}
/**
* Create a tree pane for the category resolver
* @param selectedCategory
*/
private void showCategoryResolverTree(String selectedCategory) {
// get the resolver associated with the selected category
ICategoryResolver categoryResolver = categoryMapping.getCategoryResolver(selectedCategory);
// check whether the tree (included in a scroll pane) is already available in the cache,
// if no instantiate one - if yes get it from the cache
if (!resolverTreeCache.containsKey(selectedCategory)){
CategoryResolverTree categoryResolverTree = new CategoryResolverTree(categoryResolver);
ULCScrollPane scrollPane = new ULCScrollPane(categoryResolverTree);
matcherTreePane.addCard(selectedCategory, scrollPane);
resolverTreeCache.put(selectedCategory, scrollPane);
}
ULCScrollPane newPane = resolverTreeCache.get(selectedCategory);
// put this pane that contains the resolver tree in a ULCTree
final ULCTree tree = (ULCTree) newPane.getViewPortView();
matcherTreePane.setSelectedComponent(newPane);
// attach a listener that allows to navigate within the tree and inspect the node in yet a separate pane
tree.addActionListener(new IActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
TreePath selection = tree.getSelectionPath();
Object o = selection.getLastPathComponent();
if (o instanceof CategoryResolverTreeNode) {
showCategoryResolver(((CategoryResolverTreeNode) o).getResolver());
}
}
});
}
// Show the single category resolver
public void showCategoryResolver(ICategoryResolver resolver) {
// check whether the resolver view is already loaded in the cache
// if no, instantiate and put it in the cache - if yes get the view from the cache
if (!resolverCache.containsKey(resolver)) {
ULCBoxPane view = CategoryResolverFactory.getMatcherView(resolver);
if (view != null) {
matcherConfigPane.addCard(resolver.toString(), view);
resolverCache.put(resolver, view);
}
}
ULCBoxPane view = resolverCache.get(resolver);
// bring the selected resolver to the top in the card pane
if (view != null) {
matcherConfigPane.setSelectedComponent(view);
}
}
public void addSaveActionListener(IActionListener listener) {
}
private class CategoryList extends ULCList implements ICategoryChangeListener {
CategoryList() {
super();
setSelectionMode(ULCListSelectionModel.SINGLE_SELECTION);
setSelectionBackground(Color.green);
}
public void categoryAdded(String category) {
}
public void categoryRemoved(String category) {
}
}
private class CategoryListModel extends AbstractListModel implements IMutableListModel {
public void add(Object o) {
categoryMapping.addCategory((String) o);
// fire change events ??
}
public void add(int i, Object o) {
categoryMapping.addCategory((String) o);
}
public void addAll(Object[] objects) {
for (Object o : objects) {
categoryMapping.addCategory((String) o);
}
}
public void addAll(Collection collection) {
for (Object o : collection) {
categoryMapping.addCategory((String) o);
}
}
public void addAll(int i, Object[] objects) {
for (Object o : objects) {
categoryMapping.addCategory((String) o);
}
}
public void addAll(int i, Collection collection) {
for (Object o : collection) {
categoryMapping.addCategory((String) o);
}
}
public void clear() {
categoryMapping.getMatcherMap().clear();
}
public Object remove(int i) {
String category = categoryMapping.getCategories().get(i);
boolean removed = categoryMapping.removeCategory(category);
return removed ? category : null;
}
public boolean remove(Object o) {
return categoryMapping.removeCategory((String)o);
}
public boolean removeAll(Object[] objects) {
boolean test = true;
for (Object o : objects) {
test = test && remove(o);
}
return test;
}
public boolean removeAll(Collection collection) {
boolean test = true;
for (Object o : collection) {
test = test && remove(o);
}
return test;
}
public Object set(int i, Object o) {
categoryMapping.addCategory((String)o);
return o;
}
public int getSize() {
return categoryMapping.getNumberOfCategories();
}
public Object getElementAt(int i) {
return categoryMapping.getCategories().get(i);
}
}
}
| true | true | public void createContent(final CategoryMapping categoryMapping) {
this.categoryMapping = categoryMapping;
// initialize the caches
resolverTreeCache = new HashMap<String,ULCScrollPane>();
resolverCache = new HashMap<ICategoryResolver,ULCBoxPane>();
CategoryListModel categoryListModel = new CategoryListModel();
categoryListModel.addAll(categoryMapping.getCategories());
// initialize components
ULCBoxPane contentPane = new ULCBoxPane(true);
ULCBoxPane categoryListPane = new ULCBoxPane(true);
categoryListPane.setBorder(BorderFactory.createTitledBorder("Categories"));
CategoryList categoryList = new CategoryList();
categoryList.setModel(categoryListModel);
categoryList.setSelectedIndex(0);
// ULCBoxPane addCategoryPane = new ULCBoxPane(false);
// addCategoryPane.setBorder(BorderFactory.createTitledBorder("Add Category"));
// final ULCTextField categorySpec = new ULCTextField(40);
// categorySpec.setEditable(true);
// ULCButton addCategoryButton = new ULCButton("Add");
matcherTreePane = new ULCCardPane();
matcherTreePane.setBorder(BorderFactory.createTitledBorder("How to Match Members"));
matcherConfigPane = new ULCCardPane();
matcherConfigPane.setBorder(BorderFactory.createTitledBorder("Matcher Specification"));
ULCSplitPane matcherEditArea = new ULCSplitPane(ULCSplitPane.VERTICAL_SPLIT);
matcherEditArea.setOneTouchExpandable(true);
matcherEditArea.setDividerLocation(0.6);
matcherEditArea.setDividerSize(10);
ULCSplitPane splitPane = new ULCSplitPane(ULCSplitPane.HORIZONTAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(0.4);
splitPane.setDividerSize(10);
// layout them
categoryListPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, categoryList);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, categorySpec);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, addCategoryButton);
// categoryListPane.add(ULCBoxPane.BOX_LEFT_BOTTOM,addCategoryPane);
matcherEditArea.setTopComponent(matcherTreePane);
matcherEditArea.setBottomComponent(matcherConfigPane);
splitPane.setLeftComponent(categoryListPane);
splitPane.setRightComponent(matcherEditArea);
contentPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, splitPane);
this.add(contentPane);
pack();
// attach listeners
categoryMapping.addCategoryChangeListener(categoryList);
//addCategoryButton.addActionListener(new IActionListener() {
// public void actionPerformed(ActionEvent actionEvent) {
// String newCategory = categorySpec.getText();
// categoryMapping.addCategory(newCategory);
// }
//});
categoryList.addListSelectionListener(new IListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int index = ((ULCListSelectionModel) event.getSource()).getSelectedIndices()[0];
String selectedCategory = categoryMapping.getCategories().get(index);
showCategoryResolverTree(selectedCategory);
}
});
// prepare the initial view - selected category in the list and associated resolver tree
String selectedCategory = categoryMapping.getCategories().get(0);
showCategoryResolverTree(selectedCategory);
}
| public void createContent(final CategoryMapping categoryMapping) {
this.categoryMapping = categoryMapping;
// initialize the caches
resolverTreeCache = new HashMap<String,ULCScrollPane>();
resolverCache = new HashMap<ICategoryResolver,ULCBoxPane>();
CategoryListModel categoryListModel = new CategoryListModel();
categoryListModel.addAll(categoryMapping.getCategories());
// initialize components
ULCBoxPane contentPane = new ULCBoxPane(true);
ULCBoxPane categoryListPane = new ULCBoxPane(true);
categoryListPane.setBorder(BorderFactory.createTitledBorder("Categories"));
CategoryList categoryList = new CategoryList();
categoryList.setModel(categoryListModel);
categoryList.setSelectedIndex(0);
// ULCBoxPane addCategoryPane = new ULCBoxPane(false);
// addCategoryPane.setBorder(BorderFactory.createTitledBorder("Add Category"));
// final ULCTextField categorySpec = new ULCTextField(40);
// categorySpec.setEditable(true);
// ULCButton addCategoryButton = new ULCButton("Add");
matcherTreePane = new ULCCardPane();
matcherTreePane.setBorder(BorderFactory.createTitledBorder("How to Match Members"));
matcherConfigPane = new ULCCardPane();
matcherConfigPane.setBorder(BorderFactory.createTitledBorder("Matcher Specification"));
ULCSplitPane matcherEditArea = new ULCSplitPane(ULCSplitPane.VERTICAL_SPLIT);
matcherEditArea.setOneTouchExpandable(true);
matcherEditArea.setDividerLocation(0.6);
matcherEditArea.setDividerSize(10);
ULCSplitPane splitPane = new ULCSplitPane(ULCSplitPane.HORIZONTAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(0.4);
splitPane.setDividerSize(10);
// layout them
categoryListPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, categoryList);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, categorySpec);
// addCategoryPane.add(ULCBoxPane.BOX_LEFT_BOTTOM, addCategoryButton);
// categoryListPane.add(ULCBoxPane.BOX_LEFT_BOTTOM,addCategoryPane);
matcherEditArea.setTopComponent(matcherTreePane);
matcherEditArea.setBottomComponent(matcherConfigPane);
splitPane.setLeftComponent(categoryListPane);
splitPane.setRightComponent(matcherEditArea);
contentPane.add(ULCBoxPane.BOX_EXPAND_EXPAND, splitPane);
this.add(contentPane);
pack();
// attach listeners
categoryMapping.addCategoryChangeListener(categoryList);
//addCategoryButton.addActionListener(new IActionListener() {
// public void actionPerformed(ActionEvent actionEvent) {
// String newCategory = categorySpec.getText();
// categoryMapping.addCategory(newCategory);
// }
//});
categoryList.addListSelectionListener(new IListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int index = ((ULCListSelectionModel) event.getSource()).getSelectedIndices()[0];
String selectedCategory = categoryMapping.getCategories().get(index);
showCategoryResolverTree(selectedCategory);
}
});
// prepare the initial view - selected category in the list and associated resolver tree
if (!categoryMapping.getCategories().isEmpty()) {
String selectedCategory = categoryMapping.getCategories().get(0);
showCategoryResolverTree(selectedCategory);
}
}
|
diff --git a/src/main/java/net/sf/hajdbc/sql/DatabaseClusterImpl.java b/src/main/java/net/sf/hajdbc/sql/DatabaseClusterImpl.java
index 4726bb3a..f5b91037 100644
--- a/src/main/java/net/sf/hajdbc/sql/DatabaseClusterImpl.java
+++ b/src/main/java/net/sf/hajdbc/sql/DatabaseClusterImpl.java
@@ -1,659 +1,659 @@
/*
* HA-JDBC: High-Availability JDBC
* Copyright 2004-2009 Paul Ferraro
*
* 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.hajdbc.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.DatabaseCluster;
import net.sf.hajdbc.DatabaseClusterConfiguration;
import net.sf.hajdbc.DatabaseClusterConfigurationListener;
import net.sf.hajdbc.DatabaseClusterListener;
import net.sf.hajdbc.Dialect;
import net.sf.hajdbc.Messages;
import net.sf.hajdbc.SynchronizationListener;
import net.sf.hajdbc.TransactionMode;
import net.sf.hajdbc.balancer.Balancer;
import net.sf.hajdbc.cache.DatabaseMetaDataCache;
import net.sf.hajdbc.codec.Codec;
import net.sf.hajdbc.distributed.CommandDispatcherFactory;
import net.sf.hajdbc.durability.Durability;
import net.sf.hajdbc.durability.InvocationEvent;
import net.sf.hajdbc.durability.InvokerEvent;
import net.sf.hajdbc.lock.LockManager;
import net.sf.hajdbc.lock.distributed.DistributedLockManager;
import net.sf.hajdbc.lock.semaphore.SemaphoreLockManager;
import net.sf.hajdbc.logging.Level;
import net.sf.hajdbc.logging.Logger;
import net.sf.hajdbc.logging.LoggerFactory;
import net.sf.hajdbc.management.Description;
import net.sf.hajdbc.management.MBean;
import net.sf.hajdbc.management.ManagedOperation;
import net.sf.hajdbc.state.DatabaseEvent;
import net.sf.hajdbc.state.StateManager;
import net.sf.hajdbc.state.distributed.DistributedStateManager;
import net.sf.hajdbc.util.concurrent.cron.CronThreadPoolExecutor;
import org.quartz.CronExpression;
/**
* @author paul
*
*/
@MBean
public class DatabaseClusterImpl<Z, D extends Database<Z>> implements DatabaseCluster<Z, D>
{
static final Logger logger = LoggerFactory.getLogger(DatabaseClusterImpl.class);
private final String id;
final DatabaseClusterConfiguration<Z, D> configuration;
private Balancer<Z, D> balancer;
private Dialect dialect;
private Durability<Z, D> durability;
private DatabaseMetaDataCache<Z, D> databaseMetaDataCache;
private ExecutorService executor;
private Codec codec;
private CronThreadPoolExecutor cronExecutor;
private LockManager lockManager;
private StateManager stateManager;
private volatile boolean active = false;
private final List<DatabaseClusterConfigurationListener<Z, D>> configurationListeners = new CopyOnWriteArrayList<DatabaseClusterConfigurationListener<Z, D>>();
private final List<DatabaseClusterListener> clusterListeners = new CopyOnWriteArrayList<DatabaseClusterListener>();
private final List<SynchronizationListener> synchronizationListeners = new CopyOnWriteArrayList<SynchronizationListener>();
public DatabaseClusterImpl(String id, DatabaseClusterConfiguration<Z, D> configuration, DatabaseClusterConfigurationListener<Z, D> listener)
{
this.id = id;
this.configuration = configuration;
if (listener != null)
{
this.configurationListeners.add(listener);
}
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#activate(net.sf.hajdbc.Database, net.sf.hajdbc.state.StateManager)
*/
@Override
public boolean activate(D database, StateManager manager)
{
boolean added = this.balancer.add(database);
if (added)
{
database.setActive(true);
if (database.isDirty())
{
database.clean();
}
DatabaseEvent event = new DatabaseEvent(database);
manager.activated(event);
for (DatabaseClusterListener listener: this.clusterListeners)
{
listener.activated(event);
}
}
return added;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#addConfigurationListener(net.sf.hajdbc.DatabaseClusterConfigurationListener)
*/
@Override
public void addConfigurationListener(DatabaseClusterConfigurationListener<Z, D> listener)
{
this.configurationListeners.add(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#addListener(net.sf.hajdbc.DatabaseClusterListener)
*/
@Override
public void addListener(DatabaseClusterListener listener)
{
this.clusterListeners.add(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#addSynchronizationListener(net.sf.hajdbc.SynchronizationListener)
*/
@Override
public void addSynchronizationListener(SynchronizationListener listener)
{
this.synchronizationListeners.add(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#deactivate(net.sf.hajdbc.Database, net.sf.hajdbc.state.StateManager)
*/
@Override
public boolean deactivate(D database, StateManager manager)
{
boolean removed = this.balancer.remove(database);
if (removed)
{
database.setActive(false);
DatabaseEvent event = new DatabaseEvent(database);
manager.deactivated(event);
for (DatabaseClusterListener listener: this.clusterListeners)
{
listener.deactivated(event);
}
}
return removed;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getBalancer()
*/
@Override
public Balancer<Z, D> getBalancer()
{
return this.balancer;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getDatabase(java.lang.String)
*/
@Override
public D getDatabase(String id)
{
return this.configuration.getDatabaseMap().get(id);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getDatabaseMetaDataCache()
*/
@Override
public DatabaseMetaDataCache<Z, D> getDatabaseMetaDataCache()
{
return this.databaseMetaDataCache;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getDialect()
*/
@Override
public Dialect getDialect()
{
return this.dialect;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getDurability()
*/
@Override
public Durability<Z, D> getDurability()
{
return this.durability;
}
/**
* Flushes this cluster's cache of DatabaseMetaData.
*/
@ManagedOperation
@Description("Flushes this cluster's cache of database meta data")
public void flushMetaDataCache()
{
try
{
this.databaseMetaDataCache.flush();
}
catch (SQLException e)
{
throw new IllegalStateException(e.toString(), e);
}
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getId()
*/
@Override
public String getId()
{
return this.id;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getLockManager()
*/
@Override
public LockManager getLockManager()
{
return this.lockManager;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getNonTransactionalExecutor()
*/
@Override
public ExecutorService getExecutor()
{
return this.executor;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getTransactionMode()
*/
@Override
public TransactionMode getTransactionMode()
{
return this.configuration.getTransactionMode();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#getStateManager()
*/
@Override
public StateManager getStateManager()
{
return this.stateManager;
}
@Override
public ThreadFactory getThreadFactory()
{
return this.configuration.getThreadFactory();
}
@Override
public Codec getCodec()
{
return this.codec;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isActive()
*/
@Override
public boolean isActive()
{
return this.active;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isCurrentDateEvaluationEnabled()
*/
@Override
public boolean isCurrentDateEvaluationEnabled()
{
return this.configuration.isCurrentDateEvaluationEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isCurrentTimeEvaluationEnabled()
*/
@Override
public boolean isCurrentTimeEvaluationEnabled()
{
return this.configuration.isCurrentTimeEvaluationEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isCurrentTimestampEvaluationEnabled()
*/
@Override
public boolean isCurrentTimestampEvaluationEnabled()
{
return this.configuration.isCurrentTimestampEvaluationEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isIdentityColumnDetectionEnabled()
*/
@Override
public boolean isIdentityColumnDetectionEnabled()
{
return this.configuration.isIdentityColumnDetectionEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isRandEvaluationEnabled()
*/
@Override
public boolean isRandEvaluationEnabled()
{
return this.configuration.isRandEvaluationEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#isSequenceDetectionEnabled()
*/
@Override
public boolean isSequenceDetectionEnabled()
{
return this.configuration.isSequenceDetectionEnabled();
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#removeConfigurationListener(net.sf.hajdbc.DatabaseClusterConfigurationListener)
*/
@Override
public void removeConfigurationListener(DatabaseClusterConfigurationListener<Z, D> listener)
{
this.configurationListeners.remove(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#removeListener(net.sf.hajdbc.DatabaseClusterListener)
*/
@Override
public void removeListener(DatabaseClusterListener listener)
{
this.clusterListeners.remove(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.DatabaseCluster#removeSynchronizationListener(net.sf.hajdbc.SynchronizationListener)
*/
@Override
public void removeSynchronizationListener(SynchronizationListener listener)
{
this.synchronizationListeners.remove(listener);
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.Lifecycle#start()
*/
@Override
public void start() throws Exception
{
if (this.active) return;
this.codec = this.configuration.getCodecFactory().createDecoder(System.getProperties());
this.lockManager = new SemaphoreLockManager();
this.stateManager = this.configuration.getStateManagerProvider().createStateManager(this, System.getProperties());
CommandDispatcherFactory dispatcherFactory = this.configuration.getDispatcherFactory();
if (dispatcherFactory != null)
{
this.lockManager = new DistributedLockManager(this, dispatcherFactory);
this.stateManager = new DistributedStateManager<Z, D>(this, dispatcherFactory);
}
this.balancer = this.configuration.getBalancerFactory().createBalancer(new TreeSet<D>());
this.dialect = this.configuration.getDialectFactory().createDialect();
this.durability = this.configuration.getDurabilityFactory().createDurability(this);
this.lockManager.start();
this.stateManager.start();
this.executor = this.configuration.getExecutorProvider().getExecutor(this.configuration.getThreadFactory());
Set<String> databaseSet = this.stateManager.getActiveDatabases();
if (!databaseSet.isEmpty())
{
for (String databaseId: databaseSet)
{
D database = this.getDatabase(databaseId);
if (database != null)
{
this.balancer.add(database);
}
else
{
- logger.log(Level.WARN, "{0}", database);
+ logger.log(Level.WARN, "{0} does not exist", databaseId);
}
}
}
else
{
for (D database: this.configuration.getDatabaseMap().values())
{
if (this.isAlive(database))
{
this.activate(database, this.stateManager);
}
}
}
Map<InvocationEvent, Map<String, InvokerEvent>> invokers = this.stateManager.recover();
this.durability.recover(invokers);
this.databaseMetaDataCache = this.configuration.getDatabaseMetaDataCacheFactory().createCache(this);
try
{
this.flushMetaDataCache();
}
catch (IllegalStateException e)
{
// Ignore - cache will initialize lazily.
}
CronExpression failureDetectionExpression = this.configuration.getFailureDetectionExpression();
CronExpression autoActivationExpression = this.configuration.getAutoActivationExpression();
int threads = requiredThreads(failureDetectionExpression) + requiredThreads(autoActivationExpression);
if (threads > 0)
{
this.cronExecutor = new CronThreadPoolExecutor(threads, this.configuration.getThreadFactory());
if (failureDetectionExpression != null)
{
this.cronExecutor.schedule(new FailureDetectionTask(), failureDetectionExpression);
}
if (autoActivationExpression != null)
{
this.cronExecutor.schedule(new AutoActivationTask(), autoActivationExpression);
}
}
this.active = true;
}
private static int requiredThreads(CronExpression expression)
{
return (expression != null) ? 1 : 0;
}
/**
* {@inheritDoc}
* @see net.sf.hajdbc.Lifecycle#stop()
*/
@Override
public void stop()
{
this.active = false;
if (this.executor != null)
{
this.executor.shutdownNow();
}
if (this.stateManager != null)
{
this.stateManager.stop();
}
if (this.lockManager != null)
{
this.lockManager.stop();
}
if (this.balancer != null)
{
this.balancer.clear();
}
if (this.cronExecutor != null)
{
this.cronExecutor.shutdownNow();
}
}
boolean isAlive(D database)
{
try
{
Connection connection = database.connect(database.createConnectionSource(), this.codec);
boolean alive = this.isAlive(connection);
connection.close();
return alive;
}
catch (SQLException e)
{
return false;
}
}
private boolean isAlive(Connection connection)
{
try
{
return connection.isValid(0);
}
catch (SQLException e)
{
// log
}
try
{
Statement statement = connection.createStatement();
try
{
statement.execute(this.dialect.getSimpleSQL());
return true;
}
finally
{
statement.close();
}
}
catch (SQLException e)
{
return false;
}
}
class FailureDetectionTask implements Runnable
{
@Override
public void run()
{
Set<D> databases = DatabaseClusterImpl.this.getBalancer();
int size = databases.size();
if (size > 1)
{
List<D> deadList = new ArrayList<D>(size);
for (D database: databases)
{
if (!DatabaseClusterImpl.this.isAlive(database))
{
deadList.add(database);
}
}
if (deadList.size() < size)
{
for (D database: deadList)
{
if (DatabaseClusterImpl.this.deactivate(database, DatabaseClusterImpl.this.getStateManager()))
{
logger.log(Level.ERROR, Messages.DATABASE_DEACTIVATED.getMessage(), database, DatabaseClusterImpl.this);
}
}
}
}
}
}
class AutoActivationTask implements Runnable
{
@Override
public void run()
{
Set<D> activeDatabases = DatabaseClusterImpl.this.getBalancer();
for (D database: DatabaseClusterImpl.this.configuration.getDatabaseMap().values())
{
if (!activeDatabases.contains(database))
{
if (DatabaseClusterImpl.this.activate(database, DatabaseClusterImpl.this.getStateManager()))
{
logger.log(Level.INFO, Messages.DATABASE_ACTIVATED.getMessage(), database, DatabaseClusterImpl.this);
}
}
}
}
}
}
| true | true | public void start() throws Exception
{
if (this.active) return;
this.codec = this.configuration.getCodecFactory().createDecoder(System.getProperties());
this.lockManager = new SemaphoreLockManager();
this.stateManager = this.configuration.getStateManagerProvider().createStateManager(this, System.getProperties());
CommandDispatcherFactory dispatcherFactory = this.configuration.getDispatcherFactory();
if (dispatcherFactory != null)
{
this.lockManager = new DistributedLockManager(this, dispatcherFactory);
this.stateManager = new DistributedStateManager<Z, D>(this, dispatcherFactory);
}
this.balancer = this.configuration.getBalancerFactory().createBalancer(new TreeSet<D>());
this.dialect = this.configuration.getDialectFactory().createDialect();
this.durability = this.configuration.getDurabilityFactory().createDurability(this);
this.lockManager.start();
this.stateManager.start();
this.executor = this.configuration.getExecutorProvider().getExecutor(this.configuration.getThreadFactory());
Set<String> databaseSet = this.stateManager.getActiveDatabases();
if (!databaseSet.isEmpty())
{
for (String databaseId: databaseSet)
{
D database = this.getDatabase(databaseId);
if (database != null)
{
this.balancer.add(database);
}
else
{
logger.log(Level.WARN, "{0}", database);
}
}
}
else
{
for (D database: this.configuration.getDatabaseMap().values())
{
if (this.isAlive(database))
{
this.activate(database, this.stateManager);
}
}
}
Map<InvocationEvent, Map<String, InvokerEvent>> invokers = this.stateManager.recover();
this.durability.recover(invokers);
this.databaseMetaDataCache = this.configuration.getDatabaseMetaDataCacheFactory().createCache(this);
try
{
this.flushMetaDataCache();
}
catch (IllegalStateException e)
{
// Ignore - cache will initialize lazily.
}
CronExpression failureDetectionExpression = this.configuration.getFailureDetectionExpression();
CronExpression autoActivationExpression = this.configuration.getAutoActivationExpression();
int threads = requiredThreads(failureDetectionExpression) + requiredThreads(autoActivationExpression);
if (threads > 0)
{
this.cronExecutor = new CronThreadPoolExecutor(threads, this.configuration.getThreadFactory());
if (failureDetectionExpression != null)
{
this.cronExecutor.schedule(new FailureDetectionTask(), failureDetectionExpression);
}
if (autoActivationExpression != null)
{
this.cronExecutor.schedule(new AutoActivationTask(), autoActivationExpression);
}
}
this.active = true;
}
| public void start() throws Exception
{
if (this.active) return;
this.codec = this.configuration.getCodecFactory().createDecoder(System.getProperties());
this.lockManager = new SemaphoreLockManager();
this.stateManager = this.configuration.getStateManagerProvider().createStateManager(this, System.getProperties());
CommandDispatcherFactory dispatcherFactory = this.configuration.getDispatcherFactory();
if (dispatcherFactory != null)
{
this.lockManager = new DistributedLockManager(this, dispatcherFactory);
this.stateManager = new DistributedStateManager<Z, D>(this, dispatcherFactory);
}
this.balancer = this.configuration.getBalancerFactory().createBalancer(new TreeSet<D>());
this.dialect = this.configuration.getDialectFactory().createDialect();
this.durability = this.configuration.getDurabilityFactory().createDurability(this);
this.lockManager.start();
this.stateManager.start();
this.executor = this.configuration.getExecutorProvider().getExecutor(this.configuration.getThreadFactory());
Set<String> databaseSet = this.stateManager.getActiveDatabases();
if (!databaseSet.isEmpty())
{
for (String databaseId: databaseSet)
{
D database = this.getDatabase(databaseId);
if (database != null)
{
this.balancer.add(database);
}
else
{
logger.log(Level.WARN, "{0} does not exist", databaseId);
}
}
}
else
{
for (D database: this.configuration.getDatabaseMap().values())
{
if (this.isAlive(database))
{
this.activate(database, this.stateManager);
}
}
}
Map<InvocationEvent, Map<String, InvokerEvent>> invokers = this.stateManager.recover();
this.durability.recover(invokers);
this.databaseMetaDataCache = this.configuration.getDatabaseMetaDataCacheFactory().createCache(this);
try
{
this.flushMetaDataCache();
}
catch (IllegalStateException e)
{
// Ignore - cache will initialize lazily.
}
CronExpression failureDetectionExpression = this.configuration.getFailureDetectionExpression();
CronExpression autoActivationExpression = this.configuration.getAutoActivationExpression();
int threads = requiredThreads(failureDetectionExpression) + requiredThreads(autoActivationExpression);
if (threads > 0)
{
this.cronExecutor = new CronThreadPoolExecutor(threads, this.configuration.getThreadFactory());
if (failureDetectionExpression != null)
{
this.cronExecutor.schedule(new FailureDetectionTask(), failureDetectionExpression);
}
if (autoActivationExpression != null)
{
this.cronExecutor.schedule(new AutoActivationTask(), autoActivationExpression);
}
}
this.active = true;
}
|
diff --git a/src/com/android/launcher2/LauncherAppWidgetHost.java b/src/com/android/launcher2/LauncherAppWidgetHost.java
index 75a9940c..29ffe6ed 100644
--- a/src/com/android/launcher2/LauncherAppWidgetHost.java
+++ b/src/com/android/launcher2/LauncherAppWidgetHost.java
@@ -1,43 +1,43 @@
/*
* Copyright (C) 2009 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.launcher2;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
/**
* Specific {@link AppWidgetHost} that creates our {@link LauncherAppWidgetHostView}
* which correctly captures all long-press events. This ensures that users can
* always pick up and move widgets.
*/
public class LauncherAppWidgetHost extends AppWidgetHost {
public LauncherAppWidgetHost(Context context, int hostId) {
super(context, hostId);
}
@Override
protected AppWidgetHostView onCreateView(Context context, int appWidgetId,
AppWidgetProviderInfo appWidget) {
if (LauncherApplication.isScreenXLarge()) {
return new DimmableAppWidgetHostView(context);
} else {
- return new AppWidgetHostView(context);
+ return new LauncherAppWidgetHostView(context);
}
}
}
| true | true | protected AppWidgetHostView onCreateView(Context context, int appWidgetId,
AppWidgetProviderInfo appWidget) {
if (LauncherApplication.isScreenXLarge()) {
return new DimmableAppWidgetHostView(context);
} else {
return new AppWidgetHostView(context);
}
}
| protected AppWidgetHostView onCreateView(Context context, int appWidgetId,
AppWidgetProviderInfo appWidget) {
if (LauncherApplication.isScreenXLarge()) {
return new DimmableAppWidgetHostView(context);
} else {
return new LauncherAppWidgetHostView(context);
}
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/cover/LocalCover.java b/MPDroid/src/com/namelessdev/mpdroid/cover/LocalCover.java
index daa0a9e9..6a42a122 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/cover/LocalCover.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/cover/LocalCover.java
@@ -1,72 +1,75 @@
package com.namelessdev.mpdroid.cover;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import com.namelessdev.mpdroid.MPDApplication;
public class LocalCover implements ICoverRetriever {
private final static String URL = "%s/%s/%s";
private final static String URL_PREFIX = "http://";
private final static String PLACEHOLDER_FILENAME = "%placeholder_filename";
// Note that having two PLACEHOLDER_FILENAME is on purpose
private final static String[] FILENAMES = new String[] { "%placeholder_custom", PLACEHOLDER_FILENAME, PLACEHOLDER_FILENAME,
"cover.jpg", "folder.jpg", "front.jpg", "cover.png", "front.png", "folder.png", };
private MPDApplication app = null;
private SharedPreferences settings = null;
public LocalCover(MPDApplication app, SharedPreferences settings) {
this.app = app;
this.settings = settings;
}
public String[] getCoverUrl(String artist, String album, String path, String filename) throws Exception {
// load URL parts from settings
String musicPath = settings.getString("musicPath", "music/");
FILENAMES[0] = settings.getString("coverFileName", null);
if (musicPath != null) {
// load server name/ip
final String serverName = app.oMPDAsyncHelper.getConnectionSettings().sServer;
String url;
final List<String> urls = new ArrayList<String>();
boolean secondFilenamePlaceholder = false;
for (String lfilename : FILENAMES) {
if (lfilename == null || (lfilename.startsWith("%") && !lfilename.equals(PLACEHOLDER_FILENAME)))
continue;
if (lfilename.equals(PLACEHOLDER_FILENAME)) {
final int dotIndex = filename.lastIndexOf('.');
if (dotIndex == -1)
continue;
lfilename = filename.substring(0, dotIndex) + (secondFilenamePlaceholder ? ".png" : ".jpg");
secondFilenamePlaceholder = true;
}
url = String.format(URL, new Object[] { musicPath, path.replaceAll(" ", "%20"), lfilename });
url = musicPath.toLowerCase().startsWith(URL_PREFIX) ? url : (URL_PREFIX + serverName + "/" + url);
+ while (url.lastIndexOf("//") != -1) {
+ url = url.replace("//", "/");
+ }
if (!urls.contains(url))
urls.add(url);
}
return urls.toArray(new String[urls.size()]);
} else {
return null;
}
}
@Override
public boolean isCoverLocal() {
return false;
}
@Override
public String getName() {
return "User's HTTP Server";
}
}
| true | true | public String[] getCoverUrl(String artist, String album, String path, String filename) throws Exception {
// load URL parts from settings
String musicPath = settings.getString("musicPath", "music/");
FILENAMES[0] = settings.getString("coverFileName", null);
if (musicPath != null) {
// load server name/ip
final String serverName = app.oMPDAsyncHelper.getConnectionSettings().sServer;
String url;
final List<String> urls = new ArrayList<String>();
boolean secondFilenamePlaceholder = false;
for (String lfilename : FILENAMES) {
if (lfilename == null || (lfilename.startsWith("%") && !lfilename.equals(PLACEHOLDER_FILENAME)))
continue;
if (lfilename.equals(PLACEHOLDER_FILENAME)) {
final int dotIndex = filename.lastIndexOf('.');
if (dotIndex == -1)
continue;
lfilename = filename.substring(0, dotIndex) + (secondFilenamePlaceholder ? ".png" : ".jpg");
secondFilenamePlaceholder = true;
}
url = String.format(URL, new Object[] { musicPath, path.replaceAll(" ", "%20"), lfilename });
url = musicPath.toLowerCase().startsWith(URL_PREFIX) ? url : (URL_PREFIX + serverName + "/" + url);
if (!urls.contains(url))
urls.add(url);
}
return urls.toArray(new String[urls.size()]);
} else {
return null;
}
}
| public String[] getCoverUrl(String artist, String album, String path, String filename) throws Exception {
// load URL parts from settings
String musicPath = settings.getString("musicPath", "music/");
FILENAMES[0] = settings.getString("coverFileName", null);
if (musicPath != null) {
// load server name/ip
final String serverName = app.oMPDAsyncHelper.getConnectionSettings().sServer;
String url;
final List<String> urls = new ArrayList<String>();
boolean secondFilenamePlaceholder = false;
for (String lfilename : FILENAMES) {
if (lfilename == null || (lfilename.startsWith("%") && !lfilename.equals(PLACEHOLDER_FILENAME)))
continue;
if (lfilename.equals(PLACEHOLDER_FILENAME)) {
final int dotIndex = filename.lastIndexOf('.');
if (dotIndex == -1)
continue;
lfilename = filename.substring(0, dotIndex) + (secondFilenamePlaceholder ? ".png" : ".jpg");
secondFilenamePlaceholder = true;
}
url = String.format(URL, new Object[] { musicPath, path.replaceAll(" ", "%20"), lfilename });
url = musicPath.toLowerCase().startsWith(URL_PREFIX) ? url : (URL_PREFIX + serverName + "/" + url);
while (url.lastIndexOf("//") != -1) {
url = url.replace("//", "/");
}
if (!urls.contains(url))
urls.add(url);
}
return urls.toArray(new String[urls.size()]);
} else {
return null;
}
}
|
diff --git a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
index 774ef50b..f1353438 100644
--- a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
+++ b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
@@ -1,453 +1,451 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.internal.ide.ui.builders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.common.internal.utils.AcceleoPackageRegistry;
import org.eclipse.acceleo.ide.ui.AcceleoUIActivator;
import org.eclipse.acceleo.ide.ui.resources.AcceleoProject;
import org.eclipse.acceleo.internal.ide.ui.AcceleoUIMessages;
import org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoMainClass;
import org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleowizardmodelFactory;
import org.eclipse.acceleo.internal.ide.ui.builders.runner.CreateRunnableAcceleoOperation;
import org.eclipse.acceleo.internal.ide.ui.generators.AcceleoUIGenerator;
import org.eclipse.acceleo.internal.parser.cst.utils.FileContent;
import org.eclipse.acceleo.internal.parser.cst.utils.Sequence;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
/**
* The builder compiles the Acceleo templates in a background task. Compilation errors are put in the problems
* view when it is necessary.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
*/
public class AcceleoBuilder extends IncrementalProjectBuilder {
/**
* The builder ID.
*/
public static final String BUILDER_ID = "org.eclipse.acceleo.ide.ui.acceleoBuilder"; //$NON-NLS-1$
/**
* The output folder to ignore.
*/
private IPath outputFolder;
/**
* Constructor.
*/
public AcceleoBuilder() {
super();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IncrementalProjectBuilder#build(int, java.util.Map,
* org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
@SuppressWarnings("rawtypes")
protected IProject[] build(int kind, Map arguments, IProgressMonitor monitor) throws CoreException {
if (getProject() == null || !getProject().isAccessible()) {
return new IProject[] {};
}
outputFolder = getOutputFolder(getProject());
try {
if (kind == FULL_BUILD) {
clean(monitor);
fullBuild(monitor);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
clean(monitor);
fullBuild(monitor);
} else {
incrementalBuild(delta, monitor);
}
}
} catch (OperationCanceledException e) {
// We've only thrown this to cancel everything, stop propagation
} finally {
outputFolder = null;
}
return null;
}
/**
* It does a full build.
*
* @param monitor
* is the progress monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
protected void fullBuild(IProgressMonitor monitor) throws CoreException {
List<IFile> filesOutput = new ArrayList<IFile>();
AcceleoBuilderUtils.members(filesOutput, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
if (filesOutput.size() > 0) {
Collections.sort(filesOutput, new Comparator<IFile>() {
public int compare(IFile arg0, IFile arg1) {
long m0 = arg0.getLocation().toFile().lastModified();
long m1 = arg1.getLocation().toFile().lastModified();
if (m0 < m1) {
return 1;
}
return -1;
}
});
registerAccessibleEcoreFiles();
IFile[] files = filesOutput.toArray(new IFile[filesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, false);
compileOperation.run(monitor);
validateAcceleoBuildFile(monitor);
}
}
/**
* Register the accessible workspace ecore files.
*
* @throws CoreException
* when an issue occurs
*/
private void registerAccessibleEcoreFiles() throws CoreException {
List<IFile> ecoreFiles = new ArrayList<IFile>();
AcceleoProject acceleoProject = new AcceleoProject(getProject());
for (IProject project : acceleoProject.getRecursivelyAccessibleProjects()) {
if (project.isAccessible()) {
AcceleoBuilderUtils.members(ecoreFiles, project, "ecore", outputFolder); //$NON-NLS-1$
}
}
for (IFile ecoreFile : ecoreFiles) {
AcceleoPackageRegistry.INSTANCE.registerEcorePackages(ecoreFile.getFullPath().toString(),
AcceleoPackageRegistry.DYNAMIC_METAMODEL_RESOURCE_SET);
}
}
/**
* It checks the build configuration of the Acceleo module. It creates the build.acceleo file and the
* build.xml file if they don't exist.
*
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
- if (outputFolder != null && outputFolder.segmentCount() > 1) {
+ if (outputFolder != null && outputFolder.segmentCount() >= 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
- AcceleoUIGenerator
- .getDefault()
- .generateBuildXML(
- acceleoMainClass,
- AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
- getProject().getFile("buildstandalone.xml").getLocation()).toString(), //$NON-NLS-1$
- AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
- getProject().getFile("buildstandalone.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
+ AcceleoUIGenerator.getDefault().generateBuildXML(
+ acceleoMainClass,
+ AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile, getProject().getLocation())
+ .toString(),
+ AcceleoProject.makeRelativeTo(workspacePathRelativeToFile, getProject().getLocation())
+ .toString(), getProject());
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
/**
* It does an incremental build.
*
* @param delta
* is the resource delta
* @param monitor
* is the progress monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException {
List<IFile> deltaFilesOutput = new ArrayList<IFile>();
deltaMembers(deltaFilesOutput, delta, monitor);
if (deltaFilesOutput.size() > 0) {
boolean containsManifest = false;
for (int i = 0; !containsManifest && i < deltaFilesOutput.size(); i++) {
containsManifest = "MANIFEST.MF".equals(deltaFilesOutput.get(i).getName()); //$NON-NLS-1$
}
if (containsManifest) {
deltaFilesOutput.clear();
AcceleoBuilderUtils.members(deltaFilesOutput, getProject(),
IAcceleoConstants.MTL_FILE_EXTENSION, outputFolder);
} else {
computeOtherFilesToBuild(deltaFilesOutput);
}
} else {
computeOtherFilesToBuild(deltaFilesOutput);
}
if (deltaFilesOutput.size() > 0) {
Collections.sort(deltaFilesOutput, new Comparator<IFile>() {
public int compare(IFile arg0, IFile arg1) {
long m0 = arg0.getLocation().toFile().lastModified();
long m1 = arg1.getLocation().toFile().lastModified();
if (m0 < m1) {
return 1;
}
return -1;
}
});
registerAccessibleEcoreFiles();
IFile[] files = deltaFilesOutput.toArray(new IFile[deltaFilesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, false);
compileOperation.run(monitor);
validateAcceleoBuildFile(monitor);
} else {
// We have deleted a file, let's build the whole project.
IResourceDelta[] affectedChildren = delta.getAffectedChildren();
if (affectedChildren.length == 2 && affectedChildren[0].getResource() instanceof IFolder
&& affectedChildren[1].getResource() instanceof IFolder) {
this.fullBuild(monitor);
}
}
}
/**
* Gets also the files that depend of the templates to build.
*
* @param deltaFiles
* is an output parameter to get all the templates to build
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void computeOtherFilesToBuild(List<IFile> deltaFiles) throws CoreException {
AcceleoProject acceleoProject = new AcceleoProject(getProject());
List<IFile> otherTemplates = new ArrayList<IFile>();
AcceleoBuilderUtils.members(otherTemplates, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
List<Sequence> importSequencesToSearch = new ArrayList<Sequence>();
for (int i = 0; i < deltaFiles.size(); i++) {
IFile deltaFile = deltaFiles.get(i);
if (IAcceleoConstants.MTL_FILE_EXTENSION.equals(deltaFile.getFileExtension())) {
importSequencesToSearch.addAll(AcceleoBuilderUtils.getImportSequencesToSearch(acceleoProject,
deltaFile));
otherTemplates.remove(deltaFile);
}
}
List<IFile> otherTemplatesToBuild = getOtherTemplatesToBuild(acceleoProject, otherTemplates,
importSequencesToSearch);
while (otherTemplatesToBuild.size() > 0) {
for (int i = 0; i < otherTemplatesToBuild.size(); i++) {
IFile otherTemplateToBuild = otherTemplatesToBuild.get(i);
otherTemplates.remove(otherTemplateToBuild);
if (!deltaFiles.contains(otherTemplateToBuild)) {
deltaFiles.add(otherTemplateToBuild);
importSequencesToSearch.addAll(AcceleoBuilderUtils.getImportSequencesToSearch(
acceleoProject, otherTemplateToBuild));
}
}
otherTemplatesToBuild = getOtherTemplatesToBuild(acceleoProject, otherTemplates,
importSequencesToSearch);
}
}
/**
* Gets the files that import the given dependencies.
*
* @param acceleoProject
* is the project
* @param otherTemplates
* are the other templates that we can decide to build
* @param importSequencesToSearch
* are the dependencies to detect in the "import" section of the other templates
* @return the other templates to build
*/
private List<IFile> getOtherTemplatesToBuild(AcceleoProject acceleoProject, List<IFile> otherTemplates,
List<Sequence> importSequencesToSearch) {
List<IFile> result = new ArrayList<IFile>();
for (int i = 0; i < otherTemplates.size(); i++) {
IFile otherTemplate = otherTemplates.get(i);
IPath outputPath = acceleoProject.getOutputFilePath(otherTemplate);
if (outputPath != null && !getProject().getFile(outputPath.removeFirstSegments(1)).exists()) {
result.add(otherTemplate);
} else {
StringBuffer otherTemplateContent = FileContent.getFileContent(otherTemplate.getLocation()
.toFile());
for (int j = 0; j < importSequencesToSearch.size(); j++) {
Sequence importSequence = importSequencesToSearch.get(j);
if (importSequence.search(otherTemplateContent).b() > -1) {
result.add(otherTemplate);
}
}
}
}
return result;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IncrementalProjectBuilder#clean(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
super.clean(monitor);
List<IFile> filesOutput = new ArrayList<IFile>();
AcceleoBuilderUtils.members(filesOutput, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
if (filesOutput.size() > 0) {
IFile[] files = filesOutput.toArray(new IFile[filesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, true);
compileOperation.run(monitor);
}
}
/**
* Computes a list of all the modified files (Acceleo files only).
*
* @param deltaFilesOutput
* an output parameter to get all the modified files
* @param delta
* the resource delta represents changes in the state of a resource tree
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void deltaMembers(List<IFile> deltaFilesOutput, IResourceDelta delta, IProgressMonitor monitor)
throws CoreException {
if (delta != null) {
IResource resource = delta.getResource();
if (resource instanceof IFile) {
if (delta.getKind() == IResourceDelta.REMOVED
&& IAcceleoConstants.MTL_FILE_EXTENSION.equals(resource.getFileExtension())) {
removeOutputFile((IFile)resource, monitor);
}
if (delta.getKind() != IResourceDelta.REMOVED
&& (IAcceleoConstants.MTL_FILE_EXTENSION.equals(resource.getFileExtension()) || "MANIFEST.MF" //$NON-NLS-1$
.equals(resource.getName()))) {
deltaFilesOutput.add((IFile)resource);
}
} else {
if (outputFolder == null || !outputFolder.isPrefixOf(resource.getFullPath())) {
IResourceDelta[] children = delta.getAffectedChildren();
for (int i = 0; i < children.length; i++) {
deltaMembers(deltaFilesOutput, children[i], monitor);
}
}
}
}
}
/**
* Removes the output file that corresponding to the input file.
*
* @param inputFile
* is the input file ('.acceleo')
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void removeOutputFile(IFile inputFile, IProgressMonitor monitor) throws CoreException {
AcceleoProject acceleoProject = new AcceleoProject(getProject());
IPath outputPath = acceleoProject.getOutputFilePath(inputFile);
IResource outputFile = ResourcesPlugin.getWorkspace().getRoot().findMember(outputPath);
if (outputFile instanceof IFile && outputFile.isAccessible()) {
outputFile.delete(true, monitor);
}
}
/**
* Gets the output folder of the project. For example : '/MyProject/bin'.
*
* @param aProject
* is a project of the workspace
* @return the output folder of the project, or null if it doesn't exist
*/
private IPath getOutputFolder(IProject aProject) {
final IJavaProject javaProject = JavaCore.create(aProject);
try {
IPath output = javaProject.getOutputLocation();
if (output != null && output.segmentCount() > 1) {
IFolder folder = aProject.getWorkspace().getRoot().getFolder(output);
if (folder.isAccessible()) {
return folder.getFullPath();
}
}
} catch (JavaModelException e) {
// continue
AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
}
return null;
}
}
| false | true | private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
if (outputFolder != null && outputFolder.segmentCount() > 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
AcceleoUIGenerator
.getDefault()
.generateBuildXML(
acceleoMainClass,
AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
getProject().getFile("buildstandalone.xml").getLocation()).toString(), //$NON-NLS-1$
AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
getProject().getFile("buildstandalone.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
| private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
if (outputFolder != null && outputFolder.segmentCount() >= 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
AcceleoUIGenerator.getDefault().generateBuildXML(
acceleoMainClass,
AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile, getProject().getLocation())
.toString(),
AcceleoProject.makeRelativeTo(workspacePathRelativeToFile, getProject().getLocation())
.toString(), getProject());
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
|
diff --git a/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java b/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java
index 7fbc35260..51a55dd7a 100644
--- a/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java
+++ b/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java
@@ -1,1002 +1,1003 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* 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 grails.orm;
import groovy.lang.*;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.AssociationType;
import org.hibernate.type.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.util.*;
/**
* <p>Wraps the Hibernate Criteria API in a builder. The builder can be retrieved through the "createCriteria()" dynamic static
* method of Grails domain classes (Example in Groovy):
*
* <pre>
* def c = Account.createCriteria()
* def results = c {
* projections {
* groupProperty("branch")
* }
* like("holderFirstName", "Fred%")
* and {
* between("balance", 500, 1000)
* eq("branch", "London")
* }
* maxResults(10)
* order("holderLastName", "desc")
* }
* </pre>
*
* <p>The builder can also be instantiated standalone with a SessionFactory and persistent Class instance:
*
* <pre>
* new HibernateCriteriaBuilder(clazz, sessionFactory).list {
* eq("firstName", "Fred")
* }
* </pre>
*
* @author Graeme Rocher
* @since Oct 10, 2005
*/
public class HibernateCriteriaBuilder extends GroovyObjectSupport {
public static final String AND = "and"; // builder
public static final String IS_NULL = "isNull"; // builder
public static final String IS_NOT_NULL = "isNotNull"; // builder
public static final String NOT = "not";// builder
public static final String OR = "or"; // builder
public static final String ID_EQUALS = "idEq"; // builder
public static final String IS_EMPTY = "isEmpty"; //builder
public static final String IS_NOT_EMPTY = "isNotEmpty"; //builder
public static final String BETWEEN = "between";//method
public static final String EQUALS = "eq";//method
public static final String EQUALS_PROPERTY = "eqProperty";//method
public static final String GREATER_THAN = "gt";//method
public static final String GREATER_THAN_PROPERTY = "gtProperty";//method
public static final String GREATER_THAN_OR_EQUAL = "ge";//method
public static final String GREATER_THAN_OR_EQUAL_PROPERTY = "geProperty";//method
public static final String ILIKE = "ilike";//method
public static final String IN = "in";//method
public static final String LESS_THAN = "lt"; //method
public static final String LESS_THAN_PROPERTY = "ltProperty";//method
public static final String LESS_THAN_OR_EQUAL = "le";//method
public static final String LESS_THAN_OR_EQUAL_PROPERTY = "leProperty";//method
public static final String LIKE = "like";//method
public static final String NOT_EQUAL = "ne";//method
public static final String NOT_EQUAL_PROPERTY = "neProperty";//method
public static final String SIZE_EQUALS = "sizeEq"; //method
public static final String ORDER_DESCENDING = "desc";
public static final String ORDER_ASCENDING = "asc";
private static final String ROOT_DO_CALL = "doCall";
private static final String ROOT_CALL = "call";
private static final String LIST_CALL = "list";
private static final String LIST_DISTINCT_CALL = "listDistinct";
private static final String COUNT_CALL = "count";
private static final String GET_CALL = "get";
private static final String SCROLL_CALL = "scroll";
private static final String PROJECTIONS = "projections";
private SessionFactory sessionFactory;
private Session session;
private Class targetClass;
private Criteria criteria;
private MetaClass criteriaMetaClass;
private boolean uniqueResult = false;
private Stack logicalExpressionStack = new Stack();
private Stack associationStack = new Stack();
private boolean participate;
private boolean scroll;
private boolean count;
private ProjectionList projectionList;
private BeanWrapper targetBean;
private List aliasStack = new ArrayList();
private static final String ALIAS = "_alias";
private ResultTransformer resultTransformer;
public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory) {
super();
this.targetClass = targetClass;
this.targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass));
this.sessionFactory = sessionFactory;
}
public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory, boolean uniqueResult) {
super();
this.targetClass = targetClass;
this.sessionFactory = sessionFactory;
this.uniqueResult = uniqueResult;
}
public void setUniqueResult(boolean uniqueResult) {
this.uniqueResult = uniqueResult;
}
/**
* A projection that selects a property name
* @param propertyName The name of the property
*/
public void property(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [property] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.property(propertyName));
}
}
/**
* A projection that selects a distince property name
* @param propertyName The property name
*/
public void distinct(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.distinct(Projections.property(propertyName)));
}
}
/**
* A distinct projection that takes a list
*
* @param propertyNames The list of distince property names
*/
public void distinct(Collection propertyNames) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node"));
}
else {
ProjectionList list = Projections.projectionList();
for (Iterator i = propertyNames.iterator(); i.hasNext();) {
Object o = i.next();
list.add(Projections.property(o.toString()));
}
this.projectionList.add(Projections.distinct(list));
}
}
/**
* Adds a projection that allows the criteria to return the property average value
*
* @param propertyName The name of the property
*/
public void avg(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [avg] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.avg(propertyName));
}
}
/**
* Calculates the property name including any alias paths
*
* @param propertyName The property name
* @return The calculated property name
*/
private String calculatePropertyName(String propertyName) {
if(this.aliasStack.size()>0) {
return this.aliasStack.get(this.aliasStack.size()-1).toString()+'.'+propertyName;
}
return propertyName;
}
/**
* Calculates the property value, converting GStrings if necessary
*
* @param propertyValue The property value
* @return The calculated property value
*/
private Object calculatePropertyValue(Object propertyValue) {
if(propertyValue instanceof GString) {
return propertyValue.toString();
}
return propertyValue;
}
/**
* Adds a projection that allows the criteria to return the property count
*
* @param propertyName The name of the property
*/
public void count(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [count] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.count(propertyName));
}
}
/**
* Adds a projection that allows the criteria to return the distinct property count
*
* @param propertyName The name of the property
*/
public void countDistinct(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [countDistinct] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.countDistinct(propertyName));
}
}
/**
* Adds a projection that allows the criteria's result to be grouped by a property
*
* @param propertyName The name of the property
*/
public void groupProperty(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [groupProperty] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.groupProperty(propertyName));
}
}
/**
* Adds a projection that allows the criteria to retrieve a maximum property value
*
* @param propertyName The name of the property
*/
public void max(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [max] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.max(propertyName));
}
}
/**
* Adds a projection that allows the criteria to retrieve a minimum property value
*
* @param propertyName The name of the property
*/
public void min(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [min] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.min(propertyName));
}
}
/**
* Adds a projection that allows the criteria to return the row count
*
*/
public void rowCount() {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [rowCount] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.rowCount());
}
}
/**
* Adds a projection that allows the criteria to retrieve the sum of the results of a property
*
* @param propertyName The name of the property
*/
public void sum(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [sum] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.sum(propertyName));
}
}
/**
* Sets the fetch mode of an associated path
*
* @param associationPath The name of the associated path
* @param fetchMode The fetch mode to set
*/
public void fetchMode(String associationPath, FetchMode fetchMode) {
if(criteria!=null) {
criteria.setFetchMode(associationPath, fetchMode);
}
}
/**
* Sets the resultTransformer.
* @param resultTransformer The result transformer to use.
*/
public void resultTransformer(ResultTransformer resultTransformer) {
if (criteria == null) {
throwRuntimeException( new IllegalArgumentException("Call to [resultTransformer] not supported here"));
}
this.resultTransformer = resultTransformer;
}
/**
* Creates a Criterion that compares to class properties for equality
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object eqProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [eqProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.") );
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.eqProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that compares to class properties for !equality
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object neProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [neProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.neProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is greater than the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object gtProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [gtProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.gtProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is greater than or equal to the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object geProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [geProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.geProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is less than the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object ltProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ltProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.ltProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is less than or equal to the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object leProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [leProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.leProperty(propertyName, otherPropertyName));
}
/**
* Creates a "greater than" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object gt(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [gt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.gt(propertyName, propertyValue));
}
/**
* Creates a "greater than or equal to" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object ge(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ge] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ge(propertyName, propertyValue));
}
/**
* Creates a "less than" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object lt(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [lt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.lt(propertyName, propertyValue));
}
/**
* Creates a "less than or equal to" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object le(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [le] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.le(propertyName, propertyValue));
}
/**
* Creates an "equals" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
*
* @return A Criterion instance
*/
public Object eq(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [eq] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.eq(propertyName, propertyValue));
}
/**
* Creates a Criterion with from the specified property name and "like" expression
* @param propertyName The property name
* @param propertyValue The like value
*
* @return A Criterion instance
*/
public Object like(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [like] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.like(propertyName, propertyValue));
}
/**
* Creates a Criterion with from the specified property name and "ilike" (a case sensitive version of "like") expression
* @param propertyName The property name
* @param propertyValue The ilike value
*
* @return A Criterion instance
*/
public Object ilike(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ilike] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ilike(propertyName, propertyValue));
}
/**
* Applys a "in" contrain on the specified property
* @param propertyName The property name
* @param values A collection of values
*
* @return A Criterion instance
*/
public Object in(String propertyName, Collection values) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.in(propertyName, values));
}
/**
* Delegates to in as in is a Groovy keyword
**/
public Object inList(String propertyName, Collection values) {
return in(propertyName, values);
}
/**
* Delegates to in as in is a Groovy keyword
**/
public Object inList(String propertyName, Object[] values) {
return in(propertyName, values);
}
/**
* Applys a "in" contrain on the specified property
* @param propertyName The property name
* @param values A collection of values
*
* @return A Criterion instance
*/
public Object in(String propertyName, Object[] values) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.in(propertyName, values));
}
/**
* Orders by the specified property name (defaults to ascending)
*
* @param propertyName The property name to order by
* @return A Order instance
*/
public Object order(String propertyName) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here."));
propertyName = calculatePropertyName(propertyName);
Order o = Order.asc(propertyName);
this.criteria.addOrder(o);
return o;
}
/**
* Orders by the specified property name and direction
*
* @param propertyName The property name to order by
* @param direction Either "asc" for ascending or "desc" for descending
*
* @return A Order instance
*/
public Object order(String propertyName, String direction) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here."));
propertyName = calculatePropertyName(propertyName);
Order o;
if(direction.equals( ORDER_DESCENDING )) {
o = Order.desc(propertyName);
}
else {
o = Order.asc(propertyName);
}
this.criteria.addOrder(o);
return o;
}
/**
* Creates a Criterion that contrains a collection property by size
*
* @param propertyName The property name
* @param size The size to constrain by
*
* @return A Criterion instance
*/
public Object sizeEq(String propertyName, int size) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.sizeEq(propertyName, size));
}
/**
* Creates a "not equal" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return The criterion object
*/
public Object ne(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ne] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ne(propertyName, propertyValue));
}
public Object notEqual(String propertyName, Object propertyValue) {
return ne(propertyName, propertyValue);
}
/**
* Creates a "between" Criterion based on the property name and specified lo and hi values
* @param propertyName The property name
* @param lo The low value
* @param hi The high value
* @return A Criterion instance
*/
public Object between(String propertyName, Object lo, Object hi) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [between] with propertyName ["+propertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.between(propertyName, lo, hi));
}
private boolean validateSimpleExpression() {
if(this.criteria == null) {
return false;
}
return true;
}
public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
// Calculate how many results there are in total. This has been
// moved to before the 'list()' invocation to avoid any "ORDER
// BY" clause added by 'populateArgumentsForCriteria()', otherwise
// an exception is thrown for non-string sort fields (GRAILS-2690).
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
// Drop the projection, add settings for the pagination parameters,
// and then execute the query.
this.criteria.setProjection(null);
+ this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
// Updated the paged results with the total number of records
// calculated previously.
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
invokeClosureNode(args[0]);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
invokeClosureNode(args[0]);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass());
Type type = meta.getPropertyType(name.toString());
if (type.isAssociationType()) {
String otherSideEntityName =
((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
Class oldTargetClass = targetClass;
targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO);
BeanWrapper oldTargetBean = targetBean;
targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass));
associationStack.push(name.toString());
String newAlias = name.toString() + ALIAS + aliasStack.size();
StringBuffer fullPath = new StringBuffer();
for (Iterator i = associationStack.iterator(); i.hasNext();) {
String propertyName = (String) i.next();
if(fullPath.length() > 0 ) fullPath.append(".");
fullPath.append(propertyName);
}
this.criteria.createAlias(fullPath.toString(), newAlias, CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(newAlias);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
invokeClosureNode(args[0]);
aliasStack.remove(aliasStack.size() - 1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
associationStack.pop();
targetClass = oldTargetClass;
targetBean = oldTargetBean;
return name;
}
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
String propertyName = calculatePropertyName((String)value);
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( propertyName ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( propertyName );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( propertyName );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty(propertyName );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
private boolean isCriteriaConstructionMethod(String name, Object[] args) {
return (name.equals(LIST_CALL) && args.length == 2 && args[0] instanceof Map && args[1] instanceof Closure) ||
(name.equals(ROOT_CALL) ||
name.equals(ROOT_DO_CALL) ||
name.equals(LIST_CALL) ||
name.equals(LIST_DISTINCT_CALL) ||
name.equals(GET_CALL) ||
name.equals(COUNT_CALL) ||
name.equals(SCROLL_CALL) && args.length == 1 && args[0] instanceof Closure);
}
private void createCriteriaInstance() {
if(TransactionSynchronizationManager.hasResource(sessionFactory)) {
this.participate = true;
this.session = ((SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
}
else {
this.session = sessionFactory.openSession();
}
this.criteria = this.session.createCriteria(targetClass);
this.criteriaMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(criteria.getClass());
}
private void invokeClosureNode(Object args) {
Closure callable = (Closure)args;
callable.setDelegate(this);
callable.call();
}
/**
* Throws a runtime exception where necessary to ensure the session gets closed
*/
private void throwRuntimeException(RuntimeException t) {
closeSessionFollowingException();
throw t;
}
private void closeSessionFollowingException() {
if(this.session != null && this.session.isOpen() && !this.participate) {
this.session.close();
}
if(this.criteria != null) {
this.criteria = null;
}
}
/**
* adds and returns the given criterion to the currently active criteria set.
* this might be either the root criteria or a currently open
* LogicalExpression.
*/
private Criterion addToCriteria(Criterion c) {
if (!logicalExpressionStack.isEmpty()) {
((LogicalExpression) logicalExpressionStack.peek()).args.add(c);
}
else {
this.criteria.add(c);
}
return c;
}
/**
* instances of this class are pushed onto the logicalExpressionStack
* to represent all the unfinished "and", "or", and "not" expressions.
*/
private class LogicalExpression {
final Object name;
final ArrayList args = new ArrayList();
LogicalExpression(Object name) {
this.name = name;
}
Criterion toCriterion() {
if (name.equals(NOT)) {
switch (args.size()) {
case 0:
throwRuntimeException(new IllegalArgumentException("Logical expression [not] must contain at least 1 expression"));
return null;
case 1:
return Restrictions.not((Criterion) args.get(0));
default:
// treat multiple sub-criteria as an implicit "OR"
return Restrictions.not(buildJunction(Restrictions.disjunction(), args));
}
}
else if (name.equals(AND)) {
return buildJunction(Restrictions.conjunction(), args);
}
else if (name.equals(OR)) {
return buildJunction(Restrictions.disjunction(), args);
}
else {
throwRuntimeException(new IllegalStateException("Logical expression [" + name + "] not handled!"));
return null;
}
}
// add the Criterion objects in the given list to the given junction.
Junction buildJunction(Junction junction, List criteria) {
for (Iterator i = criteria.iterator(); i.hasNext();) {
junction.add((Criterion) i.next());
}
return junction;
}
}
}
| true | true | public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
// Calculate how many results there are in total. This has been
// moved to before the 'list()' invocation to avoid any "ORDER
// BY" clause added by 'populateArgumentsForCriteria()', otherwise
// an exception is thrown for non-string sort fields (GRAILS-2690).
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
// Drop the projection, add settings for the pagination parameters,
// and then execute the query.
this.criteria.setProjection(null);
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
// Updated the paged results with the total number of records
// calculated previously.
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
invokeClosureNode(args[0]);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
invokeClosureNode(args[0]);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass());
Type type = meta.getPropertyType(name.toString());
if (type.isAssociationType()) {
String otherSideEntityName =
((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
Class oldTargetClass = targetClass;
targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO);
BeanWrapper oldTargetBean = targetBean;
targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass));
associationStack.push(name.toString());
String newAlias = name.toString() + ALIAS + aliasStack.size();
StringBuffer fullPath = new StringBuffer();
for (Iterator i = associationStack.iterator(); i.hasNext();) {
String propertyName = (String) i.next();
if(fullPath.length() > 0 ) fullPath.append(".");
fullPath.append(propertyName);
}
this.criteria.createAlias(fullPath.toString(), newAlias, CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(newAlias);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
invokeClosureNode(args[0]);
aliasStack.remove(aliasStack.size() - 1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
associationStack.pop();
targetClass = oldTargetClass;
targetBean = oldTargetBean;
return name;
}
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
String propertyName = calculatePropertyName((String)value);
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( propertyName ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( propertyName );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( propertyName );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty(propertyName );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
| public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
// Calculate how many results there are in total. This has been
// moved to before the 'list()' invocation to avoid any "ORDER
// BY" clause added by 'populateArgumentsForCriteria()', otherwise
// an exception is thrown for non-string sort fields (GRAILS-2690).
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
// Drop the projection, add settings for the pagination parameters,
// and then execute the query.
this.criteria.setProjection(null);
this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
// Updated the paged results with the total number of records
// calculated previously.
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
invokeClosureNode(args[0]);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
invokeClosureNode(args[0]);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass());
Type type = meta.getPropertyType(name.toString());
if (type.isAssociationType()) {
String otherSideEntityName =
((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
Class oldTargetClass = targetClass;
targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO);
BeanWrapper oldTargetBean = targetBean;
targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass));
associationStack.push(name.toString());
String newAlias = name.toString() + ALIAS + aliasStack.size();
StringBuffer fullPath = new StringBuffer();
for (Iterator i = associationStack.iterator(); i.hasNext();) {
String propertyName = (String) i.next();
if(fullPath.length() > 0 ) fullPath.append(".");
fullPath.append(propertyName);
}
this.criteria.createAlias(fullPath.toString(), newAlias, CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(newAlias);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
invokeClosureNode(args[0]);
aliasStack.remove(aliasStack.size() - 1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
associationStack.pop();
targetClass = oldTargetClass;
targetBean = oldTargetBean;
return name;
}
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
String propertyName = calculatePropertyName((String)value);
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( propertyName ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( propertyName );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( propertyName );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty(propertyName );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
|
diff --git a/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java b/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java
index f617053c1..45bb87235 100644
--- a/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java
+++ b/astrid/src/com/todoroo/astrid/adapter/UpdateAdapter.java
@@ -1,780 +1,780 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.adapter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.actfm.sync.ActFmPreferenceService;
import com.todoroo.astrid.actfm.sync.messages.NameMaps;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.data.History;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.User;
import com.todoroo.astrid.data.UserActivity;
import com.todoroo.astrid.helper.AsyncImageView;
import com.todoroo.astrid.helper.ImageDiskCache;
/**
* Adapter for displaying a user's activity
*
* @author Tim Su <[email protected]>
*
*/
public class UpdateAdapter extends CursorAdapter {
// --- instance variables
protected final Fragment fragment;
private final int resource;
private final LayoutInflater inflater;
private final ImageDiskCache imageCache;
private final String linkColor;
private final String fromView;
public static final String USER_TABLE_ALIAS = "users_join"; //$NON-NLS-1$
public static final StringProperty USER_PICTURE = User.PICTURE.cloneAs(USER_TABLE_ALIAS, "userPicture"); //$NON-NLS-1$
private static final StringProperty USER_FIRST_NAME = User.FIRST_NAME.cloneAs(USER_TABLE_ALIAS, "userFirstName"); //$NON-NLS-1$
private static final StringProperty USER_LAST_NAME = User.LAST_NAME.cloneAs(USER_TABLE_ALIAS, "userLastName"); //$NON-NLS-1$
private static final StringProperty USER_NAME = User.NAME.cloneAs(USER_TABLE_ALIAS, "userName"); //$NON-NLS-1$
public static final StringProperty ACTIVITY_TYPE_PROPERTY = new StringProperty(null, "'" + NameMaps.TABLE_ID_USER_ACTIVITY + "' as type"); //$NON-NLS-1$//$NON-NLS-2$
public static final StringProperty HISTORY_TYPE_PROPERTY = new StringProperty(null, "'" + NameMaps.TABLE_ID_HISTORY + "'"); //$NON-NLS-1$ //$NON-NLS-2$
public static final StringProperty PADDING_PROPERTY = new StringProperty(null, "'0'"); //$NON-NLS-1$
public static final Property<?>[] USER_PROPERTIES = {
USER_PICTURE,
USER_FIRST_NAME,
USER_LAST_NAME,
USER_NAME
};
public static final Property<?>[] USER_ACTIVITY_PROPERTIES = {
UserActivity.CREATED_AT,
UserActivity.UUID,
UserActivity.ACTION,
UserActivity.MESSAGE,
UserActivity.TARGET_ID,
UserActivity.TARGET_NAME,
UserActivity.PICTURE,
UserActivity.ID,
ACTIVITY_TYPE_PROPERTY,
};
public static final Property<?>[] HISTORY_PROPERTIES = {
History.CREATED_AT,
History.USER_UUID,
History.COLUMN,
History.TABLE_ID,
History.OLD_VALUE,
History.NEW_VALUE,
History.TASK,
History.ID,
HISTORY_TYPE_PROPERTY,
};
public static final int TYPE_PROPERTY_INDEX = USER_ACTIVITY_PROPERTIES.length - 1;
private static final String TARGET_LINK_PREFIX = "$link_"; //$NON-NLS-1$
private static final Pattern TARGET_LINK_PATTERN = Pattern.compile("\\" + TARGET_LINK_PREFIX + "(\\w*)"); //$NON-NLS-1$//$NON-NLS-2$
private static final String TASK_LINK_TYPE = "task"; //$NON-NLS-1$
public static final String FROM_TAG_VIEW = "from_tag"; //$NON-NLS-1$
public static final String FROM_TASK_VIEW = "from_task"; //$NON-NLS-1$
public static final String FROM_RECENT_ACTIVITY_VIEW = "from_recent_activity"; //$NON-NLS-1$
/**
* Constructor
*
* @param activity
* @param resource
* layout resource to inflate
* @param c
* database cursor
* @param autoRequery
* whether cursor is automatically re-queried on changes
* @param onCompletedTaskListener
* goal listener. can be null
*/
public UpdateAdapter(Fragment fragment, int resource,
Cursor c, boolean autoRequery,
String fromView) {
super(fragment.getActivity(), c, autoRequery);
DependencyInjectionService.getInstance().inject(this);
linkColor = getLinkColor(fragment);
inflater = (LayoutInflater) fragment.getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
imageCache = ImageDiskCache.getInstance();
this.fromView = fromView;
this.resource = resource;
this.fragment = fragment;
}
public static String getLinkColor(Fragment f) {
TypedValue colorType = new TypedValue();
f.getActivity().getTheme().resolveAttribute(R.attr.asDetailsColor, colorType, false);
return "#" + Integer.toHexString(colorType.data).substring(2); //$NON-NLS-1$
}
/* ======================================================================
* =========================================================== view setup
* ====================================================================== */
private class ModelHolder {
public UserActivity activity = new UserActivity();
public User user = new User();
public History history = new History();
}
/** Creates a new view for use in the list view */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewGroup view = (ViewGroup)inflater.inflate(resource, parent, false);
view.setTag(new ModelHolder());
// populate view content
bindView(view, context, cursor);
return view;
}
/** Populates a view with content */
@Override
public void bindView(View view, Context context, Cursor c) {
TodorooCursor<UserActivity> cursor = (TodorooCursor<UserActivity>)c;
ModelHolder mh = ((ModelHolder) view.getTag());
String type = cursor.getString(TYPE_PROPERTY_INDEX);
UserActivity update = mh.activity;
update.clear();
User user = mh.user;
user.clear();
History history = mh.history;
if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(type)) {
readUserActivityProperties(cursor, update);
} else {
readHistoryProperties(cursor, history);
}
readUserProperties(cursor, user);
setFieldContentsAndVisibility(view, update, user, history, type);
}
public static void readUserActivityProperties(TodorooCursor<UserActivity> unionCursor, UserActivity activity) {
activity.setValue(UserActivity.CREATED_AT, unionCursor.getLong(0));
activity.setValue(UserActivity.UUID, unionCursor.getString(1));
activity.setValue(UserActivity.ACTION, unionCursor.getString(2));
activity.setValue(UserActivity.MESSAGE, unionCursor.getString(3));
activity.setValue(UserActivity.TARGET_ID, unionCursor.getString(4));
activity.setValue(UserActivity.TARGET_NAME, unionCursor.getString(5));
activity.setValue(UserActivity.PICTURE, unionCursor.getString(6));
}
public static void readHistoryProperties(TodorooCursor<UserActivity> unionCursor, History history) {
history.setValue(History.CREATED_AT, unionCursor.getLong(0));
history.setValue(History.USER_UUID, unionCursor.getString(1));
history.setValue(History.COLUMN, unionCursor.getString(2));
history.setValue(History.TABLE_ID, unionCursor.getString(3));
history.setValue(History.OLD_VALUE, unionCursor.getString(4));
history.setValue(History.NEW_VALUE, unionCursor.getString(5));
history.setValue(History.TASK, unionCursor.getString(6));
}
public static void readUserProperties(TodorooCursor<UserActivity> joinCursor, User user) {
user.setValue(USER_FIRST_NAME, joinCursor.get(USER_FIRST_NAME));
user.setValue(USER_LAST_NAME, joinCursor.get(USER_LAST_NAME));
user.setValue(USER_NAME, joinCursor.get(USER_NAME));
user.setValue(USER_PICTURE, joinCursor.get(USER_PICTURE));
}
/** Helper method to set the contents and visibility of each field */
public synchronized void setFieldContentsAndVisibility(View view, UserActivity activity, User user, History history, String type) {
// picture
if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(type)) {
setupUserActivityRow(view, activity, user);
} else if (NameMaps.TABLE_ID_HISTORY.equals(type)) {
setupHistoryRow(view, history, user);
}
}
private void setupUserActivityRow(View view, UserActivity activity, User user) {
final AsyncImageView pictureView = (AsyncImageView)view.findViewById(R.id.picture); {
if (user.containsNonNullValue(USER_PICTURE)) {
String pictureUrl = user.getPictureUrl(USER_PICTURE, RemoteModel.PICTURE_THUMB);
pictureView.setUrl(pictureUrl);
}
pictureView.setVisibility(View.VISIBLE);
}
final AsyncImageView commentPictureView = (AsyncImageView)view.findViewById(R.id.comment_picture); {
String updatePicture = activity.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_THUMB);
Bitmap updateBitmap = null;
if (TextUtils.isEmpty(updatePicture))
updateBitmap = activity.getPictureBitmap(UserActivity.PICTURE);
setupImagePopupForCommentView(view, commentPictureView, updatePicture, updateBitmap,
activity.getValue(UserActivity.MESSAGE), fragment, imageCache);
}
// name
final TextView nameView = (TextView)view.findViewById(R.id.title); {
nameView.setText(getUpdateComment((AstridActivity)fragment.getActivity(), activity, user, linkColor, fromView));
nameView.setMovementMethod(new LinkMovementMethod());
}
// date
final TextView date = (TextView)view.findViewById(R.id.date); {
CharSequence dateString = DateUtils.getRelativeTimeSpanString(activity.getValue(UserActivity.CREATED_AT),
DateUtilities.now(), DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
date.setText(dateString);
}
}
private void setupHistoryRow(View view, History history, User user) {
final AsyncImageView pictureView = (AsyncImageView)view.findViewById(R.id.picture);
pictureView.setVisibility(View.GONE);
final AsyncImageView commentPictureView = (AsyncImageView)view.findViewById(R.id.comment_picture);
commentPictureView.setVisibility(View.GONE);
final TextView nameView = (TextView)view.findViewById(R.id.title); {
nameView.setText(getHistoryComment((AstridActivity) fragment.getActivity(), history, user, linkColor, fromView));
}
final TextView date = (TextView)view.findViewById(R.id.date); {
CharSequence dateString = DateUtils.getRelativeTimeSpanString(history.getValue(History.CREATED_AT),
DateUtilities.now(), DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
date.setText(dateString);
}
}
@Override
public boolean isEnabled(int position) {
return false;
}
public static void setupImagePopupForCommentView(View view, AsyncImageView commentPictureView, final String updatePicture, final Bitmap updateBitmap,
final String message, final Fragment fragment, ImageDiskCache imageCache) {
if ((!TextUtils.isEmpty(updatePicture) && !"null".equals(updatePicture)) || updateBitmap != null) { //$NON-NLS-1$
commentPictureView.setVisibility(View.VISIBLE);
if (updateBitmap != null)
commentPictureView.setImageBitmap(updateBitmap);
else
commentPictureView.setUrl(updatePicture);
if(imageCache.contains(updatePicture) && updateBitmap == null) {
try {
commentPictureView.setDefaultImageBitmap(imageCache.get(updatePicture));
} catch (IOException e) {
e.printStackTrace();
}
} else if (updateBitmap == null) {
commentPictureView.setUrl(updatePicture);
}
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog image = new AlertDialog.Builder(fragment.getActivity()).create();
AsyncImageView imageView = new AsyncImageView(fragment.getActivity());
imageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
imageView.setDefaultImageResource(android.R.drawable.ic_menu_gallery);
if (updateBitmap != null)
imageView.setImageBitmap(updateBitmap);
else
imageView.setUrl(updatePicture);
image.setView(imageView);
image.setMessage(message);
image.setButton(fragment.getString(R.string.DLG_close), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
image.show();
}
});
} else {
commentPictureView.setVisibility(View.GONE);
}
}
public static String linkify (String string, String linkColor) {
return String.format("<font color=%s>%s</font>", linkColor, string); //$NON-NLS-1$
}
public static Spanned getUpdateComment(final AstridActivity context, UserActivity activity, User user, String linkColor, String fromView) {
String userDisplay;
if (activity.getValue(UserActivity.USER_UUID).equals(Task.USER_ID_SELF)) {
userDisplay = context.getString(R.string.update_string_user_self);
} else if (user == null) {
userDisplay = context.getString(R.string.ENA_no_user);
} else {
userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
}
if (TextUtils.isEmpty(userDisplay))
userDisplay = context.getString(R.string.ENA_no_user);
String targetName = activity.getValue(UserActivity.TARGET_NAME);
String action = activity.getValue(UserActivity.ACTION);
String message = activity.getValue(UserActivity.MESSAGE);
int commentResource = 0;
if (UserActivity.ACTION_TASK_COMMENT.equals(action)) {
if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName))
commentResource = R.string.update_string_default_comment;
else
commentResource = R.string.update_string_task_comment;
} else if (UserActivity.ACTION_TAG_COMMENT.equals(action)) {
if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName))
commentResource = R.string.update_string_default_comment;
else
commentResource = R.string.update_string_tag_comment;
}
if (commentResource == 0)
return Html.fromHtml(String.format("%s %s", userDisplay, message)); //$NON-NLS-1$
String original = context.getString(commentResource, userDisplay, targetName, message);
int taskLinkIndex = original.indexOf(TARGET_LINK_PREFIX);
if (taskLinkIndex < 0)
return Html.fromHtml(original);
String[] components = original.split(" "); //$NON-NLS-1$
SpannableStringBuilder builder = new SpannableStringBuilder();
StringBuilder htmlStringBuilder = new StringBuilder();
for (String comp : components) {
Matcher m = TARGET_LINK_PATTERN.matcher(comp);
if (m.find()) {
builder.append(Html.fromHtml(htmlStringBuilder.toString()));
htmlStringBuilder.setLength(0);
String linkType = m.group(1);
CharSequence link = getLinkSpan(context, activity, targetName, linkColor, linkType);
if (link != null) {
builder.append(link);
if (!m.hitEnd()) {
builder.append(comp.substring(m.end()));
}
builder.append(' ');
}
} else {
htmlStringBuilder.append(comp);
htmlStringBuilder.append(' ');
}
}
if (htmlStringBuilder.length() > 0)
builder.append(Html.fromHtml(htmlStringBuilder.toString()));
return builder;
}
@SuppressWarnings("nls")
public static String getHistoryComment(final AstridActivity context, History history, User user, String linkColor, String fromView) {
boolean hasTask = false;
JSONArray taskAttrs = null;
if (!TextUtils.isEmpty(history.getValue(History.TASK))) {
try {
taskAttrs = new JSONArray(history.getValue(History.TASK));
hasTask = true;
} catch (JSONException e) {
//
}
}
String item;
String itemPosessive;
if (FROM_TASK_VIEW.equals(fromView)) {
item = context.getString(R.string.history_this_task);
} else if (hasTask && taskAttrs != null) {
item = taskAttrs.optString(1);
} else {
item = context.getString(R.string.history_this_list);
}
itemPosessive = item + "'s";
String oldValue = history.getValue(History.OLD_VALUE);
String newValue = history.getValue(History.NEW_VALUE);
String result = "";
String column = history.getValue(History.COLUMN);
try {
if (History.COL_TAG_ADDED.equals(column) || History.COL_TAG_REMOVED.equals(column)) {
- JSONObject tagObj = new JSONObject(newValue);
- String tagName = tagObj.getString("name");
+ JSONArray tagObj = new JSONArray(newValue);
+ String tagName = tagObj.getString(1);
if (History.COL_TAG_ADDED.equals(column))
result = context.getString(R.string.history_tag_added, item, tagName);
else
result = context.getString(R.string.history_tag_removed, item, tagName);
} else if (History.COL_SHARED_WITH.equals(column) || History.COL_UNSHARED_WITH.equals(column)) {
JSONArray members = new JSONArray(newValue);
String userId = history.getValue(History.USER_UUID);
StringBuilder memberList = new StringBuilder();
for (int i = 0; i < members.length(); i++) {
JSONObject m = members.getJSONObject(i);
memberList.append(userDisplay(context, userId, m));
if (i != members.length() - 1)
memberList.append(", ");
}
if (History.COL_SHARED_WITH.equals(column))
result = context.getString(R.string.history_shared_with, item, memberList);
else
result = context.getString(R.string.history_unshared_with, item, memberList);
} else if (History.COL_MEMBER_ADDED.equals(column) || History.COL_MEMBER_REMOVED.equals(column)) {
JSONObject userValue = new JSONObject(newValue);
if (history.getValue(History.USER_UUID).equals(userValue.optString("id")) && History.COL_MEMBER_REMOVED.equals(column))
result = context.getString(R.string.history_left_list, item);
else {
String userDisplay = userDisplay(context, history.getValue(History.USER_UUID), userValue);
if (History.COL_MEMBER_ADDED.equals(column))
result = context.getString(R.string.history_added_user, userDisplay, item);
else
result = context.getString(R.string.history_removed_user, userDisplay, item);
}
} else if (History.COL_COMPLETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_completed, item);
} else {
result = context.getString(R.string.history_uncompleted, item);
}
} else if (History.COL_DELETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_deleted, item);
} else {
result = context.getString(R.string.history_undeleted, item);
}
} else if (History.COL_IMPORTANCE.equals(column)) {
int oldPriority = AndroidUtilities.tryParseInt(oldValue, 0);
int newPriority = AndroidUtilities.tryParseInt(newValue, 0);
result = context.getString(R.string.history_importance_changed, itemPosessive, priorityString(oldPriority), priorityString(newPriority));
} else if (History.COL_NOTES_LENGTH.equals(column)) {
int oldLength = AndroidUtilities.tryParseInt(oldValue, 0);
int newLength = AndroidUtilities.tryParseInt(newValue, 0);
if (oldLength > 0 && newLength > oldLength)
result = context.getString(R.string.history_added_description_characters, (newLength - oldLength), itemPosessive);
else if (newLength == 0)
result = context.getString(R.string.history_removed_description, itemPosessive);
else if (oldLength > 0 && newLength < oldLength)
result = context.getString(R.string.history_removed_description_characters, (oldLength - newLength), itemPosessive);
else if (oldLength > 0 && oldLength == newLength)
result = context.getString(R.string.history_updated_description, itemPosessive);
} else if (History.COL_PUBLIC.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_made_public, item);
else
result = context.getString(R.string.history_made_private, item);
} else if (History.COL_DUE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !TextUtils.isEmpty(newValue)
&& !"null".equals(oldValue) && !"null".equals(newValue))
result = context.getString(R.string.history_changed_due_date, itemPosessive, dateString(context, oldValue, newValue), dateString(context, newValue, oldValue));
else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue))
result = context.getString(R.string.history_set_due_date, itemPosessive, dateString(context, newValue, DateUtilities.timeToIso8601(DateUtilities.now(), true)));
else
result = context.getString(R.string.history_removed_due_date, itemPosessive);
} else if (History.COL_REPEAT.equals(column)) {
String repeatString = getRepeatString(context, newValue);
if (!TextUtils.isEmpty(repeatString))
result = context.getString(R.string.history_changed_repeat, itemPosessive, repeatString);
else
result = context.getString(R.string.history_removed_repeat, itemPosessive);
} else if (History.COL_TASK_REPEATED.equals(column)) {
result = context.getString(R.string.history_completed_repeating_task, item, dateString(context, newValue, oldValue));
} else if (History.COL_TITLE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_title_changed, itemPosessive, oldValue, newValue);
else
result = context.getString(R.string.history_title_set, itemPosessive, newValue);
} else if (History.COL_NAME.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_name_changed, oldValue, newValue);
else
result = context.getString(R.string.history_name_set, newValue);
} else if (History.COL_DESCRIPTION.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_description_changed, oldValue, newValue);
else
result = context.getString(R.string.history_description_set, newValue);
} else if (History.COL_PICTURE_ID.equals(column) || History.COL_DEFAULT_LIST_IMAGE_ID.equals(column)) {
result = context.getString(R.string.history_changed_list_picture);
} else if (History.COL_IS_SILENT.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_silenced, item);
else
result = context.getString(R.string.history_unsilenced, item);
} else if (History.COL_IS_FAVORITE.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_favorited, item);
else
result = context.getString(R.string.history_unfavorited, item);
} else if (History.COL_USER_ID.equals(column)) {
String userId = history.getValue(History.USER_UUID);
JSONObject userValue = new JSONObject(newValue);
if (FROM_TAG_VIEW.equals(fromView) && !hasTask) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_changed_list_owner, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created_this_list);
} else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue) && Task.USER_ID_UNASSIGNED.equals(userValue))
result = context.getString(R.string.history_unassigned, item);
else if (Task.USER_ID_UNASSIGNED.equals(oldValue) && userValue.optString("id").equals(ActFmPreferenceService.userId()))
result = context.getString(R.string.history_claimed, item);
else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_assigned_to, item, userDisplay(context, userId, userValue));
else if (!userValue.optString("id").equals(ActFmPreferenceService.userId()) && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id")))
result = context.getString(R.string.history_created_for, item, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created, item);
} else {
result = context.getString(R.string.history_default, column, newValue);
}
} catch (Exception e) {
e.printStackTrace();
result = context.getString(R.string.history_default, column, newValue);
}
if (TextUtils.isEmpty(result))
result = context.getString(R.string.history_default, column, newValue);
String userDisplay;
if (history.getValue(History.USER_UUID).equals(Task.USER_ID_SELF) || history.getValue(History.USER_UUID).equals(ActFmPreferenceService.userId())) {
userDisplay = context.getString(R.string.update_string_user_self);
} else if (user == null) {
userDisplay = context.getString(R.string.ENA_no_user);
} else {
userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
}
return userDisplay + " " + result;
}
private static String dateString(Context context, String value, String other) {
boolean includeYear = (!TextUtils.isEmpty(other) && !value.substring(0, 4).equals(other.substring(0, 4)));
boolean hasTime = DateUtilities.isoStringHasTime(value);
long time = 0;
try {
time = DateUtilities.parseIso8601(value);
Date date = new Date(time);
String result = DateUtilities.getDateString(context, date, includeYear);
if (hasTime)
result += ", " + DateUtilities.getTimeString(context, date, false); //$NON-NLS-1$
return result;
} catch (ParseException e) {
return value;
}
}
private static final HashMap<String, Integer> INTERVAL_LABELS = new HashMap<String, Integer>();
static {
INTERVAL_LABELS.put("DAILY", R.string.repeat_days); //$NON-NLS-1$
INTERVAL_LABELS.put("WEEKDAYS", R.string.repeat_weekdays); //$NON-NLS-1$
INTERVAL_LABELS.put("WEEKLY", R.string.repeat_weeks); //$NON-NLS-1$
INTERVAL_LABELS.put("MONTHLY", R.string.repeat_months); //$NON-NLS-1$
INTERVAL_LABELS.put("YEARLY", R.string.repeat_years); //$NON-NLS-1$
INTERVAL_LABELS.put("HOURLY", R.string.repeat_hours); //$NON-NLS-1$
INTERVAL_LABELS.put("MINUTELY", R.string.repeat_minutes); //$NON-NLS-1$
}
@SuppressWarnings("nls")
private static final String[] SORTED_WEEKDAYS = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
@SuppressWarnings("nls")
private static String getRepeatString(Context context, String value) {
if (TextUtils.isEmpty(value) || "null".equals(value))
return null;
try {
JSONObject repeat = new JSONObject(value);
boolean weekdays = false;
if (repeat.has("freq")) {
String freq = repeat.getString("freq");
int interval = repeat.getInt("interval");
JSONArray byDay = repeat.optJSONArray("byday");
String[] byDayStrings = null;
if (byDay != null) {
byDayStrings = new String[byDay.length()];
for (int i = 0; i < byDay.length(); i++) {
byDayStrings[i] = byDay.getString(i);
}
}
String result = "";
if ("WEEKLY".equals(freq) && byDay != null && byDayStrings != null) {
Arrays.sort(byDayStrings);
StringBuilder daysString = new StringBuilder();
daysString.append("[");
for (String s : byDayStrings) {
daysString.append("\"").append(s).append("\"").append(",");
}
daysString.deleteCharAt(daysString.length() - 1);
daysString.append("]");
if (daysString.toString().equals("[\"FR\",\"MO\",\"TH\",\"TU\",\"WE\"]")) {
result = context.getString(R.string.repeat_weekdays);
weekdays = true;
}
}
if (!weekdays) {
if (interval == 1) {
result = context.getString(INTERVAL_LABELS.get(freq));
result = result.substring(0, result.length() - 1);
} else {
result = interval + " " + context.getString(INTERVAL_LABELS.get(freq));
}
}
result = context.getString(R.string.history_repeat_every, result);
if ("WEEKLY".equals(freq) && !weekdays && byDay != null && byDay.length() > 0 && byDayStrings != null) {
Arrays.sort(byDayStrings, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
int lhIndex = AndroidUtilities.indexOf(SORTED_WEEKDAYS, lhs);
int rhIndex = AndroidUtilities.indexOf(SORTED_WEEKDAYS, rhs);
if (lhIndex < rhIndex)
return -1;
else if (lhIndex > rhIndex)
return 1;
else
return 0;
}
});
StringBuilder byDayDisplay = new StringBuilder();
for (String s : byDayStrings) {
byDayDisplay.append(s).append(", ");
}
byDayDisplay.delete(byDayDisplay.length() - 2, byDayDisplay.length());
result += (" " + context.getString(R.string.history_repeat_on, byDayDisplay.toString()));
}
if ("COMPLETION".equals(repeat.optString("from")))
result += (" " + context.getString(R.string.history_repeat_from_completion));
return result;
} else {
return null;
}
} catch (JSONException e) {
return null;
}
}
@SuppressWarnings("nls")
private static String userDisplay(Context context, String historyUserId, JSONObject userJson) {
try {
String id = userJson.getString("id");
String name = userJson.getString("name");
if (historyUserId.equals(id) && ActFmPreferenceService.userId().equals(id))
return context.getString(R.string.history_yourself);
else if (ActFmPreferenceService.userId().equals(id))
return context.getString(R.string.history_you);
else if (RemoteModel.isValidUuid(id))
return name;
else return context.getString(R.string.history_a_deleted_user);
} catch (JSONException e) {
return context.getString(R.string.ENA_no_user).toLowerCase();
}
}
@SuppressWarnings("nls")
private static final String[] PRIORITY_STRINGS = { "!!!", "!!", "!", "o" };
private static String priorityString(int priority) {
return PRIORITY_STRINGS[priority];
}
private static CharSequence getLinkSpan(final AstridActivity activity, UserActivity update, String targetName, String linkColor, String linkType) {
if (TASK_LINK_TYPE.equals(linkType)) {
final String taskId = update.getValue(UserActivity.TARGET_ID);
if (RemoteModel.isValidUuid(taskId)) {
SpannableString taskSpan = new SpannableString(targetName);
taskSpan.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (activity != null) // TODO: This shouldn't happen, but sometimes does
activity.onTaskListItemClicked(taskId);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}, 0, targetName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return taskSpan;
} else {
return Html.fromHtml(linkify(targetName, linkColor));
}
}
return null;
}
}
| true | true | public static String getHistoryComment(final AstridActivity context, History history, User user, String linkColor, String fromView) {
boolean hasTask = false;
JSONArray taskAttrs = null;
if (!TextUtils.isEmpty(history.getValue(History.TASK))) {
try {
taskAttrs = new JSONArray(history.getValue(History.TASK));
hasTask = true;
} catch (JSONException e) {
//
}
}
String item;
String itemPosessive;
if (FROM_TASK_VIEW.equals(fromView)) {
item = context.getString(R.string.history_this_task);
} else if (hasTask && taskAttrs != null) {
item = taskAttrs.optString(1);
} else {
item = context.getString(R.string.history_this_list);
}
itemPosessive = item + "'s";
String oldValue = history.getValue(History.OLD_VALUE);
String newValue = history.getValue(History.NEW_VALUE);
String result = "";
String column = history.getValue(History.COLUMN);
try {
if (History.COL_TAG_ADDED.equals(column) || History.COL_TAG_REMOVED.equals(column)) {
JSONObject tagObj = new JSONObject(newValue);
String tagName = tagObj.getString("name");
if (History.COL_TAG_ADDED.equals(column))
result = context.getString(R.string.history_tag_added, item, tagName);
else
result = context.getString(R.string.history_tag_removed, item, tagName);
} else if (History.COL_SHARED_WITH.equals(column) || History.COL_UNSHARED_WITH.equals(column)) {
JSONArray members = new JSONArray(newValue);
String userId = history.getValue(History.USER_UUID);
StringBuilder memberList = new StringBuilder();
for (int i = 0; i < members.length(); i++) {
JSONObject m = members.getJSONObject(i);
memberList.append(userDisplay(context, userId, m));
if (i != members.length() - 1)
memberList.append(", ");
}
if (History.COL_SHARED_WITH.equals(column))
result = context.getString(R.string.history_shared_with, item, memberList);
else
result = context.getString(R.string.history_unshared_with, item, memberList);
} else if (History.COL_MEMBER_ADDED.equals(column) || History.COL_MEMBER_REMOVED.equals(column)) {
JSONObject userValue = new JSONObject(newValue);
if (history.getValue(History.USER_UUID).equals(userValue.optString("id")) && History.COL_MEMBER_REMOVED.equals(column))
result = context.getString(R.string.history_left_list, item);
else {
String userDisplay = userDisplay(context, history.getValue(History.USER_UUID), userValue);
if (History.COL_MEMBER_ADDED.equals(column))
result = context.getString(R.string.history_added_user, userDisplay, item);
else
result = context.getString(R.string.history_removed_user, userDisplay, item);
}
} else if (History.COL_COMPLETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_completed, item);
} else {
result = context.getString(R.string.history_uncompleted, item);
}
} else if (History.COL_DELETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_deleted, item);
} else {
result = context.getString(R.string.history_undeleted, item);
}
} else if (History.COL_IMPORTANCE.equals(column)) {
int oldPriority = AndroidUtilities.tryParseInt(oldValue, 0);
int newPriority = AndroidUtilities.tryParseInt(newValue, 0);
result = context.getString(R.string.history_importance_changed, itemPosessive, priorityString(oldPriority), priorityString(newPriority));
} else if (History.COL_NOTES_LENGTH.equals(column)) {
int oldLength = AndroidUtilities.tryParseInt(oldValue, 0);
int newLength = AndroidUtilities.tryParseInt(newValue, 0);
if (oldLength > 0 && newLength > oldLength)
result = context.getString(R.string.history_added_description_characters, (newLength - oldLength), itemPosessive);
else if (newLength == 0)
result = context.getString(R.string.history_removed_description, itemPosessive);
else if (oldLength > 0 && newLength < oldLength)
result = context.getString(R.string.history_removed_description_characters, (oldLength - newLength), itemPosessive);
else if (oldLength > 0 && oldLength == newLength)
result = context.getString(R.string.history_updated_description, itemPosessive);
} else if (History.COL_PUBLIC.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_made_public, item);
else
result = context.getString(R.string.history_made_private, item);
} else if (History.COL_DUE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !TextUtils.isEmpty(newValue)
&& !"null".equals(oldValue) && !"null".equals(newValue))
result = context.getString(R.string.history_changed_due_date, itemPosessive, dateString(context, oldValue, newValue), dateString(context, newValue, oldValue));
else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue))
result = context.getString(R.string.history_set_due_date, itemPosessive, dateString(context, newValue, DateUtilities.timeToIso8601(DateUtilities.now(), true)));
else
result = context.getString(R.string.history_removed_due_date, itemPosessive);
} else if (History.COL_REPEAT.equals(column)) {
String repeatString = getRepeatString(context, newValue);
if (!TextUtils.isEmpty(repeatString))
result = context.getString(R.string.history_changed_repeat, itemPosessive, repeatString);
else
result = context.getString(R.string.history_removed_repeat, itemPosessive);
} else if (History.COL_TASK_REPEATED.equals(column)) {
result = context.getString(R.string.history_completed_repeating_task, item, dateString(context, newValue, oldValue));
} else if (History.COL_TITLE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_title_changed, itemPosessive, oldValue, newValue);
else
result = context.getString(R.string.history_title_set, itemPosessive, newValue);
} else if (History.COL_NAME.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_name_changed, oldValue, newValue);
else
result = context.getString(R.string.history_name_set, newValue);
} else if (History.COL_DESCRIPTION.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_description_changed, oldValue, newValue);
else
result = context.getString(R.string.history_description_set, newValue);
} else if (History.COL_PICTURE_ID.equals(column) || History.COL_DEFAULT_LIST_IMAGE_ID.equals(column)) {
result = context.getString(R.string.history_changed_list_picture);
} else if (History.COL_IS_SILENT.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_silenced, item);
else
result = context.getString(R.string.history_unsilenced, item);
} else if (History.COL_IS_FAVORITE.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_favorited, item);
else
result = context.getString(R.string.history_unfavorited, item);
} else if (History.COL_USER_ID.equals(column)) {
String userId = history.getValue(History.USER_UUID);
JSONObject userValue = new JSONObject(newValue);
if (FROM_TAG_VIEW.equals(fromView) && !hasTask) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_changed_list_owner, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created_this_list);
} else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue) && Task.USER_ID_UNASSIGNED.equals(userValue))
result = context.getString(R.string.history_unassigned, item);
else if (Task.USER_ID_UNASSIGNED.equals(oldValue) && userValue.optString("id").equals(ActFmPreferenceService.userId()))
result = context.getString(R.string.history_claimed, item);
else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_assigned_to, item, userDisplay(context, userId, userValue));
else if (!userValue.optString("id").equals(ActFmPreferenceService.userId()) && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id")))
result = context.getString(R.string.history_created_for, item, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created, item);
} else {
result = context.getString(R.string.history_default, column, newValue);
}
} catch (Exception e) {
e.printStackTrace();
result = context.getString(R.string.history_default, column, newValue);
}
if (TextUtils.isEmpty(result))
result = context.getString(R.string.history_default, column, newValue);
String userDisplay;
if (history.getValue(History.USER_UUID).equals(Task.USER_ID_SELF) || history.getValue(History.USER_UUID).equals(ActFmPreferenceService.userId())) {
userDisplay = context.getString(R.string.update_string_user_self);
} else if (user == null) {
userDisplay = context.getString(R.string.ENA_no_user);
} else {
userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
}
return userDisplay + " " + result;
}
| public static String getHistoryComment(final AstridActivity context, History history, User user, String linkColor, String fromView) {
boolean hasTask = false;
JSONArray taskAttrs = null;
if (!TextUtils.isEmpty(history.getValue(History.TASK))) {
try {
taskAttrs = new JSONArray(history.getValue(History.TASK));
hasTask = true;
} catch (JSONException e) {
//
}
}
String item;
String itemPosessive;
if (FROM_TASK_VIEW.equals(fromView)) {
item = context.getString(R.string.history_this_task);
} else if (hasTask && taskAttrs != null) {
item = taskAttrs.optString(1);
} else {
item = context.getString(R.string.history_this_list);
}
itemPosessive = item + "'s";
String oldValue = history.getValue(History.OLD_VALUE);
String newValue = history.getValue(History.NEW_VALUE);
String result = "";
String column = history.getValue(History.COLUMN);
try {
if (History.COL_TAG_ADDED.equals(column) || History.COL_TAG_REMOVED.equals(column)) {
JSONArray tagObj = new JSONArray(newValue);
String tagName = tagObj.getString(1);
if (History.COL_TAG_ADDED.equals(column))
result = context.getString(R.string.history_tag_added, item, tagName);
else
result = context.getString(R.string.history_tag_removed, item, tagName);
} else if (History.COL_SHARED_WITH.equals(column) || History.COL_UNSHARED_WITH.equals(column)) {
JSONArray members = new JSONArray(newValue);
String userId = history.getValue(History.USER_UUID);
StringBuilder memberList = new StringBuilder();
for (int i = 0; i < members.length(); i++) {
JSONObject m = members.getJSONObject(i);
memberList.append(userDisplay(context, userId, m));
if (i != members.length() - 1)
memberList.append(", ");
}
if (History.COL_SHARED_WITH.equals(column))
result = context.getString(R.string.history_shared_with, item, memberList);
else
result = context.getString(R.string.history_unshared_with, item, memberList);
} else if (History.COL_MEMBER_ADDED.equals(column) || History.COL_MEMBER_REMOVED.equals(column)) {
JSONObject userValue = new JSONObject(newValue);
if (history.getValue(History.USER_UUID).equals(userValue.optString("id")) && History.COL_MEMBER_REMOVED.equals(column))
result = context.getString(R.string.history_left_list, item);
else {
String userDisplay = userDisplay(context, history.getValue(History.USER_UUID), userValue);
if (History.COL_MEMBER_ADDED.equals(column))
result = context.getString(R.string.history_added_user, userDisplay, item);
else
result = context.getString(R.string.history_removed_user, userDisplay, item);
}
} else if (History.COL_COMPLETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_completed, item);
} else {
result = context.getString(R.string.history_uncompleted, item);
}
} else if (History.COL_DELETED_AT.equals(column)) {
if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue)) {
result = context.getString(R.string.history_deleted, item);
} else {
result = context.getString(R.string.history_undeleted, item);
}
} else if (History.COL_IMPORTANCE.equals(column)) {
int oldPriority = AndroidUtilities.tryParseInt(oldValue, 0);
int newPriority = AndroidUtilities.tryParseInt(newValue, 0);
result = context.getString(R.string.history_importance_changed, itemPosessive, priorityString(oldPriority), priorityString(newPriority));
} else if (History.COL_NOTES_LENGTH.equals(column)) {
int oldLength = AndroidUtilities.tryParseInt(oldValue, 0);
int newLength = AndroidUtilities.tryParseInt(newValue, 0);
if (oldLength > 0 && newLength > oldLength)
result = context.getString(R.string.history_added_description_characters, (newLength - oldLength), itemPosessive);
else if (newLength == 0)
result = context.getString(R.string.history_removed_description, itemPosessive);
else if (oldLength > 0 && newLength < oldLength)
result = context.getString(R.string.history_removed_description_characters, (oldLength - newLength), itemPosessive);
else if (oldLength > 0 && oldLength == newLength)
result = context.getString(R.string.history_updated_description, itemPosessive);
} else if (History.COL_PUBLIC.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_made_public, item);
else
result = context.getString(R.string.history_made_private, item);
} else if (History.COL_DUE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !TextUtils.isEmpty(newValue)
&& !"null".equals(oldValue) && !"null".equals(newValue))
result = context.getString(R.string.history_changed_due_date, itemPosessive, dateString(context, oldValue, newValue), dateString(context, newValue, oldValue));
else if (!TextUtils.isEmpty(newValue) && !"null".equals(newValue))
result = context.getString(R.string.history_set_due_date, itemPosessive, dateString(context, newValue, DateUtilities.timeToIso8601(DateUtilities.now(), true)));
else
result = context.getString(R.string.history_removed_due_date, itemPosessive);
} else if (History.COL_REPEAT.equals(column)) {
String repeatString = getRepeatString(context, newValue);
if (!TextUtils.isEmpty(repeatString))
result = context.getString(R.string.history_changed_repeat, itemPosessive, repeatString);
else
result = context.getString(R.string.history_removed_repeat, itemPosessive);
} else if (History.COL_TASK_REPEATED.equals(column)) {
result = context.getString(R.string.history_completed_repeating_task, item, dateString(context, newValue, oldValue));
} else if (History.COL_TITLE.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_title_changed, itemPosessive, oldValue, newValue);
else
result = context.getString(R.string.history_title_set, itemPosessive, newValue);
} else if (History.COL_NAME.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_name_changed, oldValue, newValue);
else
result = context.getString(R.string.history_name_set, newValue);
} else if (History.COL_DESCRIPTION.equals(column)) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_description_changed, oldValue, newValue);
else
result = context.getString(R.string.history_description_set, newValue);
} else if (History.COL_PICTURE_ID.equals(column) || History.COL_DEFAULT_LIST_IMAGE_ID.equals(column)) {
result = context.getString(R.string.history_changed_list_picture);
} else if (History.COL_IS_SILENT.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_silenced, item);
else
result = context.getString(R.string.history_unsilenced, item);
} else if (History.COL_IS_FAVORITE.equals(column)) {
int value = AndroidUtilities.tryParseInt(newValue, 0);
if (value > 0)
result = context.getString(R.string.history_favorited, item);
else
result = context.getString(R.string.history_unfavorited, item);
} else if (History.COL_USER_ID.equals(column)) {
String userId = history.getValue(History.USER_UUID);
JSONObject userValue = new JSONObject(newValue);
if (FROM_TAG_VIEW.equals(fromView) && !hasTask) {
if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_changed_list_owner, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created_this_list);
} else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue) && Task.USER_ID_UNASSIGNED.equals(userValue))
result = context.getString(R.string.history_unassigned, item);
else if (Task.USER_ID_UNASSIGNED.equals(oldValue) && userValue.optString("id").equals(ActFmPreferenceService.userId()))
result = context.getString(R.string.history_claimed, item);
else if (!TextUtils.isEmpty(oldValue) && !"null".equals(oldValue))
result = context.getString(R.string.history_assigned_to, item, userDisplay(context, userId, userValue));
else if (!userValue.optString("id").equals(ActFmPreferenceService.userId()) && !Task.USER_ID_UNASSIGNED.equals(userValue.optString("id")))
result = context.getString(R.string.history_created_for, item, userDisplay(context, userId, userValue));
else
result = context.getString(R.string.history_created, item);
} else {
result = context.getString(R.string.history_default, column, newValue);
}
} catch (Exception e) {
e.printStackTrace();
result = context.getString(R.string.history_default, column, newValue);
}
if (TextUtils.isEmpty(result))
result = context.getString(R.string.history_default, column, newValue);
String userDisplay;
if (history.getValue(History.USER_UUID).equals(Task.USER_ID_SELF) || history.getValue(History.USER_UUID).equals(ActFmPreferenceService.userId())) {
userDisplay = context.getString(R.string.update_string_user_self);
} else if (user == null) {
userDisplay = context.getString(R.string.ENA_no_user);
} else {
userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
}
return userDisplay + " " + result;
}
|
diff --git a/network-rpc/src/main/java/org/apache/niolex/network/rpc/RpcClient.java b/network-rpc/src/main/java/org/apache/niolex/network/rpc/RpcClient.java
index 28d1ea7..2ccf1ef 100644
--- a/network-rpc/src/main/java/org/apache/niolex/network/rpc/RpcClient.java
+++ b/network-rpc/src/main/java/org/apache/niolex/network/rpc/RpcClient.java
@@ -1,378 +1,381 @@
/**
* RpcClient.java
*
* Copyright 2012 Niolex, Inc.
*
* Niolex 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.niolex.network.rpc;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.niolex.commons.reflect.MethodUtil;
import org.apache.niolex.commons.util.SystemUtil;
import org.apache.niolex.network.Config;
import org.apache.niolex.network.IClient;
import org.apache.niolex.network.IPacketHandler;
import org.apache.niolex.network.IPacketWriter;
import org.apache.niolex.network.PacketData;
import org.apache.niolex.network.rpc.anno.RpcMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The basic RpcClient, send and receive Rpc packets, do client stub here too.
*
* @author <a href="mailto:[email protected]">Xie, Jiyun</a>
* @version 1.0.0, Date: 2012-6-1
*/
public class RpcClient implements PoolableInvocationHandler, IPacketHandler {
private static final Logger LOG = LoggerFactory.getLogger(RpcClient.class);
/**
* Save the execution map.
*/
private final Map<Method, Short> executeMap = new HashMap<Method, Short>();
/**
* The serial generator.
*/
private final AtomicInteger auto = new AtomicInteger(1);
/**
* The time to sleep between retry.
*/
private int sleepBetweenRetryTime = Config.RPC_SLEEP_BT_RETRY;
/**
* Times to retry get connected.
*/
private int connectRetryTimes = Config.RPC_CONNECT_RETRY_TIMES;
/**
* The PacketClient to send and receive Rpc packets.
*/
private final IClient client;
/**
* The RPC invoker to do the real method invoke.
*/
private final RemoteInvoker invoker;
/**
* The data translator.
*/
private final IConverter converter;
/**
* The status of this Client.
*/
private Status connStatus;
/**
* The connection status of this RpcClient.
*
* @author <a href="mailto:[email protected]">Xie, Jiyun</a>
* @version 1.0.0, Date: 2012-6-2
*/
public static enum Status {
INNITIAL, CONNECTED, CLOSED
}
/**
* Create a RpcClient with this client as the backed communication tool.
* The PacketClient will be managed internally, please use this.connect() to connect.
*
* @param client the backed communication tool
* @param invoker use this to send packets to server and wait for response
* @param converter use this to serialize data
*/
public RpcClient(IClient client, RemoteInvoker invoker, IConverter converter) {
super();
this.client = client;
this.invoker = invoker;
this.converter = converter;
this.client.setPacketHandler(this);
this.connStatus = Status.INNITIAL;
}
/**
* Connect the backed communication client, and set the internal status.
* @throws IOException
*/
public void connect() throws IOException {
this.client.connect();
this.connStatus = Status.CONNECTED;
}
/**
* Stop this client, and stop the backed communication client.
*/
public void stop() {
this.connStatus = Status.CLOSED;
this.client.stop();
}
/**
* Get the Rpc Service Client Stub powered by this rpc client.
*
* @param c The interface you want to have stub.
* @return the stub
*/
@SuppressWarnings("unchecked")
public <T> T getService(Class<T> c) {
this.addInferface(c);
return (T) Proxy.newProxyInstance(RpcClient.class.getClassLoader(),
new Class[] {c}, this);
}
/**
* Check the client status before doing remote call and after response.
*/
private void checkStatus() {
RpcException rep = null;
switch (connStatus) {
case INNITIAL:
rep = new RpcException("Client not connected.", RpcException.Type.NOT_CONNECTED, null);
throw rep;
case CLOSED:
rep = new RpcException("Client closed.", RpcException.Type.CONNECTION_CLOSED, null);
throw rep;
}
}
/**
* This is the override of super method.
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
checkStatus();
RpcException rep = null;
Short rei = executeMap.get(method);
if (rei != null) {
// 1. Prepare parameters
byte[] arr;
if (args == null || args.length == 0) {
arr = new byte[0];
} else {
arr = converter.serializeParams(args);
}
// 2. Create PacketData
PacketData rc = new PacketData(rei, arr);
// 3. Generate serial number
serialPacket(rc);
// 4. Invoke, send packet to server and wait for result
PacketData sc = invoker.invoke(rc, client);
// 5. Process result.
if (sc == null) {
checkStatus();
rep = new RpcException("Timeout for this remote procedure call.",
RpcException.Type.TIMEOUT, null);
throw rep;
} else {
int exp = sc.getReserved() - rc.getReserved();
boolean isEx = false;
// 127 + 1 = -128
// -128 - 127 = -255
if (exp == 1 || exp == -255) {
isEx = true;
}
+ if (sc.getLength() == 0) {
+ return null;
+ }
Object ret = prepareReturn(sc.getData(), method.getGenericReturnType(), isEx);
if (isEx) {
rep = (RpcException) ret;
throw rep;
}
return ret;
}
} else {
rep = new RpcException("The method you want to invoke is not a remote procedure call.",
RpcException.Type.METHOD_NOT_FOUND, null);
throw rep;
}
}
/**
* Generate serial number
* The serial number will be 1, 3, 5, ...
*
* @param rc
*/
private void serialPacket(PacketData rc) {
short seri = (short) (auto.getAndAdd(2));
rc.setReserved((byte) seri);
rc.setVersion((byte) (seri >> 8));
}
/**
* Set the Rpc Configs, this method will parse all the configurations and generate execute map.
* @param interfs
*/
public void addInferface(Class<?> interfs) {
Method[] arr = MethodUtil.getMethods(interfs);
for (Method m : arr) {
if (m.isAnnotationPresent(RpcMethod.class)) {
RpcMethod rp = m.getAnnotation(RpcMethod.class);
Short rei = executeMap.put(m, rp.value());
if (rei != null) {
LOG.warn("Duplicate configuration for code: {}", rp.value());
}
}
} // End of arr
}
/**
* De-serialize returned byte array into objects.
*
* @param ret
* @param type
* @param isEx
* @return the object
* @throws Exception
*/
protected Object prepareReturn(byte[] ret, Type type, boolean isEx) throws Exception {
if (isEx) {
type = RpcException.class;
} else if (type == null || type.toString().equalsIgnoreCase("void")) {
return null;
}
return converter.prepareReturn(ret, type);
}
/**
* We delegate all read packets to invoker.
*
* Override super method
* @see org.apache.niolex.network.IPacketHandler#handleRead(org.apache.niolex.network.PacketData, org.apache.niolex.network.IPacketWriter)
*/
@Override
public void handleRead(PacketData sc, IPacketWriter wt) {
this.invoker.handleRead(sc, wt);
}
/**
* We will retry to connect to server in this method.
*
* Override super method
* @see org.apache.niolex.network.IPacketHandler#handleClose(org.apache.niolex.network.IPacketWriter)
*/
@Override
public void handleClose(IPacketWriter wt) {
if (this.connStatus == Status.CLOSED) {
return;
}
this.connStatus = Status.INNITIAL;
if (!retryConnect()) {
LOG.error("We can not re-connect to server after retry times, RpcClient with stop.");
// Try to shutdown this Client, inform all the threads.
this.connStatus = Status.CLOSED;
this.client.stop();
this.invoker.handleClose(wt);
}
}
/**
* Try to re-connect to server.
*
* @return true if connected
*/
private boolean retryConnect() {
for (int i = 0; i < connectRetryTimes; ++i) {
SystemUtil.sleep(sleepBetweenRetryTime);
LOG.info("RPC Client try to reconnect to server round {} ...", i);
try {
client.connect();
this.connStatus = Status.CONNECTED;
return true;
} catch (IOException e) {
// Not connected.
LOG.info("Try to re-connect to server failed. {}", e.toString());
}
}
return false;
}
/**
* Get Connection Status of this rpc client.
*
* @return current status
*/
public Status getConnStatus() {
return connStatus;
}
/**
* Get Connection Status of this rpc client.
*
* @return true if this RpcClient is valid and ready to work.
*/
public boolean isValid() {
return connStatus == Status.CONNECTED;
}
/**
* @return The string representation of the remote peer. i.e. The IP address.
*/
public String getRemoteName() {
return client.getRemoteName();
}
/**
* Set the time in milliseconds that client with sleep between retry to connect
* to server.
*
* @param sleepBetweenRetryTime
*/
public void setSleepBetweenRetryTime(int sleepBetweenRetryTime) {
this.sleepBetweenRetryTime = sleepBetweenRetryTime;
}
/**
* Set retry times.
*
* @param connectRetryTimes
*/
public void setConnectRetryTimes(int connectRetryTimes) {
this.connectRetryTimes = connectRetryTimes;
}
/**
* Set the socket connect timeout.
* This method must be called before {@link #connect()}
*
* @param timeout
*/
public void setConnectTimeout(int timeout) {
this.client.setConnectTimeout(timeout);
}
/**
* Set the server Internet address this client want to connect
* This method must be called before {@link #connect()}
*
* @param serverAddress
*/
public void setServerAddress(InetSocketAddress serverAddress) {
client.setServerAddress(serverAddress);
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
checkStatus();
RpcException rep = null;
Short rei = executeMap.get(method);
if (rei != null) {
// 1. Prepare parameters
byte[] arr;
if (args == null || args.length == 0) {
arr = new byte[0];
} else {
arr = converter.serializeParams(args);
}
// 2. Create PacketData
PacketData rc = new PacketData(rei, arr);
// 3. Generate serial number
serialPacket(rc);
// 4. Invoke, send packet to server and wait for result
PacketData sc = invoker.invoke(rc, client);
// 5. Process result.
if (sc == null) {
checkStatus();
rep = new RpcException("Timeout for this remote procedure call.",
RpcException.Type.TIMEOUT, null);
throw rep;
} else {
int exp = sc.getReserved() - rc.getReserved();
boolean isEx = false;
// 127 + 1 = -128
// -128 - 127 = -255
if (exp == 1 || exp == -255) {
isEx = true;
}
Object ret = prepareReturn(sc.getData(), method.getGenericReturnType(), isEx);
if (isEx) {
rep = (RpcException) ret;
throw rep;
}
return ret;
}
} else {
rep = new RpcException("The method you want to invoke is not a remote procedure call.",
RpcException.Type.METHOD_NOT_FOUND, null);
throw rep;
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
checkStatus();
RpcException rep = null;
Short rei = executeMap.get(method);
if (rei != null) {
// 1. Prepare parameters
byte[] arr;
if (args == null || args.length == 0) {
arr = new byte[0];
} else {
arr = converter.serializeParams(args);
}
// 2. Create PacketData
PacketData rc = new PacketData(rei, arr);
// 3. Generate serial number
serialPacket(rc);
// 4. Invoke, send packet to server and wait for result
PacketData sc = invoker.invoke(rc, client);
// 5. Process result.
if (sc == null) {
checkStatus();
rep = new RpcException("Timeout for this remote procedure call.",
RpcException.Type.TIMEOUT, null);
throw rep;
} else {
int exp = sc.getReserved() - rc.getReserved();
boolean isEx = false;
// 127 + 1 = -128
// -128 - 127 = -255
if (exp == 1 || exp == -255) {
isEx = true;
}
if (sc.getLength() == 0) {
return null;
}
Object ret = prepareReturn(sc.getData(), method.getGenericReturnType(), isEx);
if (isEx) {
rep = (RpcException) ret;
throw rep;
}
return ret;
}
} else {
rep = new RpcException("The method you want to invoke is not a remote procedure call.",
RpcException.Type.METHOD_NOT_FOUND, null);
throw rep;
}
}
|
diff --git a/src/book/Author.java b/src/book/Author.java
index a558d83..ef9e78b 100644
--- a/src/book/Author.java
+++ b/src/book/Author.java
@@ -1,177 +1,177 @@
package book;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
/**
@author Team Cosmos:
Erni Ali,
Phil Vaca,
Randy Zaatri
Solution for CS157B Project #1
Author.java is a class that creates the Author entity table.
It stores the firstname and last name of authors and authors can write
multiple books.
*/
@Entity
public class Author
{
private String firstname;
private String lastname;
private long id;
private List<Book> books = new ArrayList<>();
public Author()
{
}
public Author(String firstname, String lastname)
{
this.firstname = firstname;
this.lastname = lastname;
}
@ManyToMany
@JoinTable(name="Book_Author",
joinColumns={@JoinColumn(name="author_id")},
inverseJoinColumns={@JoinColumn(name="book_id")})
public List<Book> getBooks()
{
return books;
}
public void setBooks(List<Book> books)
{
this.books = books;
}
@Id
@GeneratedValue
@Column(name = "author_id")
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
@Column(name = "first_name")
public String getFirstname()
{
return firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
@Column(name = "last_name")
public String getLastname()
{
return lastname;
}
public void setLastname(String lastname)
{
this.lastname = lastname;
}
/**
Load the author table
*/
public static void load()
{
Session session = HibernateContext.getSession();
Transaction tx = session.beginTransaction();
{
session.save(new Author("Stephen", "King"));
session.save(new Author("James", "Hilton"));
session.save(new Author("Felix", "Salten"));
session.save(new Author("Hector", "Garcia-Milina"));
session.save(new Author("Jeffry", "Ullman"));
session.save(new Author("Jennifer", "Widom"));
session.save(new Author("Prentice", "Hall"));
}
tx.commit();
session.close();
System.out.println("Author table loaded.");
}
/**
Fetch the author with a matching name.
@param firstname the first name of author to match.
@param lastname the last name of author to match.
@return the author or null.
*/
public static Author find(String firstname, String lastname)
{
// Query by example.
Author prototype = new Author();
prototype.setFirstname(firstname);
prototype.setLastname(lastname);
Example example = Example.create(prototype);
Session session = HibernateContext.getSession();
Criteria criteria = session.createCriteria(Author.class);
criteria.add(example);
Author author = (Author) criteria.uniqueResult();
session.close();
return author;
}
/**
List the titles by author sorted by first name.
*/
public static void list()
{
Session session = HibernateContext.getSession();
Criteria criteria = session.createCriteria(Author.class);
- criteria.addOrder(Order.asc("firstName"));
+ criteria.addOrder(Order.asc("firstname"));
List<Author> authors = criteria.list();
System.out.println("Titles that are written by Author.");
// Loop over each student.
for (Author author : authors)
{
author.print();
for (Book books : author.getBooks())
{
System.out.printf(" Books: %s (%s)\n", books.getTitle(),
books.getPublishedDate());
}
}
}
/**
Print the id, first name, and last name of authors.
*/
private void print()
{
System.out.printf("%d: %s %s\n", id, firstname, lastname);
}
}
| true | true | public static void list()
{
Session session = HibernateContext.getSession();
Criteria criteria = session.createCriteria(Author.class);
criteria.addOrder(Order.asc("firstName"));
List<Author> authors = criteria.list();
System.out.println("Titles that are written by Author.");
// Loop over each student.
for (Author author : authors)
{
author.print();
for (Book books : author.getBooks())
{
System.out.printf(" Books: %s (%s)\n", books.getTitle(),
books.getPublishedDate());
}
}
}
| public static void list()
{
Session session = HibernateContext.getSession();
Criteria criteria = session.createCriteria(Author.class);
criteria.addOrder(Order.asc("firstname"));
List<Author> authors = criteria.list();
System.out.println("Titles that are written by Author.");
// Loop over each student.
for (Author author : authors)
{
author.print();
for (Book books : author.getBooks())
{
System.out.printf(" Books: %s (%s)\n", books.getTitle(),
books.getPublishedDate());
}
}
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/client/AuthenticationRequest.java b/hazelcast/src/main/java/com/hazelcast/client/AuthenticationRequest.java
index ea37f2cbc5..1c59d9b41f 100644
--- a/hazelcast/src/main/java/com/hazelcast/client/AuthenticationRequest.java
+++ b/hazelcast/src/main/java/com/hazelcast/client/AuthenticationRequest.java
@@ -1,176 +1,177 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.client;
import com.hazelcast.cluster.ClusterService;
import com.hazelcast.config.GroupConfig;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import com.hazelcast.security.Credentials;
import com.hazelcast.security.SecurityContext;
import com.hazelcast.security.UsernamePasswordCredentials;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
public final class AuthenticationRequest extends CallableClientRequest implements Portable {
private Credentials credentials;
private ClientPrincipal principal;
private boolean reAuth;
private boolean firstConnection = false;
public AuthenticationRequest() {
}
public AuthenticationRequest(Credentials credentials) {
this.credentials = credentials;
}
public AuthenticationRequest(Credentials credentials, ClientPrincipal principal) {
this.credentials = credentials;
this.principal = principal;
}
public Object call() throws Exception {
ClientEngineImpl clientEngine = getService();
Connection connection = endpoint.getConnection();
ILogger logger = clientEngine.getLogger(getClass());
clientEngine.sendResponse(endpoint, clientEngine.getThisAddress());
boolean authenticated;
if (credentials == null) {
authenticated = false;
logger.log(Level.SEVERE, "Could not retrieve Credentials object!");
} else if (clientEngine.getSecurityContext() != null) {
credentials.setEndpoint(connection.getInetAddress().getHostAddress());
try {
SecurityContext securityContext = clientEngine.getSecurityContext();
LoginContext lc = securityContext.createClientLoginContext(credentials);
lc.login();
endpoint.setLoginContext(lc);
authenticated = true;
} catch (LoginException e) {
logger.log(Level.WARNING, e.getMessage(), e);
authenticated = false;
}
} else {
if (credentials instanceof UsernamePasswordCredentials) {
final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
GroupConfig groupConfig = clientEngine.getConfig().getGroupConfig();
final String nodeGroupName = groupConfig.getName();
final String nodeGroupPassword = groupConfig.getPassword();
authenticated = (nodeGroupName.equals(usernamePasswordCredentials.getUsername())
&& nodeGroupPassword.equals(usernamePasswordCredentials.getPassword()));
} else {
authenticated = false;
logger.log(Level.SEVERE, "Hazelcast security is disabled.\nUsernamePasswordCredentials or cluster " +
"group-name and group-password should be used for authentication!\n" +
"Current credentials type is: " + credentials.getClass().getName());
}
}
logger.log((authenticated ? Level.INFO : Level.WARNING), "Received auth from " + connection
+ ", " + (authenticated ? "successfully authenticated" : "authentication failed"));
if (authenticated) {
if (principal != null) {
final ClusterService clusterService = clientEngine.getClusterService();
if (reAuth) {
//TODO @ali check reAuth
// if (clusterService.getMember(principal.getOwnerUuid()) != null) {
// return new AuthenticationException("Owner member is already member of this cluster, cannot re-auth!");
// } else {
principal = new ClientPrincipal(principal.getUuid(), clientEngine.getLocalMember().getUuid());
final Collection<MemberImpl> members = clientEngine.getClusterService().getMemberList();
for (MemberImpl member : members) {
if (!member.localMember()) {
clientEngine.sendOperation(new ClientReAuthOperation(principal.getUuid(), firstConnection), member.getAddress());
}
}
// }
- } else if (clusterService.getMember(principal.getOwnerUuid()) == null) {
- clientEngine.removeEndpoint(connection);
- return new AuthenticationException("Owner member is not member of this cluster!");
}
+// else if (clusterService.getMember(principal.getOwnerUuid()) == null) {
+// clientEngine.removeEndpoint(connection);
+// return new AuthenticationException("Owner member is not member of this cluster!");
+// }
}
if (principal == null) {
principal = new ClientPrincipal(endpoint.getUuid(), clientEngine.getLocalMember().getUuid());
}
endpoint.authenticated(principal, firstConnection);
clientEngine.bind(endpoint);
return principal;
} else {
clientEngine.removeEndpoint(connection);
return new AuthenticationException("Invalid credentials!");
}
}
public String getServiceName() {
return ClientEngineImpl.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return 2;
}
public void setReAuth(boolean reAuth) {
this.reAuth = reAuth;
}
public boolean isFirstConnection() {
return firstConnection;
}
public void setFirstConnection(boolean firstConnection) {
this.firstConnection = firstConnection;
}
@Override
public void writePortable(PortableWriter writer) throws IOException {
writer.writePortable("credentials", (Portable) credentials);
if (principal != null) {
writer.writePortable("principal", principal);
} else {
writer.writeNullPortable("principal", ClientPortableHook.ID, ClientPortableHook.PRINCIPAL);
}
writer.writeBoolean("reAuth", reAuth);
writer.writeBoolean("firstConnection", firstConnection);
}
@Override
public void readPortable(PortableReader reader) throws IOException {
credentials = (Credentials) reader.readPortable("credentials");
principal = reader.readPortable("principal");
reAuth = reader.readBoolean("reAuth");
firstConnection = reader.readBoolean("firstConnection");
}
}
| false | true | public Object call() throws Exception {
ClientEngineImpl clientEngine = getService();
Connection connection = endpoint.getConnection();
ILogger logger = clientEngine.getLogger(getClass());
clientEngine.sendResponse(endpoint, clientEngine.getThisAddress());
boolean authenticated;
if (credentials == null) {
authenticated = false;
logger.log(Level.SEVERE, "Could not retrieve Credentials object!");
} else if (clientEngine.getSecurityContext() != null) {
credentials.setEndpoint(connection.getInetAddress().getHostAddress());
try {
SecurityContext securityContext = clientEngine.getSecurityContext();
LoginContext lc = securityContext.createClientLoginContext(credentials);
lc.login();
endpoint.setLoginContext(lc);
authenticated = true;
} catch (LoginException e) {
logger.log(Level.WARNING, e.getMessage(), e);
authenticated = false;
}
} else {
if (credentials instanceof UsernamePasswordCredentials) {
final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
GroupConfig groupConfig = clientEngine.getConfig().getGroupConfig();
final String nodeGroupName = groupConfig.getName();
final String nodeGroupPassword = groupConfig.getPassword();
authenticated = (nodeGroupName.equals(usernamePasswordCredentials.getUsername())
&& nodeGroupPassword.equals(usernamePasswordCredentials.getPassword()));
} else {
authenticated = false;
logger.log(Level.SEVERE, "Hazelcast security is disabled.\nUsernamePasswordCredentials or cluster " +
"group-name and group-password should be used for authentication!\n" +
"Current credentials type is: " + credentials.getClass().getName());
}
}
logger.log((authenticated ? Level.INFO : Level.WARNING), "Received auth from " + connection
+ ", " + (authenticated ? "successfully authenticated" : "authentication failed"));
if (authenticated) {
if (principal != null) {
final ClusterService clusterService = clientEngine.getClusterService();
if (reAuth) {
//TODO @ali check reAuth
// if (clusterService.getMember(principal.getOwnerUuid()) != null) {
// return new AuthenticationException("Owner member is already member of this cluster, cannot re-auth!");
// } else {
principal = new ClientPrincipal(principal.getUuid(), clientEngine.getLocalMember().getUuid());
final Collection<MemberImpl> members = clientEngine.getClusterService().getMemberList();
for (MemberImpl member : members) {
if (!member.localMember()) {
clientEngine.sendOperation(new ClientReAuthOperation(principal.getUuid(), firstConnection), member.getAddress());
}
}
// }
} else if (clusterService.getMember(principal.getOwnerUuid()) == null) {
clientEngine.removeEndpoint(connection);
return new AuthenticationException("Owner member is not member of this cluster!");
}
}
if (principal == null) {
principal = new ClientPrincipal(endpoint.getUuid(), clientEngine.getLocalMember().getUuid());
}
endpoint.authenticated(principal, firstConnection);
clientEngine.bind(endpoint);
return principal;
} else {
clientEngine.removeEndpoint(connection);
return new AuthenticationException("Invalid credentials!");
}
}
| public Object call() throws Exception {
ClientEngineImpl clientEngine = getService();
Connection connection = endpoint.getConnection();
ILogger logger = clientEngine.getLogger(getClass());
clientEngine.sendResponse(endpoint, clientEngine.getThisAddress());
boolean authenticated;
if (credentials == null) {
authenticated = false;
logger.log(Level.SEVERE, "Could not retrieve Credentials object!");
} else if (clientEngine.getSecurityContext() != null) {
credentials.setEndpoint(connection.getInetAddress().getHostAddress());
try {
SecurityContext securityContext = clientEngine.getSecurityContext();
LoginContext lc = securityContext.createClientLoginContext(credentials);
lc.login();
endpoint.setLoginContext(lc);
authenticated = true;
} catch (LoginException e) {
logger.log(Level.WARNING, e.getMessage(), e);
authenticated = false;
}
} else {
if (credentials instanceof UsernamePasswordCredentials) {
final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
GroupConfig groupConfig = clientEngine.getConfig().getGroupConfig();
final String nodeGroupName = groupConfig.getName();
final String nodeGroupPassword = groupConfig.getPassword();
authenticated = (nodeGroupName.equals(usernamePasswordCredentials.getUsername())
&& nodeGroupPassword.equals(usernamePasswordCredentials.getPassword()));
} else {
authenticated = false;
logger.log(Level.SEVERE, "Hazelcast security is disabled.\nUsernamePasswordCredentials or cluster " +
"group-name and group-password should be used for authentication!\n" +
"Current credentials type is: " + credentials.getClass().getName());
}
}
logger.log((authenticated ? Level.INFO : Level.WARNING), "Received auth from " + connection
+ ", " + (authenticated ? "successfully authenticated" : "authentication failed"));
if (authenticated) {
if (principal != null) {
final ClusterService clusterService = clientEngine.getClusterService();
if (reAuth) {
//TODO @ali check reAuth
// if (clusterService.getMember(principal.getOwnerUuid()) != null) {
// return new AuthenticationException("Owner member is already member of this cluster, cannot re-auth!");
// } else {
principal = new ClientPrincipal(principal.getUuid(), clientEngine.getLocalMember().getUuid());
final Collection<MemberImpl> members = clientEngine.getClusterService().getMemberList();
for (MemberImpl member : members) {
if (!member.localMember()) {
clientEngine.sendOperation(new ClientReAuthOperation(principal.getUuid(), firstConnection), member.getAddress());
}
}
// }
}
// else if (clusterService.getMember(principal.getOwnerUuid()) == null) {
// clientEngine.removeEndpoint(connection);
// return new AuthenticationException("Owner member is not member of this cluster!");
// }
}
if (principal == null) {
principal = new ClientPrincipal(endpoint.getUuid(), clientEngine.getLocalMember().getUuid());
}
endpoint.authenticated(principal, firstConnection);
clientEngine.bind(endpoint);
return principal;
} else {
clientEngine.removeEndpoint(connection);
return new AuthenticationException("Invalid credentials!");
}
}
|
diff --git a/src/java/org/apache/cassandra/db/compaction/LeveledManifest.java b/src/java/org/apache/cassandra/db/compaction/LeveledManifest.java
index fcbd5cb4a..5f221099f 100644
--- a/src/java/org/apache/cassandra/db/compaction/LeveledManifest.java
+++ b/src/java/org/apache/cassandra/db/compaction/LeveledManifest.java
@@ -1,609 +1,609 @@
package org.apache.cassandra.db.compaction;
/*
*
* 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 java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.util.*;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.SSTable;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import static org.apache.cassandra.db.compaction.AbstractCompactionStrategy.filterSuspectSSTables;
public class LeveledManifest
{
private static final Logger logger = LoggerFactory.getLogger(LeveledManifest.class);
public static final String EXTENSION = ".json";
/**
* limit the number of L0 sstables we do at once, because compaction bloom filter creation
* uses a pessimistic estimate of how many keys overlap (none), so we risk wasting memory
* or even OOMing when compacting highly overlapping sstables
*/
private static final int MAX_COMPACTING_L0 = 32;
private final ColumnFamilyStore cfs;
private final List<SSTableReader>[] generations;
private final Map<SSTableReader, Integer> sstableGenerations;
private final RowPosition[] lastCompactedKeys;
private final int maxSSTableSizeInBytes;
private LeveledManifest(ColumnFamilyStore cfs, int maxSSTableSizeInMB)
{
this.cfs = cfs;
this.maxSSTableSizeInBytes = maxSSTableSizeInMB * 1024 * 1024;
// allocate enough generations for a PB of data
int n = (int) Math.log10(1000 * 1000 * 1000 / maxSSTableSizeInMB);
generations = new List[n];
lastCompactedKeys = new RowPosition[n];
for (int i = 0; i < generations.length; i++)
{
generations[i] = new ArrayList<SSTableReader>();
lastCompactedKeys[i] = cfs.partitioner.getMinimumToken().minKeyBound();
}
sstableGenerations = new HashMap<SSTableReader, Integer>();
}
static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize)
{
return create(cfs, maxSSTableSize, cfs.getSSTables());
}
public static LeveledManifest create(ColumnFamilyStore cfs, int maxSSTableSize, Iterable<SSTableReader> sstables)
{
LeveledManifest manifest = new LeveledManifest(cfs, maxSSTableSize);
load(cfs, manifest, sstables);
// ensure all SSTables are in the manifest
for (SSTableReader ssTableReader : sstables)
{
if (manifest.levelOf(ssTableReader) < 0)
manifest.add(ssTableReader);
}
return manifest;
}
private static void load(ColumnFamilyStore cfs, LeveledManifest manifest, Iterable<SSTableReader> sstables)
{
File manifestFile = tryGetManifest(cfs);
if (manifestFile == null)
return;
ObjectMapper m = new ObjectMapper();
try
{
JsonNode rootNode = m.readValue(manifestFile, JsonNode.class);
JsonNode generations = rootNode.get("generations");
assert generations.isArray();
for (JsonNode generation : generations)
{
int level = generation.get("generation").getIntValue();
JsonNode generationValues = generation.get("members");
for (JsonNode generationValue : generationValues)
{
for (SSTableReader ssTableReader : sstables)
{
if (ssTableReader.descriptor.generation == generationValue.getIntValue())
{
logger.debug("Loading {} at L{}", ssTableReader, level);
manifest.add(ssTableReader, level);
}
}
}
}
}
catch (Exception e)
{
// TODO try to recover -old first
logger.error("Manifest present but corrupt. Cassandra will compact levels from scratch", e);
}
}
public synchronized void add(SSTableReader reader)
{
logDistribution();
logger.debug("Adding {} to L0", reader);
add(reader, 0);
serialize();
}
/**
* if the number of SSTables in the current compacted set *by itself* exceeds the target level's
* (regardless of the level's current contents), find an empty level instead
*/
private int skipLevels(int newLevel, Iterable<SSTableReader> added)
{
while (maxBytesForLevel(newLevel) < SSTableReader.getTotalBytes(added)
&& generations[(newLevel + 1)].isEmpty())
{
newLevel++;
}
return newLevel;
}
public synchronized void promote(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
assert !Iterables.isEmpty(removed); // use add() instead of promote when adding new sstables
logDistribution();
if (logger.isDebugEnabled())
logger.debug("Replacing [" + toString(removed) + "]");
// the level for the added sstables is the max of the removed ones,
// plus one if the removed were all on the same level
int minimumLevel = Integer.MAX_VALUE;
int maximumLevel = 0;
for (SSTableReader sstable : removed)
{
int thisLevel = remove(sstable);
assert thisLevel >= 0;
maximumLevel = Math.max(maximumLevel, thisLevel);
minimumLevel = Math.min(minimumLevel, thisLevel);
}
// it's valid to do a remove w/o an add (e.g. on truncate)
if (!added.iterator().hasNext())
return;
int newLevel;
if (minimumLevel == 0 && maximumLevel == 0 && SSTable.getTotalBytes(removed) <= maxSSTableSizeInBytes)
{
// special case for tiny L0 sstables; see CASSANDRA-4341
newLevel = 0;
}
else
{
newLevel = minimumLevel == maximumLevel ? maximumLevel + 1 : maximumLevel;
newLevel = skipLevels(newLevel, added);
assert newLevel > 0;
}
if (logger.isDebugEnabled())
logger.debug("Adding [{}] at L{}", toString(added), newLevel);
lastCompactedKeys[minimumLevel] = SSTable.sstableOrdering.max(added).last;
for (SSTableReader ssTableReader : added)
add(ssTableReader, newLevel);
// Fix overlapping sstables from CASSANDRA-4321/4411
if (newLevel != 0)
repairOverlappingSSTables(newLevel);
serialize();
}
public synchronized void repairOverlappingSSTables(int level)
{
SSTableReader previous = null;
Collections.sort(generations[level], SSTable.sstableComparator);
List<SSTableReader> outOfOrderSSTables = new ArrayList<SSTableReader>();
for (SSTableReader current : generations[level])
{
if (previous != null && current.first.compareTo(previous.last) <= 0)
{
logger.error(String.format("At level %d, %s [%s, %s] overlaps %s [%s, %s]. This is caused by a bug in Cassandra 1.1.0 .. 1.1.3. Sending back to L0. If you have not yet run scrub, you should do so since you may also have rows out-of-order within an sstable",
level, previous, previous.first, previous.last, current, current.first, current.last));
outOfOrderSSTables.add(current);
}
else
{
previous = current;
}
}
if (!outOfOrderSSTables.isEmpty())
{
for (SSTableReader sstable : outOfOrderSSTables)
sendBackToL0(sstable);
serialize();
}
}
public synchronized void replace(Iterable<SSTableReader> removed, Iterable<SSTableReader> added)
{
// replace is for compaction operation that operate on exactly one sstable, with no merging.
// Thus, removed will be exactly one sstable, and added will be 0 or 1.
assert Iterables.size(removed) == 1 : Iterables.size(removed);
assert Iterables.size(added) <= 1 : Iterables.size(added);
logDistribution();
logger.debug("Replacing {} with {}", removed, added);
int level = remove(removed.iterator().next());
if (!Iterables.isEmpty(added))
add(added.iterator().next(), level);
serialize();
}
private synchronized void sendBackToL0(SSTableReader sstable)
{
remove(sstable);
add(sstable, 0);
}
private String toString(Iterable<SSTableReader> sstables)
{
StringBuilder builder = new StringBuilder();
for (SSTableReader sstable : sstables)
{
builder.append(sstable.descriptor.cfname)
.append('-')
.append(sstable.descriptor.generation)
.append("(L")
.append(levelOf(sstable))
.append("), ");
}
return builder.toString();
}
private long maxBytesForLevel(int level)
{
if (level == 0)
return 4L * maxSSTableSizeInBytes;
double bytes = Math.pow(10, level) * maxSSTableSizeInBytes;
if (bytes > Long.MAX_VALUE)
throw new RuntimeException("At most " + Long.MAX_VALUE + " bytes may be in a compaction level; your maxSSTableSize must be absurdly high to compute " + bytes);
return (long) bytes;
}
public synchronized Collection<SSTableReader> getCompactionCandidates()
{
// LevelDB gives each level a score of how much data it contains vs its ideal amount, and
// compacts the level with the highest score. But this falls apart spectacularly once you
// get behind. Consider this set of levels:
// L0: 988 [ideal: 4]
// L1: 117 [ideal: 10]
// L2: 12 [ideal: 100]
//
// The problem is that L0 has a much higher score (almost 250) than L1 (11), so what we'll
// do is compact a batch of MAX_COMPACTING_L0 sstables with all 117 L1 sstables, and put the
// result (say, 120 sstables) in L1. Then we'll compact the next batch of MAX_COMPACTING_L0,
// and so forth. So we spend most of our i/o rewriting the L1 data with each batch.
//
// If we could just do *all* L0 a single time with L1, that would be ideal. But we can't
// -- see the javadoc for MAX_COMPACTING_L0.
//
// LevelDB's way around this is to simply block writes if L0 compaction falls behind.
// We don't have that luxury.
//
// So instead, we force compacting higher levels first. This may not minimize the number
// of reads done as quickly in the short term, but it minimizes the i/o needed to compact
// optimially which gives us a long term win.
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
if (sstables.isEmpty())
continue; // mostly this just avoids polluting the debug log with zero scores
double score = (double)SSTableReader.getTotalBytes(sstables) / (double)maxBytesForLevel(i);
logger.debug("Compaction score for level {} is {}", i, score);
// L0 gets a special case that if we don't have anything more important to do,
// we'll go ahead and compact if we have more than one sstable
if (score > 1.001 || (i == 0 && sstables.size() > 1))
{
Collection<SSTableReader> candidates = getCandidatesFor(i);
if (logger.isDebugEnabled())
logger.debug("Compaction candidates for L{} are {}", i, toString(candidates));
if (!candidates.isEmpty())
return candidates;
}
}
return Collections.emptyList();
}
public int getLevelSize(int i)
{
return generations.length > i ? generations[i].size() : 0;
}
private void logDistribution()
{
if (logger.isDebugEnabled())
{
for (int i = 0; i < generations.length; i++)
{
if (!generations[i].isEmpty())
{
logger.debug("L{} contains {} SSTables ({} bytes) in {}",
new Object[] {i, generations[i].size(), SSTableReader.getTotalBytes(generations[i]), this});
}
}
}
}
int levelOf(SSTableReader sstable)
{
Integer level = sstableGenerations.get(sstable);
if (level == null)
return -1;
return level.intValue();
}
private int remove(SSTableReader reader)
{
int level = levelOf(reader);
assert level >= 0 : reader + " not present in manifest";
generations[level].remove(reader);
sstableGenerations.remove(reader);
return level;
}
private void add(SSTableReader sstable, int level)
{
assert level < generations.length : "Invalid level " + level + " out of " + (generations.length - 1);
generations[level].add(sstable);
sstableGenerations.put(sstable, Integer.valueOf(level));
}
private static Set<SSTableReader> overlapping(Collection<SSTableReader> candidates, Iterable<SSTableReader> others)
{
assert !candidates.isEmpty();
/*
* Picking each sstable from others that overlap one of the sstable of candidates is not enough
* because you could have the following situation:
* candidates = [ s1(a, c), s2(m, z) ]
* others = [ s3(e, g) ]
* In that case, s2 overlaps none of s1 or s2, but if we compact s1 with s2, the resulting sstable will
* overlap s3, so we must return s3.
*
* Thus, the correct approach is to pick sstables overlapping anything between the first key in all
* the candidate sstables, and the last.
*/
Iterator<SSTableReader> iter = candidates.iterator();
SSTableReader sstable = iter.next();
Token first = sstable.first.token;
Token last = sstable.last.token;
while (iter.hasNext())
{
sstable = iter.next();
first = first.compareTo(sstable.first.token) <= 0 ? first : sstable.first.token;
last = last.compareTo(sstable.last.token) >= 0 ? last : sstable.last.token;
}
return overlapping(first, last, others);
}
private static Set<SSTableReader> overlapping(SSTableReader sstable, Iterable<SSTableReader> others)
{
return overlapping(sstable.first.token, sstable.last.token, others);
}
/**
* @return sstables from @param sstables that contain keys between @param start and @param end, inclusive.
*/
private static Set<SSTableReader> overlapping(Token start, Token end, Iterable<SSTableReader> sstables)
{
assert start.compareTo(end) <= 0;
Set<SSTableReader> overlapped = new HashSet<SSTableReader>();
Bounds<Token> promotedBounds = new Bounds<Token>(start, end);
for (SSTableReader candidate : sstables)
{
Bounds<Token> candidateBounds = new Bounds<Token>(candidate.first.token, candidate.last.token);
if (candidateBounds.intersects(promotedBounds))
overlapped.add(candidate);
}
return overlapped;
}
private Collection<SSTableReader> getCandidatesFor(int level)
{
assert !generations[level].isEmpty();
logger.debug("Choosing candidates for L{}", level);
if (level == 0)
{
// L0 is the dumping ground for new sstables which thus may overlap each other.
//
// We treat L0 compactions specially:
// 1a. add sstables to the candidate set until we have at least maxSSTableSizeInMB
// 1b. prefer choosing older sstables as candidates, to newer ones
// 1c. any L0 sstables that overlap a candidate, will also become candidates
// 2. At most MAX_COMPACTING_L0 sstables from L0 will be compacted at once
// 3. If total candidate size is less than maxSSTableSizeInMB, we won't bother compacting with L1,
// and the result of the compaction will stay in L0 instead of being promoted (see promote())
//
// Note that we ignore suspect-ness of L1 sstables here, since if an L1 sstable is suspect we're
// basically screwed, since we expect all or most L0 sstables to overlap with each L1 sstable.
// So if an L1 sstable is suspect we can't do much besides try anyway and hope for the best.
Set<SSTableReader> candidates = new HashSet<SSTableReader>();
Set<SSTableReader> remaining = new HashSet<SSTableReader>(generations[0]);
List<SSTableReader> ageSortedSSTables = new ArrayList<SSTableReader>(generations[0]);
Collections.sort(ageSortedSSTables, SSTable.maxTimestampComparator);
for (SSTableReader sstable : ageSortedSSTables)
{
if (candidates.contains(sstable))
continue;
for (SSTableReader newCandidate : Sets.union(Collections.singleton(sstable), overlapping(sstable, remaining)))
{
if (!newCandidate.isMarkedSuspect())
{
candidates.add(newCandidate);
remaining.remove(newCandidate);
}
}
if (candidates.size() > MAX_COMPACTING_L0)
{
// limit to only the MAX_COMPACTING_L0 oldest candidates
List<SSTableReader> ageSortedCandidates = new ArrayList<SSTableReader>(candidates);
Collections.sort(ageSortedCandidates, SSTable.maxTimestampComparator);
candidates = new HashSet<SSTableReader>(ageSortedCandidates.subList(0, MAX_COMPACTING_L0));
break;
}
}
if (SSTable.getTotalBytes(candidates) > maxSSTableSizeInBytes)
{
// add sstables from L1 that overlap candidates
candidates.addAll(overlapping(candidates, generations[1]));
}
- return candidates;
+ return candidates.size() > 1 ? candidates : Collections.<SSTableReader>emptyList();
}
// for non-L0 compactions, pick up where we left off last time
Collections.sort(generations[level], SSTable.sstableComparator);
int start = 0; // handles case where the prior compaction touched the very last range
for (int i = 0; i < generations[level].size(); i++)
{
SSTableReader sstable = generations[level].get(i);
if (sstable.first.compareTo(lastCompactedKeys[level]) > 0)
{
start = i;
break;
}
}
// look for a non-suspect table to compact with, starting with where we left off last time,
// and wrapping back to the beginning of the generation if necessary
int i = start;
outer:
while (true)
{
SSTableReader sstable = generations[level].get(i);
Set<SSTableReader> candidates = Sets.union(Collections.singleton(sstable), overlapping(sstable, generations[(level + 1)]));
for (SSTableReader candidate : candidates)
{
if (candidate.isMarkedSuspect())
{
i = (i + 1) % generations[level].size();
if (i == start)
break outer;
continue outer;
}
}
return candidates;
}
// all the sstables were suspect or overlapped with something suspect
return Collections.emptyList();
}
public static File tryGetManifest(ColumnFamilyStore cfs)
{
return cfs.directories.tryGetLeveledManifest();
}
public synchronized void serialize()
{
File manifestFile = cfs.directories.getOrCreateLeveledManifest();
File oldFile = new File(manifestFile.getPath().replace(EXTENSION, "-old.json"));
File tmpFile = new File(manifestFile.getPath().replace(EXTENSION, "-tmp.json"));
JsonFactory f = new JsonFactory();
try
{
JsonGenerator g = f.createJsonGenerator(tmpFile, JsonEncoding.UTF8);
g.useDefaultPrettyPrinter();
g.writeStartObject();
g.writeArrayFieldStart("generations");
for (int level = 0; level < generations.length; level++)
{
g.writeStartObject();
g.writeNumberField("generation", level);
g.writeArrayFieldStart("members");
for (SSTableReader ssTableReader : generations[level])
g.writeNumber(ssTableReader.descriptor.generation);
g.writeEndArray(); // members
g.writeEndObject(); // generation
}
g.writeEndArray(); // for field generations
g.writeEndObject(); // write global object
g.close();
if (oldFile.exists() && manifestFile.exists())
FileUtils.deleteWithConfirm(oldFile);
if (manifestFile.exists())
FileUtils.renameWithConfirm(manifestFile, oldFile);
assert tmpFile.exists();
FileUtils.renameWithConfirm(tmpFile, manifestFile);
logger.debug("Saved manifest {}", manifestFile);
}
catch (IOException e)
{
throw new IOError(e);
}
}
@Override
public String toString()
{
return "Manifest@" + hashCode();
}
public int getLevelCount()
{
for (int i = generations.length - 1; i >= 0; i--)
{
if (generations[i].size() > 0)
return i;
}
return 0;
}
public List<SSTableReader> getLevel(int i)
{
return generations[i];
}
public synchronized int getEstimatedTasks()
{
long tasks = 0;
long[] estimated = new long[generations.length];
for (int i = generations.length - 1; i >= 0; i--)
{
List<SSTableReader> sstables = generations[i];
estimated[i] = Math.max(0L, SSTableReader.getTotalBytes(sstables) - maxBytesForLevel(i)) / maxSSTableSizeInBytes;
tasks += estimated[i];
}
logger.debug("Estimating {} compactions to do for {}.{}",
new Object[] {Arrays.toString(estimated), cfs.table.name, cfs.columnFamily});
return Ints.checkedCast(tasks);
}
}
| true | true | private Collection<SSTableReader> getCandidatesFor(int level)
{
assert !generations[level].isEmpty();
logger.debug("Choosing candidates for L{}", level);
if (level == 0)
{
// L0 is the dumping ground for new sstables which thus may overlap each other.
//
// We treat L0 compactions specially:
// 1a. add sstables to the candidate set until we have at least maxSSTableSizeInMB
// 1b. prefer choosing older sstables as candidates, to newer ones
// 1c. any L0 sstables that overlap a candidate, will also become candidates
// 2. At most MAX_COMPACTING_L0 sstables from L0 will be compacted at once
// 3. If total candidate size is less than maxSSTableSizeInMB, we won't bother compacting with L1,
// and the result of the compaction will stay in L0 instead of being promoted (see promote())
//
// Note that we ignore suspect-ness of L1 sstables here, since if an L1 sstable is suspect we're
// basically screwed, since we expect all or most L0 sstables to overlap with each L1 sstable.
// So if an L1 sstable is suspect we can't do much besides try anyway and hope for the best.
Set<SSTableReader> candidates = new HashSet<SSTableReader>();
Set<SSTableReader> remaining = new HashSet<SSTableReader>(generations[0]);
List<SSTableReader> ageSortedSSTables = new ArrayList<SSTableReader>(generations[0]);
Collections.sort(ageSortedSSTables, SSTable.maxTimestampComparator);
for (SSTableReader sstable : ageSortedSSTables)
{
if (candidates.contains(sstable))
continue;
for (SSTableReader newCandidate : Sets.union(Collections.singleton(sstable), overlapping(sstable, remaining)))
{
if (!newCandidate.isMarkedSuspect())
{
candidates.add(newCandidate);
remaining.remove(newCandidate);
}
}
if (candidates.size() > MAX_COMPACTING_L0)
{
// limit to only the MAX_COMPACTING_L0 oldest candidates
List<SSTableReader> ageSortedCandidates = new ArrayList<SSTableReader>(candidates);
Collections.sort(ageSortedCandidates, SSTable.maxTimestampComparator);
candidates = new HashSet<SSTableReader>(ageSortedCandidates.subList(0, MAX_COMPACTING_L0));
break;
}
}
if (SSTable.getTotalBytes(candidates) > maxSSTableSizeInBytes)
{
// add sstables from L1 that overlap candidates
candidates.addAll(overlapping(candidates, generations[1]));
}
return candidates;
}
// for non-L0 compactions, pick up where we left off last time
Collections.sort(generations[level], SSTable.sstableComparator);
int start = 0; // handles case where the prior compaction touched the very last range
for (int i = 0; i < generations[level].size(); i++)
{
SSTableReader sstable = generations[level].get(i);
if (sstable.first.compareTo(lastCompactedKeys[level]) > 0)
{
start = i;
break;
}
}
// look for a non-suspect table to compact with, starting with where we left off last time,
// and wrapping back to the beginning of the generation if necessary
int i = start;
outer:
while (true)
{
SSTableReader sstable = generations[level].get(i);
Set<SSTableReader> candidates = Sets.union(Collections.singleton(sstable), overlapping(sstable, generations[(level + 1)]));
for (SSTableReader candidate : candidates)
{
if (candidate.isMarkedSuspect())
{
i = (i + 1) % generations[level].size();
if (i == start)
break outer;
continue outer;
}
}
return candidates;
}
// all the sstables were suspect or overlapped with something suspect
return Collections.emptyList();
}
| private Collection<SSTableReader> getCandidatesFor(int level)
{
assert !generations[level].isEmpty();
logger.debug("Choosing candidates for L{}", level);
if (level == 0)
{
// L0 is the dumping ground for new sstables which thus may overlap each other.
//
// We treat L0 compactions specially:
// 1a. add sstables to the candidate set until we have at least maxSSTableSizeInMB
// 1b. prefer choosing older sstables as candidates, to newer ones
// 1c. any L0 sstables that overlap a candidate, will also become candidates
// 2. At most MAX_COMPACTING_L0 sstables from L0 will be compacted at once
// 3. If total candidate size is less than maxSSTableSizeInMB, we won't bother compacting with L1,
// and the result of the compaction will stay in L0 instead of being promoted (see promote())
//
// Note that we ignore suspect-ness of L1 sstables here, since if an L1 sstable is suspect we're
// basically screwed, since we expect all or most L0 sstables to overlap with each L1 sstable.
// So if an L1 sstable is suspect we can't do much besides try anyway and hope for the best.
Set<SSTableReader> candidates = new HashSet<SSTableReader>();
Set<SSTableReader> remaining = new HashSet<SSTableReader>(generations[0]);
List<SSTableReader> ageSortedSSTables = new ArrayList<SSTableReader>(generations[0]);
Collections.sort(ageSortedSSTables, SSTable.maxTimestampComparator);
for (SSTableReader sstable : ageSortedSSTables)
{
if (candidates.contains(sstable))
continue;
for (SSTableReader newCandidate : Sets.union(Collections.singleton(sstable), overlapping(sstable, remaining)))
{
if (!newCandidate.isMarkedSuspect())
{
candidates.add(newCandidate);
remaining.remove(newCandidate);
}
}
if (candidates.size() > MAX_COMPACTING_L0)
{
// limit to only the MAX_COMPACTING_L0 oldest candidates
List<SSTableReader> ageSortedCandidates = new ArrayList<SSTableReader>(candidates);
Collections.sort(ageSortedCandidates, SSTable.maxTimestampComparator);
candidates = new HashSet<SSTableReader>(ageSortedCandidates.subList(0, MAX_COMPACTING_L0));
break;
}
}
if (SSTable.getTotalBytes(candidates) > maxSSTableSizeInBytes)
{
// add sstables from L1 that overlap candidates
candidates.addAll(overlapping(candidates, generations[1]));
}
return candidates.size() > 1 ? candidates : Collections.<SSTableReader>emptyList();
}
// for non-L0 compactions, pick up where we left off last time
Collections.sort(generations[level], SSTable.sstableComparator);
int start = 0; // handles case where the prior compaction touched the very last range
for (int i = 0; i < generations[level].size(); i++)
{
SSTableReader sstable = generations[level].get(i);
if (sstable.first.compareTo(lastCompactedKeys[level]) > 0)
{
start = i;
break;
}
}
// look for a non-suspect table to compact with, starting with where we left off last time,
// and wrapping back to the beginning of the generation if necessary
int i = start;
outer:
while (true)
{
SSTableReader sstable = generations[level].get(i);
Set<SSTableReader> candidates = Sets.union(Collections.singleton(sstable), overlapping(sstable, generations[(level + 1)]));
for (SSTableReader candidate : candidates)
{
if (candidate.isMarkedSuspect())
{
i = (i + 1) % generations[level].size();
if (i == start)
break outer;
continue outer;
}
}
return candidates;
}
// all the sstables were suspect or overlapped with something suspect
return Collections.emptyList();
}
|
diff --git a/src/instructions/USI_SKIPS.java b/src/instructions/USI_SKIPS.java
index 2c217df..4c7174d 100644
--- a/src/instructions/USI_SKIPS.java
+++ b/src/instructions/USI_SKIPS.java
@@ -1,93 +1,93 @@
package instructions;
import assemblernator.Instruction;
import assemblernator.Module;
/**
* The SKIPS instruction.
*
* @author Generate.java
* @date Apr 08, 2012; 08:26:19
* @specRef D9
*/
public class USI_SKIPS extends Instruction {
/**
* 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 = "SKIPS";
/** This instruction's identifying opcode. */
private static final int opCode = 0xFFFFFFFF; // This instruction doesn't have an opcode.
/** The static instance for this instruction. */
static USI_SKIPS staticInstance = new USI_SKIPS(true);
/** @see assemblernator.Instruction#getNewLC(int, Module) */
@Override public int getNewLC(int lc, Module mod) {
- return mod.evaluate(getOperand("FC"));
+ return lc+mod.evaluate(getOperand("FC"));
}
/** @see assemblernator.Instruction#check() */
@Override public boolean check() {
return false; // 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_SKIPS();
}
/**
* 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_SKIPS(boolean ignored) {
super(opId, opCode);
}
/** Default constructor; does nothing. */
private USI_SKIPS() {}
}
| true | true | @Override public int getNewLC(int lc, Module mod) {
return mod.evaluate(getOperand("FC"));
}
| @Override public int getNewLC(int lc, Module mod) {
return lc+mod.evaluate(getOperand("FC"));
}
|
diff --git a/lightfish/src/main/java/org/lightfish/business/monitoring/boundary/MonitoringController.java b/lightfish/src/main/java/org/lightfish/business/monitoring/boundary/MonitoringController.java
index 711a8d8..c4a5a46 100644
--- a/lightfish/src/main/java/org/lightfish/business/monitoring/boundary/MonitoringController.java
+++ b/lightfish/src/main/java/org/lightfish/business/monitoring/boundary/MonitoringController.java
@@ -1,341 +1,341 @@
/*
Copyright 2012 Adam Bien, adam-bien.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.lightfish.business.monitoring.boundary;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.lightfish.business.monitoring.entity.Snapshot;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lightfish.business.monitoring.control.collectors.DataPoint;
import org.lightfish.business.monitoring.control.collectors.ParallelDataCollectionAction;
import org.lightfish.business.monitoring.control.collectors.ParallelDataCollectionExecutor;
import org.lightfish.business.monitoring.entity.Application;
import org.lightfish.business.monitoring.entity.ConnectionPool;
import org.lightfish.business.monitoring.entity.LogRecord;
/**
*
* @author Adam Bien, blog.adam-bien.com
*/
@Singleton
@Path("snapshots")
@Produces(MediaType.APPLICATION_JSON)
public class MonitoringController {
public static final String COMBINED_SNAPSHOT_NAME = "__all__";
@Inject
private Logger LOG;
@Inject
Instance<SnapshotCollector> snapshotCollectorInstance;
@Inject
ParallelDataCollectionExecutor parallelCollector;
@Inject
Instance<ParallelDataCollectionAction> parallelAction;
@PersistenceContext
EntityManager em;
@Inject
@Severity(Severity.Level.HEARTBEAT)
Event<Snapshot> heartBeat;
@Inject
Instance<String[]> serverInstances;
@Inject
Instance<Integer> collectionTimeout;
int nextInstanceIndex = 0;
Map<String, SnapshotCollectionAction> currentCollectionActions = new HashMap<>();
Map<String, Snapshot> currentSnapshots = new HashMap<>();
@Resource
TimerService timerService;
private Timer timer;
@Inject
private Instance<Integer> interval;
public void startTimer() {
ScheduleExpression expression = new ScheduleExpression();
expression.minute("*").second("*/" + interval.get()).hour("*");
this.timer = this.timerService.createCalendarTimer(expression);
}
private void handleCompletedFutures(Boolean wait) {
List<Snapshot> handledSnapshots = new ArrayList<>();
Iterator<Entry<String, SnapshotCollectionAction>> it = currentCollectionActions.entrySet().iterator();
while (it.hasNext()) {
Entry<String, SnapshotCollectionAction> entry = it.next();
try {
DataPoint<Snapshot> dataPoint = null;
if(wait){
dataPoint = entry.getValue().getFuture().get();
}else{
dataPoint = entry.getValue().getFuture().get(0, TimeUnit.NANOSECONDS);
}
LOG.log(Level.FINE, "Handling completed snapshot for {0}", entry.getKey());
it.remove();
if (dataPoint == null) {
LOG.log(Level.WARNING, "An exception occured while retrieving data for "+
entry.getKey(),entry.getValue().getAction().getThrownException());
continue;
}
LOG.fine("Adding completed snapshot to currentSnapshots list");
currentSnapshots.put(entry.getKey(), dataPoint.getValue());
LOG.log(Level.FINER, "Persisting {0}", dataPoint.getValue());
em.persist(dataPoint.getValue());
handledSnapshots.add(dataPoint.getValue());
LOG.log(Level.FINE, "Done handling completed snapshot for {0}", entry.getKey());
} catch (InterruptedException ex) {
LOG.log(Level.FINE, "The snapshot collection for " + entry.getKey() + " was interrupted", ex);
} catch (ExecutionException ex) {
LOG.log(Level.SEVERE, "The snapshot collection for " + entry.getKey() + " resulted in an exception", ex);
entry.getValue().getFuture().cancel(false);
it.remove();
} catch (TimeoutException ex) {
LOG.log(Level.FINEST, "The snapshot collection for " + entry.getKey() + " has not completed", ex);
}
em.flush();
for (Snapshot snapshot : handledSnapshots) {
fireHeartbeat(snapshot);
}
}
}
private void handleTimedOutFutures() {
Calendar timedOutCal = Calendar.getInstance();
timedOutCal.add(Calendar.SECOND, -(collectionTimeout.get()));
Long timedOutTime = timedOutCal.getTimeInMillis();
Iterator<Entry<String, SnapshotCollectionAction>> it = currentCollectionActions.entrySet().iterator();
while (it.hasNext()) {
Entry<String, SnapshotCollectionAction> entry = it.next();
if (timedOutTime > entry.getValue().getStarted()) {
LOG.log(Level.WARNING, "The snapshot collection for {0} timed out.", entry.getKey());
it.remove();
}
}
}
private void handleRoundCompletion() {
LOG.info("All snapshots collected for this round!");
Snapshot combinedSnapshot = combineSnapshots(currentSnapshots.values());
em.persist(combinedSnapshot);
fireHeartbeat(combinedSnapshot);
currentSnapshots.clear();
currentCollectionActions.clear();
}
private void startNextInstanceCollection(int index) {
String currentServerInstance = null;
try{
currentServerInstance = serverInstances.get()[index];
}catch(ArrayIndexOutOfBoundsException oobEx){
LOG.warning("It appears you changed the server instances you are monitoring while the timer is running, this is not recommended...");
return;
}
ParallelDataCollectionAction action = parallelAction.get();
SnapshotCollector collector = snapshotCollectorInstance.get();
collector.setServerInstance(currentServerInstance);
LOG.log(Level.INFO, "Starting data collection for {0}", currentServerInstance);
Future<DataPoint<Snapshot>> future = action.compute(collector);
currentCollectionActions.put(currentServerInstance,
new SnapshotCollectionAction(Calendar.getInstance().getTimeInMillis(), future, action));
}
@Timeout
public void gatherAndPersist() {
handleCompletedFutures(false);
handleTimedOutFutures();
startNextInstanceCollection(nextInstanceIndex++);
if (nextInstanceIndex >= serverInstances.get().length) {
if (!currentCollectionActions.isEmpty()) {
handleCompletedFutures(true);
}
handleRoundCompletion();
nextInstanceIndex = 0;
}
LOG.info(".");
}
private Snapshot combineSnapshots(Collection<Snapshot> snapshots) {
long usedHeapSize = 0l;
int threadCount = 0;
int peakThreadCount = 0;
int totalErrors = 0;
int currentThreadBusy = 0;
int committedTX = 0;
int rolledBackTX = 0;
int queuedConnections = 0;
int activeSessions = 0;
int expiredSessions = 0;
//List<Application> applications = new ArrayList<>();
Map<String, Application> applications = new HashMap<>();
Map<String, ConnectionPool> pools = new HashMap<>();
Set<LogRecord> logs = new TreeSet<>();
for (Snapshot current : snapshots) {
usedHeapSize += current.getUsedHeapSize();
threadCount += current.getThreadCount();
peakThreadCount += current.getPeakThreadCount();
totalErrors += current.getTotalErrors();
currentThreadBusy += current.getCurrentThreadBusy();
committedTX += current.getCommittedTX();
rolledBackTX += current.getRolledBackTX();
queuedConnections += current.getQueuedConnections();
activeSessions += current.getActiveSessions();
expiredSessions += current.getExpiredSessions();
for (Application application : current.getApps()) {
- //Application combinedApp = new Application(application.getApplicationName(), application.getComponents());
- applications.put(application.getApplicationName(), application);
+ Application combinedApp = new Application(application.getApplicationName(), application.getComponents());
+ applications.put(application.getApplicationName(), combinedApp);
}
for (ConnectionPool currentPool : current.getPools()) {
ConnectionPool combinedPool = pools.get(currentPool.getJndiName());
if (combinedPool == null) {
combinedPool = new ConnectionPool();
combinedPool.setJndiName(currentPool.getJndiName());
pools.put(currentPool.getJndiName(), combinedPool);
}
combinedPool.setNumconnfree(currentPool.getNumconnfree() + combinedPool.getNumconnfree());
combinedPool.setNumconnused(currentPool.getNumconnused() + combinedPool.getNumconnused());
combinedPool.setNumpotentialconnleak(currentPool.getNumpotentialconnleak() + combinedPool.getNumpotentialconnleak());
combinedPool.setWaitqueuelength(currentPool.getWaitqueuelength() + combinedPool.getWaitqueuelength());
}
- logs.addAll(current.getLogRecords());
+ //logs.addAll(current.getLogRecords());
}
Snapshot combined = new Snapshot.Builder()
.activeSessions(activeSessions)
.committedTX(committedTX)
.currentThreadBusy(currentThreadBusy)
.expiredSessions(expiredSessions)
.peakThreadCount(peakThreadCount)
.queuedConnections(queuedConnections)
.rolledBackTX(rolledBackTX)
.threadCount(threadCount)
.totalErrors(totalErrors)
.usedHeapSize(usedHeapSize)
.instanceName(COMBINED_SNAPSHOT_NAME)
.logs(new ArrayList<>(logs))
.build();
combined.setApps(new ArrayList(applications.values()));
combined.setPools(new ArrayList(pools.values()));
return combined;
}
@GET
public List<Snapshot> all() {
CriteriaBuilder cb = this.em.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery();
CriteriaQuery<Snapshot> select = q.select(q.from(Snapshot.class));
return this.em.createQuery(select)
.getResultList();
}
@PreDestroy
public void stopTimer() {
if (timer != null) {
try {
this.timer.cancel();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Cannot cancel timer " + this.timer, e);
} finally {
this.timer = null;
}
}
}
private void fireHeartbeat(Snapshot snapshot) {
LOG.log(Level.FINE, "Firing heartbeat for {0}", snapshot.getInstanceName());
try {
heartBeat.fire(snapshot);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Cannot fire heartbeat for " + snapshot.getInstanceName(), e);
}
}
public boolean isRunning() {
return (this.timer != null);
}
private class SnapshotCollectionAction{
private Long started;
private Future<DataPoint<Snapshot>> future;
private ParallelDataCollectionAction action;
public SnapshotCollectionAction(Long started, Future<DataPoint<Snapshot>> future, ParallelDataCollectionAction action) {
this.started = started;
this.future = future;
this.action = action;
}
public Long getStarted() {
return started;
}
public Future<DataPoint<Snapshot>> getFuture() {
return future;
}
public ParallelDataCollectionAction getAction() {
return action;
}
}
}
| false | true | private Snapshot combineSnapshots(Collection<Snapshot> snapshots) {
long usedHeapSize = 0l;
int threadCount = 0;
int peakThreadCount = 0;
int totalErrors = 0;
int currentThreadBusy = 0;
int committedTX = 0;
int rolledBackTX = 0;
int queuedConnections = 0;
int activeSessions = 0;
int expiredSessions = 0;
//List<Application> applications = new ArrayList<>();
Map<String, Application> applications = new HashMap<>();
Map<String, ConnectionPool> pools = new HashMap<>();
Set<LogRecord> logs = new TreeSet<>();
for (Snapshot current : snapshots) {
usedHeapSize += current.getUsedHeapSize();
threadCount += current.getThreadCount();
peakThreadCount += current.getPeakThreadCount();
totalErrors += current.getTotalErrors();
currentThreadBusy += current.getCurrentThreadBusy();
committedTX += current.getCommittedTX();
rolledBackTX += current.getRolledBackTX();
queuedConnections += current.getQueuedConnections();
activeSessions += current.getActiveSessions();
expiredSessions += current.getExpiredSessions();
for (Application application : current.getApps()) {
//Application combinedApp = new Application(application.getApplicationName(), application.getComponents());
applications.put(application.getApplicationName(), application);
}
for (ConnectionPool currentPool : current.getPools()) {
ConnectionPool combinedPool = pools.get(currentPool.getJndiName());
if (combinedPool == null) {
combinedPool = new ConnectionPool();
combinedPool.setJndiName(currentPool.getJndiName());
pools.put(currentPool.getJndiName(), combinedPool);
}
combinedPool.setNumconnfree(currentPool.getNumconnfree() + combinedPool.getNumconnfree());
combinedPool.setNumconnused(currentPool.getNumconnused() + combinedPool.getNumconnused());
combinedPool.setNumpotentialconnleak(currentPool.getNumpotentialconnleak() + combinedPool.getNumpotentialconnleak());
combinedPool.setWaitqueuelength(currentPool.getWaitqueuelength() + combinedPool.getWaitqueuelength());
}
logs.addAll(current.getLogRecords());
}
Snapshot combined = new Snapshot.Builder()
.activeSessions(activeSessions)
.committedTX(committedTX)
.currentThreadBusy(currentThreadBusy)
.expiredSessions(expiredSessions)
.peakThreadCount(peakThreadCount)
.queuedConnections(queuedConnections)
.rolledBackTX(rolledBackTX)
.threadCount(threadCount)
.totalErrors(totalErrors)
.usedHeapSize(usedHeapSize)
.instanceName(COMBINED_SNAPSHOT_NAME)
.logs(new ArrayList<>(logs))
.build();
combined.setApps(new ArrayList(applications.values()));
combined.setPools(new ArrayList(pools.values()));
return combined;
}
| private Snapshot combineSnapshots(Collection<Snapshot> snapshots) {
long usedHeapSize = 0l;
int threadCount = 0;
int peakThreadCount = 0;
int totalErrors = 0;
int currentThreadBusy = 0;
int committedTX = 0;
int rolledBackTX = 0;
int queuedConnections = 0;
int activeSessions = 0;
int expiredSessions = 0;
//List<Application> applications = new ArrayList<>();
Map<String, Application> applications = new HashMap<>();
Map<String, ConnectionPool> pools = new HashMap<>();
Set<LogRecord> logs = new TreeSet<>();
for (Snapshot current : snapshots) {
usedHeapSize += current.getUsedHeapSize();
threadCount += current.getThreadCount();
peakThreadCount += current.getPeakThreadCount();
totalErrors += current.getTotalErrors();
currentThreadBusy += current.getCurrentThreadBusy();
committedTX += current.getCommittedTX();
rolledBackTX += current.getRolledBackTX();
queuedConnections += current.getQueuedConnections();
activeSessions += current.getActiveSessions();
expiredSessions += current.getExpiredSessions();
for (Application application : current.getApps()) {
Application combinedApp = new Application(application.getApplicationName(), application.getComponents());
applications.put(application.getApplicationName(), combinedApp);
}
for (ConnectionPool currentPool : current.getPools()) {
ConnectionPool combinedPool = pools.get(currentPool.getJndiName());
if (combinedPool == null) {
combinedPool = new ConnectionPool();
combinedPool.setJndiName(currentPool.getJndiName());
pools.put(currentPool.getJndiName(), combinedPool);
}
combinedPool.setNumconnfree(currentPool.getNumconnfree() + combinedPool.getNumconnfree());
combinedPool.setNumconnused(currentPool.getNumconnused() + combinedPool.getNumconnused());
combinedPool.setNumpotentialconnleak(currentPool.getNumpotentialconnleak() + combinedPool.getNumpotentialconnleak());
combinedPool.setWaitqueuelength(currentPool.getWaitqueuelength() + combinedPool.getWaitqueuelength());
}
//logs.addAll(current.getLogRecords());
}
Snapshot combined = new Snapshot.Builder()
.activeSessions(activeSessions)
.committedTX(committedTX)
.currentThreadBusy(currentThreadBusy)
.expiredSessions(expiredSessions)
.peakThreadCount(peakThreadCount)
.queuedConnections(queuedConnections)
.rolledBackTX(rolledBackTX)
.threadCount(threadCount)
.totalErrors(totalErrors)
.usedHeapSize(usedHeapSize)
.instanceName(COMBINED_SNAPSHOT_NAME)
.logs(new ArrayList<>(logs))
.build();
combined.setApps(new ArrayList(applications.values()));
combined.setPools(new ArrayList(pools.values()));
return combined;
}
|
diff --git a/src/edacc/EDACCView.java b/src/edacc/EDACCView.java
index 17ede50..588a9e9 100644
--- a/src/edacc/EDACCView.java
+++ b/src/edacc/EDACCView.java
@@ -1,445 +1,445 @@
/*
* EDACCView.java
*/
package edacc;
import edacc.model.DatabaseConnector;
import edacc.model.NoConnectionToDBException;
import java.awt.Component;
import java.sql.SQLException;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observer;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
* The application's main frame.
*/
public class EDACCView extends FrameView implements Observer {
private EDACCExperimentMode experimentMode;
private EDACCManageDBMode manageDBMode;
private EDACCNoMode noMode;
private Component mode;
private javax.swing.GroupLayout mainPanelLayout;
public EDACCView(SingleFrameApplication app) {
super(app);
initComponents();
DatabaseConnector.getInstance().addObserver(this);
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
experimentMode = new EDACCExperimentMode();
manageDBMode = new EDACCManageDBMode();
noMode = new EDACCNoMode();
mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(noMode, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(noMode, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
mode = noMode;
updateConnectionStateView();
btnConnectToDB();
}
private void createDatabaseErrorMessage(SQLException e) {
javax.swing.JOptionPane.showMessageDialog(null, "There was an error while communicating with the database: " +e, "Connection error", javax.swing.JOptionPane.ERROR_MESSAGE);
}
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = EDACCApp.getApplication().getMainFrame();
aboutBox = new EDACCAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
EDACCApp.getApplication().show(aboutBox);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
connectToDBMenuItem = new javax.swing.JMenuItem();
disconnectMenuItem = new javax.swing.JMenuItem();
generateDBMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
gridMenu = new javax.swing.JMenu();
settingsMenuItem = new javax.swing.JMenuItem();
modusMenu = new javax.swing.JMenu();
manageDBModeMenuItem = new javax.swing.JRadioButtonMenuItem();
manageExperimentModeMenuItem = new javax.swing.JRadioButtonMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 1006, Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 630, Short.MAX_VALUE)
);
menuBar.setAutoscrolls(true);
menuBar.setName("menuBar"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCView.class);
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getActionMap(EDACCView.class, this);
connectToDBMenuItem.setAction(actionMap.get("btnConnectToDB")); // NOI18N
connectToDBMenuItem.setText(resourceMap.getString("connectToDBMenuItem.text")); // NOI18N
connectToDBMenuItem.setName("connectToDBMenuItem"); // NOI18N
fileMenu.add(connectToDBMenuItem);
disconnectMenuItem.setAction(actionMap.get("btnDisconnect")); // NOI18N
disconnectMenuItem.setText(resourceMap.getString("disconnectMenuItem.text")); // NOI18N
disconnectMenuItem.setName("disconnectMenuItem"); // NOI18N
fileMenu.add(disconnectMenuItem);
generateDBMenuItem.setAction(actionMap.get("btnGenerateTables")); // NOI18N
generateDBMenuItem.setText(resourceMap.getString("generateDBMenuItem.text")); // NOI18N
generateDBMenuItem.setName("generateDBMenuItem"); // NOI18N
fileMenu.add(generateDBMenuItem);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
gridMenu.setAction(actionMap.get("btnGridSettings")); // NOI18N
gridMenu.setText(resourceMap.getString("gridMenu.text")); // NOI18N
gridMenu.setName("gridMenu"); // NOI18N
settingsMenuItem.setAction(actionMap.get("btnGridSettings")); // NOI18N
settingsMenuItem.setText(resourceMap.getString("settingsMenuItem.text")); // NOI18N
settingsMenuItem.setName("settingsMenuItem"); // NOI18N
gridMenu.add(settingsMenuItem);
menuBar.add(gridMenu);
modusMenu.setText(resourceMap.getString("modusMenu.text")); // NOI18N
modusMenu.setName("modusMenu"); // NOI18N
manageDBModeMenuItem.setAction(actionMap.get("manageDBMode")); // NOI18N
manageDBModeMenuItem.setText(resourceMap.getString("manageDBModeMenuItem.text")); // NOI18N
manageDBModeMenuItem.setName("manageDBModeMenuItem"); // NOI18N
modusMenu.add(manageDBModeMenuItem);
manageExperimentModeMenuItem.setAction(actionMap.get("manageExperimentMode")); // NOI18N
manageExperimentModeMenuItem.setText(resourceMap.getString("manageExperimentModeMenuItem.text")); // NOI18N
manageExperimentModeMenuItem.setName("manageExperimentModeMenuItem"); // NOI18N
modusMenu.add(manageExperimentModeMenuItem);
menuBar.add(modusMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
helpMenu.add(jMenuItem1);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1006, Short.MAX_VALUE)
.add(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusMessageLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 836, Short.MAX_VALUE)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelLayout.createSequentialGroup()
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusMessageLabel)
.add(statusAnimationLabel)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(3, 3, 3))
);
- setComponent(manageDBModeMenuItem);
+ setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
@Action
public void btnConnectToDB() {
if (databaseSettings == null) {
JFrame mainFrame = EDACCApp.getApplication().getMainFrame();
databaseSettings = new EDACCDatabaseSettingsView(mainFrame, true);
databaseSettings.setLocationRelativeTo(mainFrame);
}
EDACCApp.getApplication().show(databaseSettings);
manageDBMode();
}
@Action
public void btnDisconnect() {
try {
DatabaseConnector.getInstance().disconnect();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(EDACCApp.getApplication().getMainFrame(), "An error occured while closing the database connection: \n" + ex.getMessage(), "Couldn't close database connection", JOptionPane.ERROR_MESSAGE);
} finally {
noMode();
}
}
@Action
public void btnGenerateTables() {
if (JOptionPane.showConfirmDialog(mode,
"This will destroy the EDACC tables of your DB an create new ones. Do you wish to continue?",
"Warning!",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {
try {
// User clicked on "Yes"
DatabaseConnector.getInstance().createDBSchema();
} catch (NoConnectionToDBException ex) {
JOptionPane.showMessageDialog(mode,
"Couldn't generate the EDACC tables: No connection to database. Please connect to a database first.",
"Error!", JOptionPane.ERROR_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(mode,
"An error occured while trying to generate the EDACC tables: " + ex.getMessage(),
"Error!", JOptionPane.ERROR_MESSAGE);
} finally {
noMode();
}
}
}
public void noMode() {
manageExperimentModeMenuItem.setSelected(false);
manageDBModeMenuItem.setSelected(false);
mainPanelLayout.replace(mode, noMode);
mode = noMode;
}
@Action
public void manageDBMode() {
/**if (!manageDBModeMenuItem.isSelected()) {
noMode();
return;
}*/
if (manageExperimentModeMenuItem.isSelected()) {
manageExperimentModeMenuItem.setSelected(false);
}
try {
manageDBMode.initialize();
mainPanelLayout.replace(mode, manageDBMode);
mode = manageDBMode;
manageDBModeMenuItem.setSelected(true);
} catch (NoConnectionToDBException ex) {
JOptionPane.showMessageDialog(this.getComponent(), "You have to connect to the database before switching modes", "No database connection", JOptionPane.ERROR_MESSAGE);
noMode();
}
catch (SQLException ex) {
createDatabaseErrorMessage(ex);
noMode();
}
}
@Action
public void manageExperimentMode() {
{
}
if (!manageExperimentModeMenuItem.isSelected()) {
noMode();
return;
}
if (manageDBModeMenuItem.isSelected()) {
manageDBModeMenuItem.setSelected(false);
}
try {
experimentMode.initialize();
mainPanelLayout.replace(mode, experimentMode);
mode = experimentMode;
manageExperimentModeMenuItem.setSelected(true);
} catch (NoConnectionToDBException ex) {
JOptionPane.showMessageDialog(this.getComponent(), "You have to connect to the database before switching modes", "No database connection", JOptionPane.ERROR_MESSAGE);
noMode();
}
catch (SQLException ex) {
createDatabaseErrorMessage(ex);
noMode();
}
}
@Action
public void btnGridSettings() {
if (gridSettings == null) {
JFrame mainFrame = EDACCApp.getApplication().getMainFrame();
gridSettings = new EDACCGridSettingsView(mainFrame, true);
gridSettings.setLocationRelativeTo(mainFrame);
}
try {
gridSettings.loadSettings();
EDACCApp.getApplication().show(gridSettings);
}
catch (NoConnectionToDBException e) {
JOptionPane.showMessageDialog(this.getComponent(), "Couldn't load settings. No connection to database", "No database connection", JOptionPane.ERROR_MESSAGE);
}
catch (SQLException e) {
JOptionPane.showMessageDialog(this.getComponent(), "Error while loading settings: \n" + e.getMessage(), "Error loading settings", JOptionPane.ERROR_MESSAGE);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem connectToDBMenuItem;
private javax.swing.JMenuItem disconnectMenuItem;
private javax.swing.JMenuItem generateDBMenuItem;
private javax.swing.JMenu gridMenu;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JPanel mainPanel;
private javax.swing.JRadioButtonMenuItem manageDBModeMenuItem;
private javax.swing.JRadioButtonMenuItem manageExperimentModeMenuItem;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenu modusMenu;
private javax.swing.JProgressBar progressBar;
private javax.swing.JMenuItem settingsMenuItem;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
private JDialog databaseSettings;
private EDACCGridSettingsView gridSettings;
public void update(Observable o, Object arg) {
// watch connection state
updateConnectionStateView();
}
/**
* Updates the GUI components which are sensitive on the DB connection state.
*/
private void updateConnectionStateView() {
boolean state = DatabaseConnector.getInstance().isConnected();
connectToDBMenuItem.setEnabled(!state);
disconnectMenuItem.setEnabled(state);
generateDBMenuItem.setEnabled(state);
}
}
| true | true | private void initComponents() {
mainPanel = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
connectToDBMenuItem = new javax.swing.JMenuItem();
disconnectMenuItem = new javax.swing.JMenuItem();
generateDBMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
gridMenu = new javax.swing.JMenu();
settingsMenuItem = new javax.swing.JMenuItem();
modusMenu = new javax.swing.JMenu();
manageDBModeMenuItem = new javax.swing.JRadioButtonMenuItem();
manageExperimentModeMenuItem = new javax.swing.JRadioButtonMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 1006, Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 630, Short.MAX_VALUE)
);
menuBar.setAutoscrolls(true);
menuBar.setName("menuBar"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCView.class);
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getActionMap(EDACCView.class, this);
connectToDBMenuItem.setAction(actionMap.get("btnConnectToDB")); // NOI18N
connectToDBMenuItem.setText(resourceMap.getString("connectToDBMenuItem.text")); // NOI18N
connectToDBMenuItem.setName("connectToDBMenuItem"); // NOI18N
fileMenu.add(connectToDBMenuItem);
disconnectMenuItem.setAction(actionMap.get("btnDisconnect")); // NOI18N
disconnectMenuItem.setText(resourceMap.getString("disconnectMenuItem.text")); // NOI18N
disconnectMenuItem.setName("disconnectMenuItem"); // NOI18N
fileMenu.add(disconnectMenuItem);
generateDBMenuItem.setAction(actionMap.get("btnGenerateTables")); // NOI18N
generateDBMenuItem.setText(resourceMap.getString("generateDBMenuItem.text")); // NOI18N
generateDBMenuItem.setName("generateDBMenuItem"); // NOI18N
fileMenu.add(generateDBMenuItem);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
gridMenu.setAction(actionMap.get("btnGridSettings")); // NOI18N
gridMenu.setText(resourceMap.getString("gridMenu.text")); // NOI18N
gridMenu.setName("gridMenu"); // NOI18N
settingsMenuItem.setAction(actionMap.get("btnGridSettings")); // NOI18N
settingsMenuItem.setText(resourceMap.getString("settingsMenuItem.text")); // NOI18N
settingsMenuItem.setName("settingsMenuItem"); // NOI18N
gridMenu.add(settingsMenuItem);
menuBar.add(gridMenu);
modusMenu.setText(resourceMap.getString("modusMenu.text")); // NOI18N
modusMenu.setName("modusMenu"); // NOI18N
manageDBModeMenuItem.setAction(actionMap.get("manageDBMode")); // NOI18N
manageDBModeMenuItem.setText(resourceMap.getString("manageDBModeMenuItem.text")); // NOI18N
manageDBModeMenuItem.setName("manageDBModeMenuItem"); // NOI18N
modusMenu.add(manageDBModeMenuItem);
manageExperimentModeMenuItem.setAction(actionMap.get("manageExperimentMode")); // NOI18N
manageExperimentModeMenuItem.setText(resourceMap.getString("manageExperimentModeMenuItem.text")); // NOI18N
manageExperimentModeMenuItem.setName("manageExperimentModeMenuItem"); // NOI18N
modusMenu.add(manageExperimentModeMenuItem);
menuBar.add(modusMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
helpMenu.add(jMenuItem1);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1006, Short.MAX_VALUE)
.add(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusMessageLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 836, Short.MAX_VALUE)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelLayout.createSequentialGroup()
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusMessageLabel)
.add(statusAnimationLabel)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(3, 3, 3))
);
setComponent(manageDBModeMenuItem);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
mainPanel = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
connectToDBMenuItem = new javax.swing.JMenuItem();
disconnectMenuItem = new javax.swing.JMenuItem();
generateDBMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
gridMenu = new javax.swing.JMenu();
settingsMenuItem = new javax.swing.JMenuItem();
modusMenu = new javax.swing.JMenu();
manageDBModeMenuItem = new javax.swing.JRadioButtonMenuItem();
manageExperimentModeMenuItem = new javax.swing.JRadioButtonMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 1006, Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 630, Short.MAX_VALUE)
);
menuBar.setAutoscrolls(true);
menuBar.setName("menuBar"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCView.class);
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getActionMap(EDACCView.class, this);
connectToDBMenuItem.setAction(actionMap.get("btnConnectToDB")); // NOI18N
connectToDBMenuItem.setText(resourceMap.getString("connectToDBMenuItem.text")); // NOI18N
connectToDBMenuItem.setName("connectToDBMenuItem"); // NOI18N
fileMenu.add(connectToDBMenuItem);
disconnectMenuItem.setAction(actionMap.get("btnDisconnect")); // NOI18N
disconnectMenuItem.setText(resourceMap.getString("disconnectMenuItem.text")); // NOI18N
disconnectMenuItem.setName("disconnectMenuItem"); // NOI18N
fileMenu.add(disconnectMenuItem);
generateDBMenuItem.setAction(actionMap.get("btnGenerateTables")); // NOI18N
generateDBMenuItem.setText(resourceMap.getString("generateDBMenuItem.text")); // NOI18N
generateDBMenuItem.setName("generateDBMenuItem"); // NOI18N
fileMenu.add(generateDBMenuItem);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
gridMenu.setAction(actionMap.get("btnGridSettings")); // NOI18N
gridMenu.setText(resourceMap.getString("gridMenu.text")); // NOI18N
gridMenu.setName("gridMenu"); // NOI18N
settingsMenuItem.setAction(actionMap.get("btnGridSettings")); // NOI18N
settingsMenuItem.setText(resourceMap.getString("settingsMenuItem.text")); // NOI18N
settingsMenuItem.setName("settingsMenuItem"); // NOI18N
gridMenu.add(settingsMenuItem);
menuBar.add(gridMenu);
modusMenu.setText(resourceMap.getString("modusMenu.text")); // NOI18N
modusMenu.setName("modusMenu"); // NOI18N
manageDBModeMenuItem.setAction(actionMap.get("manageDBMode")); // NOI18N
manageDBModeMenuItem.setText(resourceMap.getString("manageDBModeMenuItem.text")); // NOI18N
manageDBModeMenuItem.setName("manageDBModeMenuItem"); // NOI18N
modusMenu.add(manageDBModeMenuItem);
manageExperimentModeMenuItem.setAction(actionMap.get("manageExperimentMode")); // NOI18N
manageExperimentModeMenuItem.setText(resourceMap.getString("manageExperimentModeMenuItem.text")); // NOI18N
manageExperimentModeMenuItem.setName("manageExperimentModeMenuItem"); // NOI18N
modusMenu.add(manageExperimentModeMenuItem);
menuBar.add(modusMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
helpMenu.add(jMenuItem1);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1006, Short.MAX_VALUE)
.add(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusMessageLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 836, Short.MAX_VALUE)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelLayout.createSequentialGroup()
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusMessageLabel)
.add(statusAnimationLabel)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java
index 8f300770..efa90987 100644
--- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java
+++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java
@@ -1,528 +1,529 @@
/**
* This file is part of Waarp Project.
*
* Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the
* COPYRIGHT.txt in the distribution for a full listing of individual contributors.
*
* All Waarp Project 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.
*
* Waarp 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 Waarp. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.protocol.localhandler;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory;
import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory;
import org.jboss.netty.channel.local.LocalAddress;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.waarp.common.logging.WaarpInternalLogger;
import org.waarp.common.logging.WaarpInternalLoggerFactory;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66FiniteDualStates;
import org.waarp.openr66.context.R66Result;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolRemoteShutdownException;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolShutdownException;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException;
import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory;
import org.waarp.openr66.protocol.localhandler.packet.StartupPacket;
import org.waarp.openr66.protocol.localhandler.packet.ValidPacket;
import org.waarp.openr66.protocol.networkhandler.NetworkTransaction;
import org.waarp.openr66.protocol.networkhandler.packet.NetworkPacket;
import org.waarp.openr66.protocol.utils.R66Future;
/**
* This class handles Local Transaction connections
*
* @author frederic bregier
*/
public class LocalTransaction {
/**
* Internal Logger
*/
private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory
.getLogger(LocalTransaction.class);
/**
* HashMap of LocalChannelReference using LocalChannelId
*/
final ConcurrentHashMap<Integer, LocalChannelReference> localChannelHashMap = new ConcurrentHashMap<Integer, LocalChannelReference>();
/**
* HashMap of Validation of LocalChannelReference using LocalChannelId
*/
final ConcurrentHashMap<Integer, R66Future> validLocalChannelHashMap = new ConcurrentHashMap<Integer, R66Future>();
/**
* HashMap of LocalChannelReference using requested_requester_specialId
*/
final ConcurrentHashMap<String, LocalChannelReference> localChannelHashMapExternal = new ConcurrentHashMap<String, LocalChannelReference>();
/**
* Remover from HashMap
*/
private final ChannelFutureListener remover = new ChannelFutureListener() {
public void operationComplete(
ChannelFuture future) {
remove(future
.getChannel());
}
};
private final ChannelFactory channelServerFactory = new DefaultLocalServerChannelFactory();
private final ServerBootstrap serverBootstrap = new ServerBootstrap(
channelServerFactory);
private final Channel serverChannel;
private final LocalAddress socketLocalServerAddress = new LocalAddress(
"0");
private final ChannelFactory channelClientFactory = new DefaultLocalClientChannelFactory();
private final ClientBootstrap clientBootstrap = new ClientBootstrap(
channelClientFactory);
private final ChannelGroup localChannelGroup = new DefaultChannelGroup(
"LocalChannels");
/**
* Constructor
*/
public LocalTransaction() {
serverBootstrap.setPipelineFactory(new LocalServerPipelineFactory());
serverBootstrap.setOption("connectTimeoutMillis",
Configuration.configuration.TIMEOUTCON);
serverChannel = serverBootstrap.bind(socketLocalServerAddress);
localChannelGroup.add(serverChannel);
clientBootstrap.setPipelineFactory(new LocalClientPipelineFactory());
}
/**
* Get the corresponding LocalChannelReference
*
* @param remoteId
* @param localId
* @return the LocalChannelReference
* @throws OpenR66ProtocolSystemException
*/
public LocalChannelReference getClient(Integer remoteId, Integer localId)
throws OpenR66ProtocolSystemException {
LocalChannelReference localChannelReference = getFromId(localId);
if (localChannelReference != null) {
if (localChannelReference.getRemoteId() != remoteId) {
localChannelReference.setRemoteId(remoteId);
}
return localChannelReference;
}
throw new OpenR66ProtocolSystemException(
"Cannot find LocalChannelReference");
}
/**
* Create a new Client
*
* @param networkChannel
* @param remoteId
* @param futureRequest
* @return the LocalChannelReference
* @throws OpenR66ProtocolSystemException
*/
public LocalChannelReference createNewClient(Channel networkChannel,
Integer remoteId, R66Future futureRequest)
throws OpenR66ProtocolSystemException {
ChannelFuture channelFuture = null;
logger.debug("Status LocalChannelServer: {} {}", serverChannel
.getClass().getName(), serverChannel.getConfig()
.getConnectTimeoutMillis() + " " + serverChannel.isBound());
R66Future validLCR = new R66Future(true);
validLocalChannelHashMap.put(remoteId, validLCR);
for (int i = 0; i < Configuration.RETRYNB; i++) {
channelFuture = clientBootstrap.connect(socketLocalServerAddress);
try {
channelFuture.await();
} catch (InterruptedException e1) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer Interrupted: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() +
" " + serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Interruption - Cannot connect to local handler: " +
socketLocalServerAddress + " " +
serverChannel.isBound() + " " + serverChannel,
e1);
}
if (channelFuture.isSuccess()) {
final Channel channel = channelFuture.getChannel();
localChannelGroup.add(channel);
+ logger.debug("Will start localChannelReference and eventually generate a new Db Connection if not-thread-safe");
final LocalChannelReference localChannelReference = new LocalChannelReference(
channel, networkChannel, remoteId, futureRequest);
- logger.debug("Create LocalChannel entry: " + i + " {}",
+ logger.debug("Db connection done and Create LocalChannel entry: " + i + " {}",
localChannelReference);
channel.getCloseFuture().addListener(remover);
localChannelHashMap.put(channel.getId(), localChannelReference);
try {
NetworkTransaction.addLocalChannelToNetworkChannel(
networkChannel, channel);
} catch (OpenR66ProtocolRemoteShutdownException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
Channels.close(channel);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
// Now send first a Startup message
StartupPacket startup = new StartupPacket(
localChannelReference.getLocalId());
try {
Channels.write(channel, startup).await();
} catch (InterruptedException e) {
logger.error("Can't connect to local server due to interruption" + i);
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
validLCR.setSuccess();
return localChannelReference;
} else {
logger.error("Can't connect to local server " + i);
}
try {
Thread.sleep(Configuration.RETRYINMS);
} catch (InterruptedException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
}
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() + " " +
serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler: " + socketLocalServerAddress +
" " + serverChannel.isBound() + " " + serverChannel,
channelFuture.getCause());
}
/**
*
* @param id
* @return the LocalChannelReference
*/
public LocalChannelReference getFromId(Integer id) {
for (int i = 0; i < Configuration.RETRYNB * 4; i++) {
LocalChannelReference lcr = localChannelHashMap.get(id);
if (lcr == null) {
/*
* R66Future future = validLocalChannelHashMap.get(id);
* logger.debug("DEBUG Future ValidLocalChannel: not found: " + id + (future !=
* null)); if (future != null) { try {
* future.await(Configuration.configuration.TIMEOUTCON); } catch
* (InterruptedException e) { return localChannelHashMap.get(id); }
* logger.debug("DEBUG Future ValidLocalChannel: " + id + future.isDone() + ":" +
* future.isSuccess()); if (future.isSuccess()) { return
* localChannelHashMap.get(id); } else if (future.isFailed()) { return null; } }
* else { logger.debug("DEBUG Future ValidLocalChannel: Sleep" + id); try {
* Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e) { }
* continue; }
*/
try {
Thread.sleep(Configuration.RETRYINMS * 2);
} catch (InterruptedException e) {
}
} else {
return lcr;
}
}
return localChannelHashMap.get(id);
}
/**
* Remove one local channel
*
* @param channel
*/
public void remove(Channel channel) {
LocalChannelReference localChannelReference = localChannelHashMap
.remove(channel.getId());
if (localChannelReference != null) {
logger.debug("Remove LocalChannel");
R66Future validLCR = validLocalChannelHashMap
.remove(localChannelReference.getRemoteId());
if (validLCR != null) {
validLCR.cancel();
}
DbTaskRunner runner = null;
if (localChannelReference.getSession() != null) {
runner = localChannelReference.getSession().getRunner();
}
R66Result result = new R66Result(
new OpenR66ProtocolSystemException(
"While closing Local Channel"),
localChannelReference.getSession(), false,
ErrorCode.ConnectionImpossible, runner);
localChannelReference.validateConnection(false, result);
if (localChannelReference.getSession() != null) {
if (runner != null) {
String key = runner.getKey();
localChannelHashMapExternal.remove(key);
}
}
}
}
/**
*
* @param runner
* @param lcr
*/
public void setFromId(DbTaskRunner runner, LocalChannelReference lcr) {
String key = runner.getKey();
localChannelHashMapExternal.put(key, lcr);
}
/**
*
* @param key
* as "requested requester specialId"
* @return the LocalChannelReference
*/
public LocalChannelReference getFromRequest(String key) {
return localChannelHashMapExternal.get(key);
}
/**
*
* @return the number of active local channels
*/
public int getNumberLocalChannel() {
return localChannelHashMap.size();
}
private static class CloseLocalChannelsFromNetworkChannelTast implements TimerTask {
LocalTransaction localTransaction;
AtomicInteger semaphore;
LocalChannelReference localChannelReference;
boolean analysis;
public CloseLocalChannelsFromNetworkChannelTast(
LocalTransaction localTransaction,
AtomicInteger semaphore,
LocalChannelReference localChannelReference) {
this.localTransaction = localTransaction;
this.semaphore = semaphore;
this.localChannelReference = localChannelReference;
analysis = true;
}
public void run(Timeout timeout) {
// give a chance for the LocalChannel to stop normally
if (analysis) {
boolean wait = false;
if (!localChannelReference.getFutureRequest().isDone()) {
if (localChannelReference.getFutureValidRequest().isDone() &&
localChannelReference.getFutureValidRequest()
.isFailed()) {
logger.debug("Already currently on finalize");
wait = true;
} else {
R66Result finalValue = new R66Result(
localChannelReference.getSession(), true,
ErrorCode.Shutdown, null);
if (localChannelReference.getSession() != null) {
try {
localChannelReference.getSession()
.tryFinalizeRequest(finalValue);
} catch (OpenR66RunnerErrorException e) {
} catch (OpenR66ProtocolSystemException e) {
}
}
}
}
if (wait) {
this.analysis = false;
Configuration.configuration.getTimerClose().newTimeout(this,
Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS);
return;
}
}
logger.debug("Will close local channel");
try {
Channels.close(localChannelReference.getLocalChannel()).await();
} catch (InterruptedException e) {
}
localTransaction.remove(localChannelReference.getLocalChannel());
semaphore.decrementAndGet();
}
}
/**
* Close all Local Channels from the NetworkChannel
*
* @param networkChannel
*/
public void closeLocalChannelsFromNetworkChannel(Channel networkChannel) {
Collection<LocalChannelReference> collection = localChannelHashMap
.values();
AtomicInteger semaphore = new AtomicInteger();
Iterator<LocalChannelReference> iterator = collection.iterator();
while (iterator.hasNext()) {
LocalChannelReference localChannelReference = iterator.next();
if (localChannelReference.getNetworkChannel().compareTo(
networkChannel) == 0) {
semaphore.incrementAndGet();
CloseLocalChannelsFromNetworkChannelTast task =
new CloseLocalChannelsFromNetworkChannelTast(this,
semaphore, localChannelReference);
Configuration.configuration.getTimerClose().newTimeout(task,
Configuration.RETRYINMS * 10, TimeUnit.MILLISECONDS);
}
}
while (true) {
if (semaphore.get() == 0) {
break;
}
try {
Thread.sleep(Configuration.RETRYINMS * 2);
} catch (InterruptedException e) {
break;
}
}
}
/**
* Debug function (while shutdown for instance)
*/
public void debugPrintActiveLocalChannels() {
Collection<LocalChannelReference> collection = localChannelHashMap
.values();
Iterator<LocalChannelReference> iterator = collection.iterator();
while (iterator.hasNext()) {
LocalChannelReference localChannelReference = iterator.next();
logger.debug("Will close local channel: {}", localChannelReference);
logger.debug(
" Containing: {}",
(localChannelReference.getSession() != null ? localChannelReference
.getSession() : "no session"));
}
}
/**
* Informs all remote client that the server is shutting down
*/
public void shutdownLocalChannels() {
Collection<LocalChannelReference> collection = localChannelHashMap
.values();
Iterator<LocalChannelReference> iterator = collection.iterator();
ValidPacket packet = new ValidPacket("Shutdown forced", null,
LocalPacketFactory.SHUTDOWNPACKET);
ChannelBuffer buffer = null;
while (iterator.hasNext()) {
LocalChannelReference localChannelReference = iterator.next();
logger.debug("Inform Shutdown {}", localChannelReference);
packet.setSmiddle(null);
// If a transfer is running, save the current rank and inform remote
// host
if (localChannelReference.getSession() != null) {
R66Session session = localChannelReference.getSession();
DbTaskRunner runner = session.getRunner();
if (runner != null && runner.isInTransfer()) {
if (!runner.isSender()) {
int newrank = runner.getRank();
packet.setSmiddle(Integer.toString(newrank));
}
// Save File status
try {
runner.saveStatus();
} catch (OpenR66RunnerErrorException e) {
}
R66Result result = new R66Result(
new OpenR66ProtocolShutdownException(), session,
true, ErrorCode.Shutdown, runner);
result.other = packet;
try {
buffer = packet.getLocalPacket(localChannelReference);
} catch (OpenR66ProtocolPacketException e1) {
}
localChannelReference
.sessionNewState(R66FiniteDualStates.SHUTDOWN);
NetworkPacket message = new NetworkPacket(
localChannelReference.getLocalId(),
localChannelReference.getRemoteId(),
packet.getType(), buffer);
try {
Channels.write(localChannelReference.getNetworkChannel(),
message).await();
} catch (InterruptedException e1) {
}
try {
session.setFinalizeTransfer(false, result);
} catch (OpenR66RunnerErrorException e) {
} catch (OpenR66ProtocolSystemException e) {
}
}
Channels.close(localChannelReference.getLocalChannel());
continue;
}
try {
buffer = packet.getLocalPacket(localChannelReference);
} catch (OpenR66ProtocolPacketException e1) {
}
NetworkPacket message = new NetworkPacket(
localChannelReference.getLocalId(),
localChannelReference.getRemoteId(), packet.getType(),
buffer);
Channels.write(localChannelReference.getNetworkChannel(), message);
}
}
/**
* Close All Local Channels
*/
public void closeAll() {
logger.debug("close All Local Channels");
localChannelGroup.close().awaitUninterruptibly();
clientBootstrap.releaseExternalResources();
channelClientFactory.releaseExternalResources();
serverBootstrap.releaseExternalResources();
channelServerFactory.releaseExternalResources();
}
}
| false | true | public LocalChannelReference createNewClient(Channel networkChannel,
Integer remoteId, R66Future futureRequest)
throws OpenR66ProtocolSystemException {
ChannelFuture channelFuture = null;
logger.debug("Status LocalChannelServer: {} {}", serverChannel
.getClass().getName(), serverChannel.getConfig()
.getConnectTimeoutMillis() + " " + serverChannel.isBound());
R66Future validLCR = new R66Future(true);
validLocalChannelHashMap.put(remoteId, validLCR);
for (int i = 0; i < Configuration.RETRYNB; i++) {
channelFuture = clientBootstrap.connect(socketLocalServerAddress);
try {
channelFuture.await();
} catch (InterruptedException e1) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer Interrupted: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() +
" " + serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Interruption - Cannot connect to local handler: " +
socketLocalServerAddress + " " +
serverChannel.isBound() + " " + serverChannel,
e1);
}
if (channelFuture.isSuccess()) {
final Channel channel = channelFuture.getChannel();
localChannelGroup.add(channel);
final LocalChannelReference localChannelReference = new LocalChannelReference(
channel, networkChannel, remoteId, futureRequest);
logger.debug("Create LocalChannel entry: " + i + " {}",
localChannelReference);
channel.getCloseFuture().addListener(remover);
localChannelHashMap.put(channel.getId(), localChannelReference);
try {
NetworkTransaction.addLocalChannelToNetworkChannel(
networkChannel, channel);
} catch (OpenR66ProtocolRemoteShutdownException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
Channels.close(channel);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
// Now send first a Startup message
StartupPacket startup = new StartupPacket(
localChannelReference.getLocalId());
try {
Channels.write(channel, startup).await();
} catch (InterruptedException e) {
logger.error("Can't connect to local server due to interruption" + i);
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
validLCR.setSuccess();
return localChannelReference;
} else {
logger.error("Can't connect to local server " + i);
}
try {
Thread.sleep(Configuration.RETRYINMS);
} catch (InterruptedException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
}
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() + " " +
serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler: " + socketLocalServerAddress +
" " + serverChannel.isBound() + " " + serverChannel,
channelFuture.getCause());
}
| public LocalChannelReference createNewClient(Channel networkChannel,
Integer remoteId, R66Future futureRequest)
throws OpenR66ProtocolSystemException {
ChannelFuture channelFuture = null;
logger.debug("Status LocalChannelServer: {} {}", serverChannel
.getClass().getName(), serverChannel.getConfig()
.getConnectTimeoutMillis() + " " + serverChannel.isBound());
R66Future validLCR = new R66Future(true);
validLocalChannelHashMap.put(remoteId, validLCR);
for (int i = 0; i < Configuration.RETRYNB; i++) {
channelFuture = clientBootstrap.connect(socketLocalServerAddress);
try {
channelFuture.await();
} catch (InterruptedException e1) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer Interrupted: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() +
" " + serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Interruption - Cannot connect to local handler: " +
socketLocalServerAddress + " " +
serverChannel.isBound() + " " + serverChannel,
e1);
}
if (channelFuture.isSuccess()) {
final Channel channel = channelFuture.getChannel();
localChannelGroup.add(channel);
logger.debug("Will start localChannelReference and eventually generate a new Db Connection if not-thread-safe");
final LocalChannelReference localChannelReference = new LocalChannelReference(
channel, networkChannel, remoteId, futureRequest);
logger.debug("Db connection done and Create LocalChannel entry: " + i + " {}",
localChannelReference);
channel.getCloseFuture().addListener(remover);
localChannelHashMap.put(channel.getId(), localChannelReference);
try {
NetworkTransaction.addLocalChannelToNetworkChannel(
networkChannel, channel);
} catch (OpenR66ProtocolRemoteShutdownException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
Channels.close(channel);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
// Now send first a Startup message
StartupPacket startup = new StartupPacket(
localChannelReference.getLocalId());
try {
Channels.write(channel, startup).await();
} catch (InterruptedException e) {
logger.error("Can't connect to local server due to interruption" + i);
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
validLCR.setSuccess();
return localChannelReference;
} else {
logger.error("Can't connect to local server " + i);
}
try {
Thread.sleep(Configuration.RETRYINMS);
} catch (InterruptedException e) {
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler", e);
}
}
validLCR.cancel();
validLocalChannelHashMap.remove(remoteId);
logger.error("LocalChannelServer: " +
serverChannel.getClass().getName() + " " +
serverChannel.getConfig().getConnectTimeoutMillis() + " " +
serverChannel.isBound());
throw new OpenR66ProtocolSystemException(
"Cannot connect to local handler: " + socketLocalServerAddress +
" " + serverChannel.isBound() + " " + serverChannel,
channelFuture.getCause());
}
|
diff --git a/src/org/yaxim/androidclient/service/GenericService.java b/src/org/yaxim/androidclient/service/GenericService.java
index 6706c14..85dd34a 100644
--- a/src/org/yaxim/androidclient/service/GenericService.java
+++ b/src/org/yaxim/androidclient/service/GenericService.java
@@ -1,173 +1,172 @@
package org.yaxim.androidclient.service;
import java.util.HashMap;
import java.util.Map;
import org.yaxim.androidclient.chat.ChatWindow;
import org.yaxim.androidclient.data.YaximConfiguration;
import org.yaxim.androidclient.util.LogConstants;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import org.yaxim.androidclient.R;
public abstract class GenericService extends Service {
private static final String TAG = "Service";
private static final String APP_NAME = "yaxim";
private NotificationManager mNotificationMGR;
private Notification mNotification;
private Vibrator mVibrator;
private Intent mNotificationIntent;
//private int mNotificationCounter = 0;
private Map<String, Integer> notificationCount = new HashMap<String, Integer>(2);
private Map<String, Integer> notificationId = new HashMap<String, Integer>(2);
private int lastNotificationId = 0;
protected YaximConfiguration mConfig;
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "called onBind()");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "called onUnbind()");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
Log.i(TAG, "called onRebind()");
super.onRebind(intent);
}
@Override
public void onCreate() {
Log.i(TAG, "called onCreate()");
super.onCreate();
mConfig = new YaximConfiguration(PreferenceManager
.getDefaultSharedPreferences(this));
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
addNotificationMGR();
}
@Override
public void onDestroy() {
Log.i(TAG, "called onDestroy()");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i(TAG, "called onStart()");
super.onStart(intent, startId);
}
private void addNotificationMGR() {
mNotificationMGR = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationIntent = new Intent(this, ChatWindow.class);
}
protected void notifyClient(String fromJid, String fromUserName, String message) {
setNotification(fromJid, fromUserName, message);
setLEDNotifivation();
int notifyId = 0;
if (notificationId.containsKey(fromJid)) {
notifyId = notificationId.get(fromJid);
} else {
lastNotificationId++;
notifyId = lastNotificationId;
notificationId.put(fromJid, Integer.valueOf(notifyId));
}
mNotificationMGR.notify(notifyId, mNotification);
vibraNotififaction();
}
private void setNotification(String fromJid, String fromUserId, String message) {
int mNotificationCounter = 0;
if (notificationCount.containsKey(fromJid)) {
mNotificationCounter = notificationCount.get(fromJid);
} else {
notificationCount.put(fromJid, Integer.valueOf(1));
}
mNotificationCounter++;
String author;
if (null == fromUserId || fromUserId.length() == 0 || fromJid.equals(fromUserId)) {
author = fromJid;
} else {
author = fromUserId + " (" + fromJid + ")";
}
String title = getString(R.string.notification_message, author);
mNotification = new Notification(R.drawable.icon, title,
System.currentTimeMillis());
Uri userNameUri = Uri.parse(fromJid);
mNotificationIntent.setData(userNameUri);
mNotificationIntent.putExtra(ChatWindow.INTENT_EXTRA_USERNAME, fromUserId);
//need to set flag FLAG_UPDATE_CURRENT to get extras transferred
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
mNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.setLatestEventInfo(this, title, message, pendingIntent);
mNotification.number = mNotificationCounter;
- mNotification.flags = Notification.FLAG_AUTO_CANCEL
- | Notification.FLAG_ONLY_ALERT_ONCE;
+ mNotification.flags = Notification.FLAG_AUTO_CANCEL;
}
private void setLEDNotifivation() {
if (mConfig.isLEDNotify) {
mNotification.flags |= Notification.DEFAULT_LIGHTS;
mNotification.ledARGB = Color.MAGENTA;
mNotification.ledOnMS = 300;
mNotification.ledOffMS = 1000;
mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
}
}
private void vibraNotififaction() {
if (mConfig.isVibraNotify) {
mVibrator.vibrate(400);
}
}
protected void shortToastNotify(String msg) {
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
public void resetNotificationCounter(String userJid) {
notificationCount.remove(userJid);
}
protected void logError(String data) {
if (LogConstants.LOG_ERROR) {
Log.e(TAG, data);
}
}
protected void logInfo(String data) {
if (LogConstants.LOG_ERROR) {
Log.e(TAG, data);
}
}
}
| true | true | private void setNotification(String fromJid, String fromUserId, String message) {
int mNotificationCounter = 0;
if (notificationCount.containsKey(fromJid)) {
mNotificationCounter = notificationCount.get(fromJid);
} else {
notificationCount.put(fromJid, Integer.valueOf(1));
}
mNotificationCounter++;
String author;
if (null == fromUserId || fromUserId.length() == 0 || fromJid.equals(fromUserId)) {
author = fromJid;
} else {
author = fromUserId + " (" + fromJid + ")";
}
String title = getString(R.string.notification_message, author);
mNotification = new Notification(R.drawable.icon, title,
System.currentTimeMillis());
Uri userNameUri = Uri.parse(fromJid);
mNotificationIntent.setData(userNameUri);
mNotificationIntent.putExtra(ChatWindow.INTENT_EXTRA_USERNAME, fromUserId);
//need to set flag FLAG_UPDATE_CURRENT to get extras transferred
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
mNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.setLatestEventInfo(this, title, message, pendingIntent);
mNotification.number = mNotificationCounter;
mNotification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONLY_ALERT_ONCE;
}
| private void setNotification(String fromJid, String fromUserId, String message) {
int mNotificationCounter = 0;
if (notificationCount.containsKey(fromJid)) {
mNotificationCounter = notificationCount.get(fromJid);
} else {
notificationCount.put(fromJid, Integer.valueOf(1));
}
mNotificationCounter++;
String author;
if (null == fromUserId || fromUserId.length() == 0 || fromJid.equals(fromUserId)) {
author = fromJid;
} else {
author = fromUserId + " (" + fromJid + ")";
}
String title = getString(R.string.notification_message, author);
mNotification = new Notification(R.drawable.icon, title,
System.currentTimeMillis());
Uri userNameUri = Uri.parse(fromJid);
mNotificationIntent.setData(userNameUri);
mNotificationIntent.putExtra(ChatWindow.INTENT_EXTRA_USERNAME, fromUserId);
//need to set flag FLAG_UPDATE_CURRENT to get extras transferred
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
mNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.setLatestEventInfo(this, title, message, pendingIntent);
mNotification.number = mNotificationCounter;
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
}
|
diff --git a/app/in/partake/model/dao/DataFilter.java b/app/in/partake/model/dao/DataFilter.java
index 7dd1721..ebfb281 100644
--- a/app/in/partake/model/dao/DataFilter.java
+++ b/app/in/partake/model/dao/DataFilter.java
@@ -1,66 +1,66 @@
package in.partake.model.dao;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.NoSuchElementException;
import javax.annotation.Nonnull;
import com.google.common.base.Predicate;
public class DataFilter<T> extends DataIterator<T> {
private final DataIterator<T> unfiltered;
private final Predicate<? super T> predicate;
private T next;
private boolean searchedNext;
private boolean foundNext;
public DataFilter(@Nonnull DataIterator<T> unfiltered, @Nonnull Predicate<? super T> predicate) {
this.unfiltered = checkNotNull(unfiltered);
this.predicate = checkNotNull(predicate);
}
@Override
public boolean hasNext() throws DAOException {
if (searchedNext) {
- return next != null;
+ return foundNext;
}
searchedNext = true;
while (unfiltered.hasNext()) {
next = unfiltered.next();
if (predicate.apply(next)) {
foundNext = true;
return true;
}
}
next = null;
- foundNext = true;
+ foundNext = false;
return false;
}
@Override
public T next() throws DAOException {
if ((searchedNext && !foundNext) || (!searchedNext && !hasNext())){
throw new NoSuchElementException();
}
searchedNext = foundNext = false;
return next;
}
@Override
public void close() {
unfiltered.close();
}
@Override
public void remove() throws DAOException, UnsupportedOperationException {
unfiltered.remove();
}
@Override
public void update(T t) throws DAOException, UnsupportedOperationException {
unfiltered.update(t);
}
}
| false | true | public boolean hasNext() throws DAOException {
if (searchedNext) {
return next != null;
}
searchedNext = true;
while (unfiltered.hasNext()) {
next = unfiltered.next();
if (predicate.apply(next)) {
foundNext = true;
return true;
}
}
next = null;
foundNext = true;
return false;
}
| public boolean hasNext() throws DAOException {
if (searchedNext) {
return foundNext;
}
searchedNext = true;
while (unfiltered.hasNext()) {
next = unfiltered.next();
if (predicate.apply(next)) {
foundNext = true;
return true;
}
}
next = null;
foundNext = false;
return false;
}
|
diff --git a/pdfbox/src/test/java/org/apache/pdfbox/cos/TestCOSFloat.java b/pdfbox/src/test/java/org/apache/pdfbox/cos/TestCOSFloat.java
index 2f2a208..68699eb 100644
--- a/pdfbox/src/test/java/org/apache/pdfbox/cos/TestCOSFloat.java
+++ b/pdfbox/src/test/java/org/apache/pdfbox/cos/TestCOSFloat.java
@@ -1,216 +1,217 @@
/*
* 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.pdfbox.cos;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.pdfbox.pdfwriter.COSWriter;
/**
* Tests {@link COSFloat}.
*/
public class TestCOSFloat extends TestCOSNumber
{
// Use random number to ensure various float values are expressed in the test
private Random rnd;
private DecimalFormat formatDecimal;
{
formatDecimal = (DecimalFormat) NumberFormat.getNumberInstance();
formatDecimal.setMaximumFractionDigits(10);
formatDecimal.setGroupingUsed(false);
DecimalFormatSymbols symbols = formatDecimal.getDecimalFormatSymbols();
symbols.setDecimalSeparator('.');
formatDecimal.setDecimalFormatSymbols(symbols);
}
public void setUp()
{
rnd = new Random();
try
{
testCOSBase = COSNumber.get("1.1");
}
catch (IOException e)
{
fail("Failed to create a COSNumber in setUp()");
}
}
/**
* Tests equals() - ensures that the Object.equals() contract is obeyed. These are tested over
* a range of arbitrary values to ensure Consistency, Reflexivity, Symmetry, Transitivity and
* non-nullity.
*/
public void testEquals()
{
// Consistency
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat test1 = new COSFloat(num);
COSFloat test2 = new COSFloat(num);
COSFloat test3 = new COSFloat(num);
// Reflexive (x == x)
assertTrue(test1.equals(test1));
// Symmetric is preserved ( x==y then y==x)
assertTrue(test2.equals(test1));
assertTrue(test1.equals(test2));
// Transitive (if x==y && y==z then x==z)
assertTrue(test1.equals(test2));
assertTrue(test2.equals(test3));
assertTrue(test1.equals(test3));
// Non-nullity
assertFalse(test1.equals(null));
assertFalse(test2.equals(null));
assertFalse(test3.equals(null));
- COSFloat test4 = new COSFloat(num + 0.01f);
+ float nf = Float.intBitsToFloat(Float.floatToIntBits(num)+1);
+ COSFloat test4 = new COSFloat(nf);
assertFalse(test4.equals(test1));
}
}
/**
* Tests hashCode() - ensures that the Object.hashCode() contract is obeyed over a range of
* arbitrary values.
*/
public void testHashCode()
{
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat test1 = new COSFloat(num);
COSFloat test2 = new COSFloat(num);
assertEquals(test1.hashCode(), test2.hashCode());
COSFloat test3 = new COSFloat(num + 0.01f);
assertFalse(test3.equals(test1));
}
}
@Override
public void testFloatValue()
{
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat testFloat = new COSFloat(num);
assertEquals(num, testFloat.floatValue());
}
}
@Override
public void testDoubleValue()
{
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat testFloat = new COSFloat(num);
assertEquals((double) num, testFloat.doubleValue());
}
}
@Override
public void testIntValue()
{
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat testFloat = new COSFloat(num);
assertEquals((int) num, testFloat.intValue());
}
}
@Override
public void testLongValue()
{
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat testFloat = new COSFloat(num);
assertEquals((long) num, testFloat.longValue());
}
}
@Override
public void testAccept()
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
COSWriter visitor = new COSWriter(outStream);
float num = 0;
try
{
for (int i = -100000; i < 300000; i += 20000)
{
num = i * rnd.nextFloat();
COSFloat cosFloat = new COSFloat(num);
cosFloat.accept(visitor);
testByteArrays(formatDecimal.format(num).getBytes("ISO-8859-1"),
outStream.toByteArray());
outStream.reset();
}
}
catch (Exception e)
{
fail("Failed to write " + num + " exception: " + e.getMessage());
}
}
/**
* Tests writePDF() - this method takes an {@link OutputStream} and writes this object to it.
*/
public void testWritePDF()
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
float num = 0;
try
{
for (int i = -1000; i < 3000; i += 200)
{
num = i * rnd.nextFloat();
COSFloat cosFloat = new COSFloat(num);
cosFloat.writePDF(outStream);
testByteArrays(formatDecimal.format(num).getBytes("ISO-8859-1"),
outStream.toByteArray());
outStream.reset();
}
}
catch (IOException e)
{
fail("Failed to write " + num + " exception: " + e.getMessage());
}
}
/**
* This will get the suite of test that this class holds.
*
* @return All of the tests that this class holds.
*/
public static Test suite()
{
return new TestSuite(TestCOSFloat.class);
}
}
| true | true | public void testEquals()
{
// Consistency
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat test1 = new COSFloat(num);
COSFloat test2 = new COSFloat(num);
COSFloat test3 = new COSFloat(num);
// Reflexive (x == x)
assertTrue(test1.equals(test1));
// Symmetric is preserved ( x==y then y==x)
assertTrue(test2.equals(test1));
assertTrue(test1.equals(test2));
// Transitive (if x==y && y==z then x==z)
assertTrue(test1.equals(test2));
assertTrue(test2.equals(test3));
assertTrue(test1.equals(test3));
// Non-nullity
assertFalse(test1.equals(null));
assertFalse(test2.equals(null));
assertFalse(test3.equals(null));
COSFloat test4 = new COSFloat(num + 0.01f);
assertFalse(test4.equals(test1));
}
}
| public void testEquals()
{
// Consistency
for (int i = -100000; i < 300000; i += 20000)
{
float num = i * rnd.nextFloat();
COSFloat test1 = new COSFloat(num);
COSFloat test2 = new COSFloat(num);
COSFloat test3 = new COSFloat(num);
// Reflexive (x == x)
assertTrue(test1.equals(test1));
// Symmetric is preserved ( x==y then y==x)
assertTrue(test2.equals(test1));
assertTrue(test1.equals(test2));
// Transitive (if x==y && y==z then x==z)
assertTrue(test1.equals(test2));
assertTrue(test2.equals(test3));
assertTrue(test1.equals(test3));
// Non-nullity
assertFalse(test1.equals(null));
assertFalse(test2.equals(null));
assertFalse(test3.equals(null));
float nf = Float.intBitsToFloat(Float.floatToIntBits(num)+1);
COSFloat test4 = new COSFloat(nf);
assertFalse(test4.equals(test1));
}
}
|
diff --git a/src/org/mozilla/javascript/NativeCall.java b/src/org/mozilla/javascript/NativeCall.java
index d0817072..b196ac3d 100644
--- a/src/org/mozilla/javascript/NativeCall.java
+++ b/src/org/mozilla/javascript/NativeCall.java
@@ -1,154 +1,154 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* 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
* http://www.mozilla.org/MPL/
*
* 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.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Bob Jervis
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* This class implements the activation object.
*
* See ECMA 10.1.6
*
* @see org.mozilla.javascript.Arguments
* @author Norris Boyd
*/
public final class NativeCall extends IdScriptableObject
{
static final long serialVersionUID = -7471457301304454454L;
private static final Object CALL_TAG = new Object();
static void init(Scriptable scope, boolean sealed)
{
NativeCall obj = new NativeCall();
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
NativeCall() { }
NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
- // initialize "arguments" property but only if it was not overriden by
+ // initialize "arguments" property but only if it was not overridden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
public String getClassName()
{
return "Call";
}
protected int findPrototypeId(String s)
{
return s.equals("constructor") ? Id_constructor : 0;
}
protected void initPrototypeId(int id)
{
String s;
int arity;
if (id == Id_constructor) {
arity=1; s="constructor";
} else {
throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(CALL_TAG, id, s, arity);
}
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(CALL_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
if (id == Id_constructor) {
if (thisObj != null) {
throw Context.reportRuntimeError1("msg.only.from.new", "Call");
}
ScriptRuntime.checkDeprecated(cx, "Call");
NativeCall result = new NativeCall();
result.setPrototype(getObjectPrototype(scope));
return result;
}
throw new IllegalArgumentException(String.valueOf(id));
}
private static final int
Id_constructor = 1,
MAX_PROTOTYPE_ID = 1;
NativeFunction function;
Object[] originalArgs;
transient NativeCall parentActivationCall;
}
| true | true | NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
// initialize "arguments" property but only if it was not overriden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
| NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
// initialize "arguments" property but only if it was not overridden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
|
diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/IsModifiedTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/IsModifiedTests.java
index 15a2117e2..d86bbc845 100644
--- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/IsModifiedTests.java
+++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/IsModifiedTests.java
@@ -1,544 +1,551 @@
/*******************************************************************************
* Copyright (c) 2000, 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.tests.ccvs.core.provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
import org.eclipse.team.internal.ccvs.core.util.ResourceStateChangeListeners;
import org.eclipse.team.tests.ccvs.core.CVSTestSetup;
import org.eclipse.team.tests.ccvs.core.EclipseTest;
/**
* Test isModified on file, folders and projects.
*/
public class IsModifiedTests extends EclipseTest {
Set previouslyModified = new HashSet();
Map changedResources = new HashMap();
IResourceStateChangeListener listener = new IResourceStateChangeListener() {
public void resourceSyncInfoChanged(IResource[] changedResources) {
try {
for (int i = 0; i < changedResources.length; i++) {
IResource resource = changedResources[i];
ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource);
recordModificationState(cvsResource);
recordParents(cvsResource);
if (cvsResource.isFolder()) {
recordChildren((ICVSFolder)cvsResource);
}
}
} catch (CVSException e) {
fail(e.getMessage());
}
}
public void externalSyncInfoChange(IResource[] changedResources) {
resourceSyncInfoChanged(changedResources);
}
private void recordChildren(ICVSFolder folder) {
try {
folder.accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
recordModificationState(file);
}
public void visitFolder(ICVSFolder folder) throws CVSException {
recordModificationState(folder);
folder.acceptChildren(this);
}
});
} catch (CVSException e) {
fail(e.getMessage());
}
}
private void recordParents(ICVSResource cvsResource) throws CVSException {
if (cvsResource.getIResource().getType() == IResource.ROOT) return;
recordModificationState(cvsResource);
recordParents(cvsResource.getParent());
}
private void recordModificationState(ICVSResource cvsResource) throws CVSException {
IsModifiedTests.this.changedResources.put(cvsResource.getIResource(), cvsResource.isModified(null) ? Boolean.TRUE : Boolean.FALSE);
}
public void resourceModified(IResource[] changedResources) {
try {
for (int i = 0; i < changedResources.length; i++) {
IResource resource = changedResources[i];
ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource);
IsModifiedTests.this.changedResources.put(resource, cvsResource.isModified(null) ? Boolean.TRUE : Boolean.FALSE);
recordParents(cvsResource);
if (cvsResource.isFolder()) {
recordChildren((ICVSFolder)cvsResource);
}
}
} catch (CVSException e) {
fail(e.getMessage());
}
}
public void projectConfigured(IProject project) {
}
public void projectDeconfigured(IProject project) {
}
};
/**
* Constructor for CVSProviderTest
*/
public IsModifiedTests() {
super();
}
/**
* Constructor for CVSProviderTest
*/
public IsModifiedTests(String name) {
super(name);
}
public static Test suite() {
String testName = System.getProperty("eclipse.cvs.testName");
if (testName == null) {
TestSuite suite = new TestSuite(IsModifiedTests.class);
return new CVSTestSetup(suite);
} else {
return new CVSTestSetup(new IsModifiedTests(testName));
}
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
previouslyModified.clear();
changedResources.clear();
ResourceStateChangeListeners.getListener().addResourceStateChangeListener(listener);
}
/**
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
previouslyModified.clear();
changedResources.clear();
ResourceStateChangeListeners.getListener().removeResourceStateChangeListener(listener);
super.tearDown();
}
/*
* Assert that the modification state of the provided resources matches the
* provided state and that the other are the opposite state.
*/
private void assertModificationState(IContainer container, String[] resources, final boolean listedResourcesShouldBeModified) throws CVSException {
final ICVSFolder rootFolder = CVSWorkspaceRoot.getCVSFolderFor(container);
final List resourceList = new ArrayList();
final Set modifiedResources = new HashSet();
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
String string = resources[i];
resourceList.add(new Path(string));
}
}
waitForIgnoreFileHandling();
rootFolder.accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
assertModificationState(file);
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// find the deepest mistake
folder.acceptChildren(this);
assertModificationState(folder);
}
public void assertModificationState(ICVSResource resource) throws CVSException {
IPath relativePath = new Path(resource.getRelativePath(rootFolder));
boolean resourceModified = resource.isModified(null);
boolean resourceListed = resourceList.contains(relativePath);
- assertTrue(resource.getIResource().getFullPath().toString()
- + (resourceModified ? " should not be modified but is" : " should be modified but isn't"),
- (listedResourcesShouldBeModified && (resourceModified == resourceListed)) ||
- (!listedResourcesShouldBeModified && (!resourceModified == resourceListed)));
+ if (CVSTestSetup.FAIL_ON_BAD_DIFF) {
+ assertTrue(resource.getIResource().getFullPath().toString()
+ + (resourceModified ? " should not be modified but is" : " should be modified but isn't"),
+ (listedResourcesShouldBeModified && (resourceModified == resourceListed)) ||
+ (!listedResourcesShouldBeModified && (!resourceModified == resourceListed)));
+ } else if (!resourceModified){
+ // Only fail if a file that should be modified isn't
+ assertTrue(resource.getIResource().getFullPath().toString()
+ + " should be modified but isn't",
+ listedResourcesShouldBeModified == resourceListed);
+ }
// Commented because the CVS core doesn't rely on resourceModify to be called.
// IResource iResource = resource.getIResource();
// if (resource.isModified()) {
// modifiedResources.add(iResource);
// if (!wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.TRUE);
// }
// } else {
// if (wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.FALSE);
// }
// }
}
// public boolean wasPreviouslyModified(IResource iResource) {
// return previouslyModified.contains(iResource);
// }
});
changedResources.clear();
previouslyModified.clear();
previouslyModified.addAll(modifiedResources);
}
/**
* Assert that a project (and all it's children) is clean after it is
* created and shared.
*
* @see org.eclipse.team.tests.ccvs.core.EclipseTest#createProject(java.lang.String, java.lang.String)
*/
protected IProject createProject(String prefix, String[] resources) throws CoreException, TeamException {
IProject project = super.createProject(prefix, resources);
assertModificationState(project, null, true);
return project;
}
public void testFileModifications() throws CoreException, TeamException {
IProject project = createProject("testFileModifications", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt" });
// change two files, commit one and revert the other
setContentsAndEnsureModified(project.getFile("changed.txt"));
assertModificationState(project, new String[] {".", "changed.txt"}, true);
setContentsAndEnsureModified(project.getFile(new Path("folder1/a.txt")));
assertModificationState(project, new String[] {".", "changed.txt", "folder1/", "folder1/a.txt"}, true);
commitResources(project, new String[] {"folder1/a.txt"});
assertModificationState(project, new String[] {".", "changed.txt"}, true);
replace(new IResource[] {project.getFile("changed.txt")}, null, true);
assertModificationState(project, null, true);
}
public void testFileDeletions() throws CoreException, TeamException {
IProject project = createProject("testFileDeletions", new String[] { "changed.txt", "folder1/", "folder1/deleted.txt", "folder1/a.txt" });
// delete and commit a file
project.getFile("folder1/deleted.txt").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/deleted.txt"}, true);
commitResources(project, new String[] {"folder1/deleted.txt"});
assertModificationState(project, null, true);
// modify, delete and revert a file
setContentsAndEnsureModified(project.getFile("changed.txt"));
assertModificationState(project, new String[] {".", "changed.txt"}, true);
project.getFile("changed.txt").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "changed.txt"}, true);
replace(new IResource[] {project.getFile("changed.txt")}, null, true);
assertModificationState(project, null, true);
// modify, delete and commit a file
setContentsAndEnsureModified(project.getFile("changed.txt"));
assertModificationState(project, new String[] {".", "changed.txt"}, true);
project.getFile("changed.txt").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "changed.txt"}, true);
commitResources(project, new String[] {"changed.txt"});
assertModificationState(project, null, true);
// delete, recreate and commit
project.getFile("folder1/a.txt").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/a.txt"}, true);
buildResources(project, new String[] {"folder1/a.txt"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/a.txt"}, true);
commitResources(project, new String[] {"folder1/a.txt"});
assertModificationState(project, null, true);
}
public void testFileAdditions() throws CoreException, TeamException {
IProject project = createProject("testFileAdditions", new String[] { "changed.txt", "folder1/", "folder1/deleted.txt", "folder1/a.txt" });
// create, add and commit a file
IResource[] addedResources = buildResources(project, new String[] {"folder1/added.txt"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/added.txt"}, true);
addResources(addedResources);
assertModificationState(project, new String[] {".", "folder1/", "folder1/added.txt"}, true);
commitResources(project, new String[] {"folder1/added.txt"});
assertModificationState(project, null, true);
// create, add and delete a file
addResources(project, new String[] {"added.txt"}, false);
assertModificationState(project, new String[] {".", "added.txt"}, true);
project.getFile("added.txt").delete(false, false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// create and delete a file
addedResources = buildResources(project, new String[] {"folder1/another.txt"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/another.txt"}, true);
project.getFile("folder1/another.txt").delete(false, false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// create and ignore a file
addedResources = buildResources(project, new String[] {"ignored.txt"}, false);
assertModificationState(project, new String[] {".", "ignored.txt"}, true);
project.getFile(".cvsignore").create(new ByteArrayInputStream("ignored.txt".getBytes()), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", ".cvsignore"}, true);
addResources(new IResource[] {project.getFile(".cvsignore")});
assertModificationState(project, new String[] {".", ".cvsignore"}, true);
commitResources(project, new String[] {".cvsignore"});
assertModificationState(project, null, true);
// delete the .cvsignore to see the modification come back
project.getFile(".cvsignore").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "ignored.txt", ".cvsignore"}, true);
commitResources(project, new String[] {".cvsignore"});
assertModificationState(project, new String[] {".", "ignored.txt"}, true);
// re-add the ignore and then delete the ignored
project.getFile(".cvsignore").create(new ByteArrayInputStream("ignored.txt".getBytes()), false, DEFAULT_MONITOR);
addResources(new IResource[] {project.getFile(".cvsignore")});
assertModificationState(project, new String[] {".", ".cvsignore"}, true);
commitResources(project, new String[] {".cvsignore"});
assertModificationState(project, null, true);
project.getFile("ignored.txt").delete(false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// add the ignored file to version control
buildResources(project, new String[] {"ignored.txt"}, false);
assertModificationState(project, null, true);
addResources(new IResource[] {project.getFile("ignored.txt")});
assertModificationState(project, new String[] {".", "ignored.txt"}, true);
commitProject(project);
assertModificationState(project, null, true);
}
public void testFileMoveAndCopy() throws CoreException, TeamException {
IProject project = createProject("testFileMoveAndCopy", new String[] { "changed.txt", "folder1/", "folder2/", "folder1/a.txt" });
// move a file
project.getFile("folder1/a.txt").move(project.getFile("folder2/a.txt").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/a.txt", "folder2/", "folder2/a.txt"}, true);
// commit the source
commitResources(project, new String[] {"folder1/a.txt"});
assertModificationState(project, new String[] {".", "folder2/", "folder2/a.txt"}, true);
// copy the destination back to the source
project.getFolder("folder1").create(false, true, DEFAULT_MONITOR);
project.getFile("folder2/a.txt").copy(project.getFile("folder1/a.txt").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/a.txt", "folder2/", "folder2/a.txt"}, true);
// add the source, delete the destination and commit
addResources(new IResource[] {project.getFile("folder1/a.txt")});
project.getFile("folder2/a.txt").delete(false, DEFAULT_MONITOR);
commitProject(project);
assertModificationState(project, null, true);
// Do the above without committing the source
project.getFile("folder1/a.txt").move(project.getFile("folder2/a.txt").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/a.txt", "folder2/", "folder2/a.txt"}, true);
// copy the destination back to the source
project.getFile("folder2/a.txt").copy(project.getFile("folder1/a.txt").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder2/", "folder2/a.txt"}, true);
addResources(new IResource[] {project.getFile("folder2/a.txt")});
commitProject(project);
assertModificationState(project, null, true);
}
public void testFolderAdditions() throws CoreException, TeamException {
IProject project = createProject("testFileAdditions", new String[] { "changed.txt", "folder1/", "folder1/deleted.txt", "folder1/a.txt" });
// create a folder
project.getFolder("folder1/folder2").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/"}, true);
addResources(new IResource[] {project.getFolder("folder1/folder2/")});
assertModificationState(project, null, true);
// create a folder
project.getFolder("folder1/folder2/folder3").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/", "folder1/folder2/folder3"}, true);
// add some children
buildResources(project, new String[] {
"folder1/folder2/folder3/add1.txt",
"folder1/folder2/folder3/add2.txt",
"folder1/folder2/folder3/folder4/",
"folder1/folder2/folder3/folder5/"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/", "folder1/folder2/folder3",
"folder1/folder2/folder3/add1.txt",
"folder1/folder2/folder3/add2.txt",
"folder1/folder2/folder3/folder4/",
"folder1/folder2/folder3/folder5/"}, true);
// delete some children
project.getFile("folder1/folder2/folder3/add2.txt").delete(false, DEFAULT_MONITOR);
project.getFolder("folder1/folder2/folder3/folder5/").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/", "folder1/folder2/folder3",
"folder1/folder2/folder3/add1.txt",
"folder1/folder2/folder3/folder4/"}, true);
// add to version control
addResources(new IResource[] {
project.getFile("folder1/folder2/folder3/add1.txt"),
project.getFolder("folder1/folder2/folder3/folder4/")});
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/", "folder1/folder2/folder3",
"folder1/folder2/folder3/add1.txt"}, true);
// commit
commitResources(project, new String[] {"folder1/folder2/folder3/add1.txt"});
assertModificationState(project, null, true);
// create a folder
project.getFolder("folder1/ignored").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/ignored/"}, true);
// add some files
buildResources(project, new String[] {"folder1/ignored/file.txt"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/ignored/", "folder1/ignored/file.txt"}, true);
// ignore the folder
project.getFile("folder1/.cvsignore").create(new ByteArrayInputStream("ignored".getBytes()), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/.cvsignore"}, true);
addResources(new IResource[] {project.getFile("folder1/.cvsignore")});
assertModificationState(project, new String[] {".", "folder1/", "folder1/.cvsignore"}, true);
commitResources(project, new String[] {"folder1/.cvsignore"});
assertModificationState(project, null, true);
// delete the .cvsignore to see the modification come back
project.getFile("folder1/.cvsignore").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/.cvsignore", "folder1/ignored/", "folder1/ignored/file.txt"}, true);
commitResources(project, new String[] {"folder1/.cvsignore"});
assertModificationState(project, new String[] {".", "folder1/", "folder1/ignored/", "folder1/ignored/file.txt"}, true);
// re-add the .cvsignore and then delete the ignored
project.getFile("folder1/.cvsignore").create(new ByteArrayInputStream("ignored".getBytes()), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/.cvsignore"}, true);
addResources(new IResource[] {project.getFile("folder1/.cvsignore")});
commitResources(project, new String[] {"folder1/.cvsignore"});
assertModificationState(project, null, true);
project.getFolder("folder/ignored").delete(false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// add the ignored file to version control
buildResources(project, new String[] {"folder1/ignored/file.txt"}, false);
assertModificationState(project, null, true);
addResources(new IResource[] {project.getFile("folder1/ignored/file.txt")});
assertModificationState(project, new String[] {".", "folder1/", "folder1/ignored/", "folder1/ignored/file.txt"}, true);
commitProject(project);
assertModificationState(project, null, true);
}
public void testFolderDeletions() throws CoreException, TeamException {
IProject project = createProject("testFileAdditions", new String[] { "changed.txt", "folder1/", "folder1/deleted.txt", "folder1/a.txt" });
// create a folder
project.getFolder("folder1/folder2").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/"}, true);
// delete the folder
project.getFolder("folder1/folder2").delete(false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// create a folder
project.getFolder("folder1/folder2").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/"}, true);
// add some children
buildResources(project, new String[] {"folder1/folder2/file.txt"}, false);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder2/", "folder1/folder2/file.txt"}, true);
// delete the folder
project.getFolder("folder1/folder2").delete(false, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// delete a shared folder with files
project.getFolder("folder1").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/deleted.txt", "folder1/a.txt"}, true);
// recreate folders and files
project.getFolder("folder1").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/deleted.txt", "folder1/a.txt"}, true);
replace(new IResource[] {project.getFile("folder1/deleted.txt"), project.getFile("folder1/a.txt")}, null, true);
assertModificationState(project, null, true);
// delete a shared folder with files
project.getFolder("folder1").delete(false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/deleted.txt", "folder1/a.txt"}, true);
// commit file deletions
commitProject(project);
assertModificationState(project, null, true);
}
public void testFolderMoveAndCopy() throws CoreException, TeamException {
IProject project = createProject("testFolderMoveAndCopy", new String[] { "changed.txt", "folder1/", "folder2/", "folder1/a.txt" , "folder1/folder3/file.txt"});
// move a file
project.getFolder("folder1/folder3").move(project.getFolder("folder2/folder3").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder3", "folder1/folder3/file.txt", "folder2/", "folder2/folder3/", "folder2/folder3/file.txt"}, true);
// commit the source
commitResources(project, new String[] {"folder1/folder3"});
assertModificationState(project, new String[] {".", "folder2/", "folder2/folder3/", "folder2/folder3/file.txt"}, true);
// copy the destination back to the source
project.getFolder("folder2/folder3/").copy(project.getFolder("folder1/folder3").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder3", "folder1/folder3/file.txt", "folder2/", "folder2/folder3/", "folder2/folder3/file.txt"}, true);
// add the source, delete the destination and commit
addResources(new IResource[] {project.getFile("folder1/folder3/file.txt")});
project.getFolder("folder2/folder3").delete(false, DEFAULT_MONITOR);
commitProject(project);
assertModificationState(project, null, true);
// Do the above without committing the source
project.getFolder("folder1/folder3").move(project.getFolder("folder2/folder3").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder1/", "folder1/folder3", "folder1/folder3/file.txt", "folder2/", "folder2/folder3/", "folder2/folder3/file.txt"}, true);
// copy the destination back to the source
project.getFolder("folder2/folder3/").copy(project.getFolder("folder1/folder3").getFullPath(), false, DEFAULT_MONITOR);
assertModificationState(project, new String[] {".", "folder2/", "folder2/folder3/", "folder2/folder3/file.txt"}, true);
addResources(new IResource[] {project.getFolder("folder2/folder3/")});
commitProject(project);
assertModificationState(project, null, true);
}
public void testUpdate() throws TeamException, CoreException, IOException {
// Create a test project, import it into cvs and check it out
IProject project = createProject("testUpdate", new String[] { "changed.txt", "merged.txt", "deleted.txt", "folder1/", "folder1/a.txt" });
// Check the project out under a different name
IProject copy = checkoutCopy(project, "-copy");
assertModificationState(copy, null, true);
// Perform some operations on the copy and commit
addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false);
setContentsAndEnsureModified(copy.getFile("changed.txt"));
setContentsAndEnsureModified(copy.getFile("merged.txt"));
deleteResources(new IResource[] {copy.getFile("deleted.txt")});
assertModificationState(copy, new String[] {".", "added.txt", "folder2/", "folder2/added.txt", "changed.txt", "merged.txt", "deleted.txt"}, true);
commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE);
assertModificationState(copy, null, true);
// update the project and check status
setContentsAndEnsureModified(project.getFile("merged.txt"));
updateProject(project, null, false);
assertModificationState(project, new String[] {".", "merged.txt"}, true);
// can't commit because of merge
// commitProject(project);
// assertModificationState(project, null, true);
}
public void testUpdateIgnoreLocal() throws TeamException, CoreException, IOException {
// Create a test project, import it into cvs and check it out
IProject project = createProject("testUpdateIgnoreLocal", new String[] { "changed.txt", "merged.txt", "deleted.txt", "folder1/", "folder1/a.txt" });
// modifiy a file
setContentsAndEnsureModified(project.getFile("changed.txt"));
assertModificationState(project, new String[] {".", "changed.txt"}, true);
// peform un update -C
updateProject(project, null, true /* ignore local changes */);
assertModificationState(project, null, true);
}
public void testExternalDeletion() throws CoreException, TeamException {
IProject project = createProject("testExternalDeletion", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/folder2/b.txt"});
IFile file = project.getFile("folder1/unmanaged.txt");
file.create(new ByteArrayInputStream("stuff".getBytes()), false, DEFAULT_MONITOR);
file.getLocation().toFile().delete();
file.refreshLocal(IResource.DEPTH_ZERO, DEFAULT_MONITOR);
assertTrue(!file.exists());
assertModificationState(project, null, true);
}
public void testIgnoredAfterCheckout() throws TeamException, CoreException {
// Bug 43938
// Create a project and add a .cvsignore to it
IProject project = createProject("testIgnoredAfterCheckout", new String[] { ".changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/folder2/b.txt"});
project.getFile(".cvsignore").create(new ByteArrayInputStream("ignored".getBytes()), false, DEFAULT_MONITOR);
addResources(new IResource[] {project.getFile(".cvsignore")});
commitProject(project);
assertModificationState(project, null, true);
project.getFolder("ignored").create(false, true, DEFAULT_MONITOR);
assertModificationState(project, null, true);
// Checkout a copy and add the file to ensure it is ignored
// Check the project out under a different name
IProject copy = checkoutCopy(project, "-copy");
assertModificationState(copy, null, true);
copy.getFolder("ignored").create(false, true, DEFAULT_MONITOR);
assertModificationState(copy, null, true);
}
}
| true | true | private void assertModificationState(IContainer container, String[] resources, final boolean listedResourcesShouldBeModified) throws CVSException {
final ICVSFolder rootFolder = CVSWorkspaceRoot.getCVSFolderFor(container);
final List resourceList = new ArrayList();
final Set modifiedResources = new HashSet();
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
String string = resources[i];
resourceList.add(new Path(string));
}
}
waitForIgnoreFileHandling();
rootFolder.accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
assertModificationState(file);
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// find the deepest mistake
folder.acceptChildren(this);
assertModificationState(folder);
}
public void assertModificationState(ICVSResource resource) throws CVSException {
IPath relativePath = new Path(resource.getRelativePath(rootFolder));
boolean resourceModified = resource.isModified(null);
boolean resourceListed = resourceList.contains(relativePath);
assertTrue(resource.getIResource().getFullPath().toString()
+ (resourceModified ? " should not be modified but is" : " should be modified but isn't"),
(listedResourcesShouldBeModified && (resourceModified == resourceListed)) ||
(!listedResourcesShouldBeModified && (!resourceModified == resourceListed)));
// Commented because the CVS core doesn't rely on resourceModify to be called.
// IResource iResource = resource.getIResource();
// if (resource.isModified()) {
// modifiedResources.add(iResource);
// if (!wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.TRUE);
// }
// } else {
// if (wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.FALSE);
// }
// }
}
// public boolean wasPreviouslyModified(IResource iResource) {
// return previouslyModified.contains(iResource);
// }
});
changedResources.clear();
previouslyModified.clear();
previouslyModified.addAll(modifiedResources);
}
| private void assertModificationState(IContainer container, String[] resources, final boolean listedResourcesShouldBeModified) throws CVSException {
final ICVSFolder rootFolder = CVSWorkspaceRoot.getCVSFolderFor(container);
final List resourceList = new ArrayList();
final Set modifiedResources = new HashSet();
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
String string = resources[i];
resourceList.add(new Path(string));
}
}
waitForIgnoreFileHandling();
rootFolder.accept(new ICVSResourceVisitor() {
public void visitFile(ICVSFile file) throws CVSException {
assertModificationState(file);
}
public void visitFolder(ICVSFolder folder) throws CVSException {
// find the deepest mistake
folder.acceptChildren(this);
assertModificationState(folder);
}
public void assertModificationState(ICVSResource resource) throws CVSException {
IPath relativePath = new Path(resource.getRelativePath(rootFolder));
boolean resourceModified = resource.isModified(null);
boolean resourceListed = resourceList.contains(relativePath);
if (CVSTestSetup.FAIL_ON_BAD_DIFF) {
assertTrue(resource.getIResource().getFullPath().toString()
+ (resourceModified ? " should not be modified but is" : " should be modified but isn't"),
(listedResourcesShouldBeModified && (resourceModified == resourceListed)) ||
(!listedResourcesShouldBeModified && (!resourceModified == resourceListed)));
} else if (!resourceModified){
// Only fail if a file that should be modified isn't
assertTrue(resource.getIResource().getFullPath().toString()
+ " should be modified but isn't",
listedResourcesShouldBeModified == resourceListed);
}
// Commented because the CVS core doesn't rely on resourceModify to be called.
// IResource iResource = resource.getIResource();
// if (resource.isModified()) {
// modifiedResources.add(iResource);
// if (!wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.TRUE);
// }
// } else {
// if (wasPreviouslyModified(iResource)) {
// // the state has changed, make sure we got a notification
// Boolean b = (Boolean)changedResources.get(iResource);
// assertTrue("No notification received for state change of " + iResource.getFullPath().toString(),
// b == Boolean.FALSE);
// }
// }
}
// public boolean wasPreviouslyModified(IResource iResource) {
// return previouslyModified.contains(iResource);
// }
});
changedResources.clear();
previouslyModified.clear();
previouslyModified.addAll(modifiedResources);
}
|
diff --git a/core/rio/turtle/src/main/java/org/openrdf/rio/turtle/TurtleUtil.java b/core/rio/turtle/src/main/java/org/openrdf/rio/turtle/TurtleUtil.java
index 5845c9a7a..bb2a6471d 100644
--- a/core/rio/turtle/src/main/java/org/openrdf/rio/turtle/TurtleUtil.java
+++ b/core/rio/turtle/src/main/java/org/openrdf/rio/turtle/TurtleUtil.java
@@ -1,312 +1,320 @@
/*
* Licensed to Aduna under one or more contributor license agreements.
* See the NOTICE.txt file distributed with this work for additional
* information regarding copyright ownership.
*
* Aduna licenses this file to you under the terms of the Aduna BSD
* License (the "License"); you may not use this file except in compliance
* with the License. See the LICENSE.txt file distributed with this work
* for the full License.
*
* 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.openrdf.rio.turtle;
import java.util.Arrays;
import info.aduna.text.ASCIIUtil;
import info.aduna.text.StringUtil;
/**
* Utility methods for Turtle encoding/decoding.
*
* @see <a href="http://www.w3.org/TR/turtle/">Turtle: Terse RDF Triple
* Language</a>
*/
public class TurtleUtil {
public static final char[] LOCAL_ESCAPED_CHARS = new char[] {
'_',
'~',
'.',
'-',
'!',
'$',
'&',
'\'',
'(',
')',
'*',
'+',
',',
';',
'=',
'/',
'?',
'#',
'@',
'%' };
static {
// sorting array to allow simple binary search for char lookup.
Arrays.sort(LOCAL_ESCAPED_CHARS);
}
/**
* Tries to find an index where the supplied URI can be split into a
* namespace and a local name that comply with the serialization constraints
* of the Turtle format.
*
* @param uri
* The URI to split.
* @return The index where the supplied URI can be split, or <tt>-1</tt> if
* the URI cannot be split.
*/
public static int findURISplitIndex(String uri) {
int uriLength = uri.length();
int idx = uriLength - 1;
// Search last character that is not a name character
for (; idx >= 0; idx--) {
if (!TurtleUtil.isNameChar(uri.charAt(idx))) {
// Found a non-name character
break;
}
}
idx++;
// Local names need to start with a 'nameStartChar', skip characters
// that are not nameStartChar's.
for (; idx < uriLength; idx++) {
if (TurtleUtil.isNameStartChar(uri.charAt(idx))) {
break;
}
}
if (idx > 0 && idx < uriLength) {
// A valid split index has been found
return idx;
}
// No valid local name has been found
return -1;
}
public static boolean isWhitespace(int c) {
// Whitespace character are space, tab, newline and carriage return:
return c == 0x20 || c == 0x9 || c == 0xA || c == 0xD;
}
public static boolean isPrefixStartChar(int c) {
return ASCIIUtil.isLetter(c) || c >= 0x00C0 && c <= 0x00D6 || c >= 0x00D8 && c <= 0x00F6 || c >= 0x00F8
&& c <= 0x02FF || c >= 0x0370 && c <= 0x037D || c >= 0x037F && c <= 0x1FFF || c >= 0x200C
&& c <= 0x200D || c >= 0x2070 && c <= 0x218F || c >= 0x2C00 && c <= 0x2FEF || c >= 0x3001
&& c <= 0xD7FF || c >= 0xF900 && c <= 0xFDCF || c >= 0xFDF0 && c <= 0xFFFD || c >= 0x10000
&& c <= 0xEFFFF;
}
public static boolean isNameStartChar(int c) {
return c == '\\' || c == '_' || c == ':' || c == '%' || ASCIIUtil.isNumber(c) || isPrefixStartChar(c);
}
public static boolean isNameChar(int c) {
return isNameStartChar(c) || ASCIIUtil.isNumber(c) || c == '-' || c == 0x00B7 || c >= 0x0300
&& c <= 0x036F || c >= 0x203F && c <= 0x2040;
}
public static boolean isLocalEscapedChar(int c) {
return Arrays.binarySearch(LOCAL_ESCAPED_CHARS, (char)c) > -1;
}
public static boolean isPrefixChar(int c) {
return c == '_' || ASCIIUtil.isNumber(c) || isPrefixStartChar(c) || c == '-' || c == 0x00B7
|| c >= 0x0300 && c <= 0x036F || c >= 0x203F && c <= 0x2040;
}
public static boolean isLanguageStartChar(int c) {
return ASCIIUtil.isLetter(c);
}
public static boolean isLanguageChar(int c) {
return ASCIIUtil.isLetter(c) || ASCIIUtil.isNumber(c) || c == '-';
}
public static boolean isLegalPrefix(String prefix) {
if (prefix.length() == 0) {
return false;
}
if (!isPrefixStartChar(prefix.charAt(0))) {
return false;
}
// FIXME: Last character cannot be an unescaped period '.' character
for (int i = 1; i < prefix.length(); i++) {
if (!isPrefixChar(prefix.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isLegalName(String name) {
if (name.length() == 0) {
return false;
}
if (!isNameStartChar(name.charAt(0))) {
return false;
}
// FIXME: Last character cannot be an unescaped period '.' character
for (int i = 1; i < name.length(); i++) {
if (!isNameChar(name.charAt(i))) {
return false;
}
}
return true;
}
/**
* Encodes the supplied string for inclusion as a 'normal' string in a Turtle
* document.
*/
public static String encodeString(String s) {
s = StringUtil.gsub("\\", "\\\\", s);
s = StringUtil.gsub("\t", "\\t", s);
s = StringUtil.gsub("\n", "\\n", s);
s = StringUtil.gsub("\r", "\\r", s);
s = StringUtil.gsub("\"", "\\\"", s);
return s;
}
/**
* Encodes the supplied string for inclusion as a long string in a Turtle
* document.
**/
public static String encodeLongString(String s) {
// TODO: not all double quotes need to be escaped. It suffices to encode
// the ones that form sequences of 3 or more double quotes, and the ones
// at the end of a string.
s = StringUtil.gsub("\\", "\\\\", s);
s = StringUtil.gsub("\"", "\\\"", s);
return s;
}
/**
* Encodes the supplied string for inclusion as a (relative) URI in a Turtle
* document.
**/
public static String encodeURIString(String s) {
s = StringUtil.gsub("\\", "\\\\", s);
s = StringUtil.gsub(">", "\\>", s);
return s;
}
/**
* Decodes an encoded Turtle string. Any \-escape sequences are substituted
* with their decoded value.
*
* @param s
* An encoded Turtle string.
* @return The unencoded string.
* @exception IllegalArgumentException
* If the supplied string is not a correctly encoded Turtle
* string.
**/
public static String decodeString(String s) {
int backSlashIdx = s.indexOf('\\');
if (backSlashIdx == -1) {
// No escaped characters found
return s;
}
int startIdx = 0;
int sLength = s.length();
StringBuilder sb = new StringBuilder(sLength);
while (backSlashIdx != -1) {
sb.append(s.substring(startIdx, backSlashIdx));
if (backSlashIdx + 1 >= sLength) {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
char c = s.charAt(backSlashIdx + 1);
if (c == 't') {
sb.append('\t');
startIdx = backSlashIdx + 2;
}
else if (c == 'r') {
sb.append('\r');
startIdx = backSlashIdx + 2;
}
else if (c == 'n') {
sb.append('\n');
startIdx = backSlashIdx + 2;
}
+ else if (c == 'b') {
+ sb.append('\b');
+ startIdx = backSlashIdx + 2;
+ }
+ else if (c == 'f') {
+ sb.append('\f');
+ startIdx = backSlashIdx + 2;
+ }
else if (c == '"') {
sb.append('"');
startIdx = backSlashIdx + 2;
}
else if (c == '>') {
sb.append('>');
startIdx = backSlashIdx + 2;
}
else if (c == '\\') {
sb.append('\\');
startIdx = backSlashIdx + 2;
}
else if (c == 'u') {
// \\uxxxx
if (backSlashIdx + 5 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 6);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 6;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\u" + xx + "' in: " + s);
}
}
else if (c == 'U') {
// \\Uxxxxxxxx
if (backSlashIdx + 9 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 10);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 10;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\U" + xx + "' in: " + s);
}
}
else {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
backSlashIdx = s.indexOf('\\', startIdx);
}
sb.append(s.substring(startIdx));
return sb.toString();
}
}
| true | true | public static String decodeString(String s) {
int backSlashIdx = s.indexOf('\\');
if (backSlashIdx == -1) {
// No escaped characters found
return s;
}
int startIdx = 0;
int sLength = s.length();
StringBuilder sb = new StringBuilder(sLength);
while (backSlashIdx != -1) {
sb.append(s.substring(startIdx, backSlashIdx));
if (backSlashIdx + 1 >= sLength) {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
char c = s.charAt(backSlashIdx + 1);
if (c == 't') {
sb.append('\t');
startIdx = backSlashIdx + 2;
}
else if (c == 'r') {
sb.append('\r');
startIdx = backSlashIdx + 2;
}
else if (c == 'n') {
sb.append('\n');
startIdx = backSlashIdx + 2;
}
else if (c == '"') {
sb.append('"');
startIdx = backSlashIdx + 2;
}
else if (c == '>') {
sb.append('>');
startIdx = backSlashIdx + 2;
}
else if (c == '\\') {
sb.append('\\');
startIdx = backSlashIdx + 2;
}
else if (c == 'u') {
// \\uxxxx
if (backSlashIdx + 5 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 6);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 6;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\u" + xx + "' in: " + s);
}
}
else if (c == 'U') {
// \\Uxxxxxxxx
if (backSlashIdx + 9 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 10);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 10;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\U" + xx + "' in: " + s);
}
}
else {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
backSlashIdx = s.indexOf('\\', startIdx);
}
sb.append(s.substring(startIdx));
return sb.toString();
}
| public static String decodeString(String s) {
int backSlashIdx = s.indexOf('\\');
if (backSlashIdx == -1) {
// No escaped characters found
return s;
}
int startIdx = 0;
int sLength = s.length();
StringBuilder sb = new StringBuilder(sLength);
while (backSlashIdx != -1) {
sb.append(s.substring(startIdx, backSlashIdx));
if (backSlashIdx + 1 >= sLength) {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
char c = s.charAt(backSlashIdx + 1);
if (c == 't') {
sb.append('\t');
startIdx = backSlashIdx + 2;
}
else if (c == 'r') {
sb.append('\r');
startIdx = backSlashIdx + 2;
}
else if (c == 'n') {
sb.append('\n');
startIdx = backSlashIdx + 2;
}
else if (c == 'b') {
sb.append('\b');
startIdx = backSlashIdx + 2;
}
else if (c == 'f') {
sb.append('\f');
startIdx = backSlashIdx + 2;
}
else if (c == '"') {
sb.append('"');
startIdx = backSlashIdx + 2;
}
else if (c == '>') {
sb.append('>');
startIdx = backSlashIdx + 2;
}
else if (c == '\\') {
sb.append('\\');
startIdx = backSlashIdx + 2;
}
else if (c == 'u') {
// \\uxxxx
if (backSlashIdx + 5 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 6);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 6;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\u" + xx + "' in: " + s);
}
}
else if (c == 'U') {
// \\Uxxxxxxxx
if (backSlashIdx + 9 >= sLength) {
throw new IllegalArgumentException("Incomplete Unicode escape sequence in: " + s);
}
String xx = s.substring(backSlashIdx + 2, backSlashIdx + 10);
try {
c = (char)Integer.parseInt(xx, 16);
sb.append(c);
startIdx = backSlashIdx + 10;
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal Unicode escape sequence '\\U" + xx + "' in: " + s);
}
}
else {
throw new IllegalArgumentException("Unescaped backslash in: " + s);
}
backSlashIdx = s.indexOf('\\', startIdx);
}
sb.append(s.substring(startIdx));
return sb.toString();
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/CleanUpData.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/CleanUpData.java
index 7f14cb46..ff60670e 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/CleanUpData.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/CleanUpData.java
@@ -1,165 +1,166 @@
/**
* This file is part of OSM2GpsMid
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* Copyright (C) 2007 Harald Mueller
* Copyright (C) 2007, 2008 Kai Krueger
*/
package de.ueller.osmToGpsMid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import de.ueller.osmToGpsMid.model.Node;
import de.ueller.osmToGpsMid.model.SubPath;
import de.ueller.osmToGpsMid.model.Way;
import edu.wlu.cs.levy.CG.KDTree;
import edu.wlu.cs.levy.CG.KeyDuplicateException;
import edu.wlu.cs.levy.CG.KeySizeException;
/**
* @author hmueller
*
*/
public class CleanUpData {
private final OxParser parser;
private final Configuration conf;
private HashMap<Node,Node> replaceNodes = new HashMap<Node,Node>();
public CleanUpData(OxParser parser, Configuration conf) {
this.parser = parser;
this.conf = conf;
removeDupNodes();
removeUnusedNodes();
parser.resize();
System.out.println("after cleanup Nodes " + parser.getNodes().size());
System.out.println("after cleanup Ways " + parser.getWays().size());
System.out.println("after cleanup Relations " + parser.getRelations().size());
// System.exit(1);
}
/**
*
*/
private void removeDupNodes() {
int progressCounter = 0;
int noNodes = parser.getNodes().size()/20;
KDTree kd = new KDTree(3);
double [] latlonKey;
double [] lowk = new double[3];
double [] uppk = new double[3];
for (Node n:parser.getNodes()){
progressCounter++;
if (noNodes > 0 && progressCounter % noNodes == 0) {
System.out.println("Processed " + progressCounter + " out of " + noNodes*20 + " Nodes");
}
n.used=true;
latlonKey = MyMath.latlon2XYZ(n);
/*lowk[0] = latlonKey[0] - 10.0;
lowk[1] = latlonKey[1] - 10.0;
lowk[2] = latlonKey[2] - 10.0;
uppk[0] = latlonKey[0] + 10.0;
uppk[1] = latlonKey[1] + 10.0;
uppk[2] = latlonKey[2] + 10.0;
try {
Object[] neighbours = kd.range(lowk, uppk);
if (neighbours.length == 1) {
n.used = false;
if (!substitute(n, (Node)neighbours[0]))
kd.insert(latlonKey, n);
} else if (neighbours.length > 1) {
n.used = false;
if (!substitute(n,(Node)kd.nearest(latlonKey)))
kd.insert(latlonKey, n);
} else {*/
try {
kd.insert(latlonKey, n);
//}
} catch (KeySizeException e) {
e.printStackTrace();
} catch (KeyDuplicateException e) {
//System.out.println("Key Duplication");
try {
n.used = false;
Node rn = (Node)kd.search(latlonKey);
if (n.getType(conf) != rn.getType(conf)){
System.err.println("Warn " + n + " / " + rn);
//Shouldn't substitute in this case;
n.used = true;
} else {
replaceNodes.put(n, rn);
}
} catch (KeySizeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Iterator<Node> it=parser.getNodes().iterator();
int rm=0;
while (it.hasNext()){
Node n=it.next();
if (! n.used){
it.remove();
rm++;
}
}
+ substitute();
System.out.println("remove " + rm + " dupLicate Nodes");
}
/**
* @param no
* @param n
*/
private boolean substitute() {
for (Way w:parser.getWays()){
w.replace(replaceNodes);
}
return true;
}
/**
*
*/
private void removeUnusedNodes() {
for (Node n:parser.getNodes()){
if (n.getType(conf) < 0 ){
n.used=false;
} else {
n.used=true;
}
}
for (Way w:parser.getWays()){
for (SubPath s:w.getSubPaths()){
for (Node n:s.getNodes()){
n.used=true;
}
}
}
ArrayList<Node> rmNodes=new ArrayList<Node>();
for (Node n:parser.getNodes()){
if (! n.used){
rmNodes.add(n);
}
}
System.out.println("remove " + rmNodes.size() + " unused Nodes");
for (Node n:rmNodes){
parser.removeNode(n.id);
}
}
}
| true | true | private void removeDupNodes() {
int progressCounter = 0;
int noNodes = parser.getNodes().size()/20;
KDTree kd = new KDTree(3);
double [] latlonKey;
double [] lowk = new double[3];
double [] uppk = new double[3];
for (Node n:parser.getNodes()){
progressCounter++;
if (noNodes > 0 && progressCounter % noNodes == 0) {
System.out.println("Processed " + progressCounter + " out of " + noNodes*20 + " Nodes");
}
n.used=true;
latlonKey = MyMath.latlon2XYZ(n);
/*lowk[0] = latlonKey[0] - 10.0;
lowk[1] = latlonKey[1] - 10.0;
lowk[2] = latlonKey[2] - 10.0;
uppk[0] = latlonKey[0] + 10.0;
uppk[1] = latlonKey[1] + 10.0;
uppk[2] = latlonKey[2] + 10.0;
try {
Object[] neighbours = kd.range(lowk, uppk);
if (neighbours.length == 1) {
n.used = false;
if (!substitute(n, (Node)neighbours[0]))
kd.insert(latlonKey, n);
} else if (neighbours.length > 1) {
n.used = false;
if (!substitute(n,(Node)kd.nearest(latlonKey)))
kd.insert(latlonKey, n);
} else {*/
try {
kd.insert(latlonKey, n);
//}
} catch (KeySizeException e) {
e.printStackTrace();
} catch (KeyDuplicateException e) {
//System.out.println("Key Duplication");
try {
n.used = false;
Node rn = (Node)kd.search(latlonKey);
if (n.getType(conf) != rn.getType(conf)){
System.err.println("Warn " + n + " / " + rn);
//Shouldn't substitute in this case;
n.used = true;
} else {
replaceNodes.put(n, rn);
}
} catch (KeySizeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Iterator<Node> it=parser.getNodes().iterator();
int rm=0;
while (it.hasNext()){
Node n=it.next();
if (! n.used){
it.remove();
rm++;
}
}
System.out.println("remove " + rm + " dupLicate Nodes");
}
/**
* @param no
* @param n
*/
private boolean substitute() {
for (Way w:parser.getWays()){
w.replace(replaceNodes);
}
return true;
}
/**
*
*/
private void removeUnusedNodes() {
for (Node n:parser.getNodes()){
if (n.getType(conf) < 0 ){
n.used=false;
} else {
n.used=true;
}
}
for (Way w:parser.getWays()){
for (SubPath s:w.getSubPaths()){
for (Node n:s.getNodes()){
n.used=true;
}
}
}
ArrayList<Node> rmNodes=new ArrayList<Node>();
for (Node n:parser.getNodes()){
if (! n.used){
rmNodes.add(n);
}
}
System.out.println("remove " + rmNodes.size() + " unused Nodes");
for (Node n:rmNodes){
parser.removeNode(n.id);
}
}
}
| private void removeDupNodes() {
int progressCounter = 0;
int noNodes = parser.getNodes().size()/20;
KDTree kd = new KDTree(3);
double [] latlonKey;
double [] lowk = new double[3];
double [] uppk = new double[3];
for (Node n:parser.getNodes()){
progressCounter++;
if (noNodes > 0 && progressCounter % noNodes == 0) {
System.out.println("Processed " + progressCounter + " out of " + noNodes*20 + " Nodes");
}
n.used=true;
latlonKey = MyMath.latlon2XYZ(n);
/*lowk[0] = latlonKey[0] - 10.0;
lowk[1] = latlonKey[1] - 10.0;
lowk[2] = latlonKey[2] - 10.0;
uppk[0] = latlonKey[0] + 10.0;
uppk[1] = latlonKey[1] + 10.0;
uppk[2] = latlonKey[2] + 10.0;
try {
Object[] neighbours = kd.range(lowk, uppk);
if (neighbours.length == 1) {
n.used = false;
if (!substitute(n, (Node)neighbours[0]))
kd.insert(latlonKey, n);
} else if (neighbours.length > 1) {
n.used = false;
if (!substitute(n,(Node)kd.nearest(latlonKey)))
kd.insert(latlonKey, n);
} else {*/
try {
kd.insert(latlonKey, n);
//}
} catch (KeySizeException e) {
e.printStackTrace();
} catch (KeyDuplicateException e) {
//System.out.println("Key Duplication");
try {
n.used = false;
Node rn = (Node)kd.search(latlonKey);
if (n.getType(conf) != rn.getType(conf)){
System.err.println("Warn " + n + " / " + rn);
//Shouldn't substitute in this case;
n.used = true;
} else {
replaceNodes.put(n, rn);
}
} catch (KeySizeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Iterator<Node> it=parser.getNodes().iterator();
int rm=0;
while (it.hasNext()){
Node n=it.next();
if (! n.used){
it.remove();
rm++;
}
}
substitute();
System.out.println("remove " + rm + " dupLicate Nodes");
}
/**
* @param no
* @param n
*/
private boolean substitute() {
for (Way w:parser.getWays()){
w.replace(replaceNodes);
}
return true;
}
/**
*
*/
private void removeUnusedNodes() {
for (Node n:parser.getNodes()){
if (n.getType(conf) < 0 ){
n.used=false;
} else {
n.used=true;
}
}
for (Way w:parser.getWays()){
for (SubPath s:w.getSubPaths()){
for (Node n:s.getNodes()){
n.used=true;
}
}
}
ArrayList<Node> rmNodes=new ArrayList<Node>();
for (Node n:parser.getNodes()){
if (! n.used){
rmNodes.add(n);
}
}
System.out.println("remove " + rmNodes.size() + " unused Nodes");
for (Node n:rmNodes){
parser.removeNode(n.id);
}
}
}
|
diff --git a/devoxx-schedule/src/net/peterkuterna/android/apps/devoxxsched/io/RemoteScheduleHandler.java b/devoxx-schedule/src/net/peterkuterna/android/apps/devoxxsched/io/RemoteScheduleHandler.java
index 3898d2c..70435fc 100644
--- a/devoxx-schedule/src/net/peterkuterna/android/apps/devoxxsched/io/RemoteScheduleHandler.java
+++ b/devoxx-schedule/src/net/peterkuterna/android/apps/devoxxsched/io/RemoteScheduleHandler.java
@@ -1,171 +1,173 @@
/*
* Copyright 2010 Peter Kuterna
*
* 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 net.peterkuterna.android.apps.devoxxsched.io;
import java.util.ArrayList;
import java.util.HashMap;
import net.peterkuterna.android.apps.devoxxsched.provider.ScheduleContract;
import net.peterkuterna.android.apps.devoxxsched.provider.ScheduleContract.Blocks;
import net.peterkuterna.android.apps.devoxxsched.provider.ScheduleContract.Rooms;
import net.peterkuterna.android.apps.devoxxsched.provider.ScheduleContract.Sessions;
import net.peterkuterna.android.apps.devoxxsched.util.Lists;
import net.peterkuterna.android.apps.devoxxsched.util.Maps;
import net.peterkuterna.android.apps.devoxxsched.util.ParserUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Handle a remote {@link JSONArray} that defines a set of {@link Blocks}
* entries. Also updates the related {@link Sessions} with {@link Rooms} and
* {@link Blocks} info.
*/
public class RemoteScheduleHandler extends JSONHandler {
private static final String TAG = "ScheduleHandler";
public RemoteScheduleHandler() {
super(ScheduleContract.CONTENT_AUTHORITY, false);
}
@Override
public ArrayList<ContentProviderOperation> parse(JSONArray schedules, ContentResolver resolver) throws JSONException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();
Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
for (int i=0; i<schedules.length(); i++) {
JSONObject schedule = schedules.getJSONObject(i);
final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
final String blockId = Blocks.generateBlockId(startTime, endTime);
if (!blockBatchMap.containsKey(blockId)) {
final Uri blockUri = Blocks.buildBlockUri(blockId);
ContentProviderOperation.Builder builder;
if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
builder = ContentProviderOperation.newUpdate(blockUri);
} else {
builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
builder.withValue(Blocks.BLOCK_ID, blockId);
}
builder.withValue(Blocks.BLOCK_START, startTime);
builder.withValue(Blocks.BLOCK_END, endTime);
final String type = schedule.getString("type");
final String code = schedule.getString("code");
final String kind = schedule.getString("kind");
if (code.startsWith("D10")) {
builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
} else {
builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
}
builder.withValue(Blocks.BLOCK_TYPE, kind);
blockBatchMap.put(blockId, builder.build());
}
if (schedule.has("presentationUri")) {
final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
final String sessionId = presentationUri.getLastPathSegment();
final Uri sessionUri = Sessions.buildSessionUri(sessionId);
if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
String roomId = null;
if (schedule.has("room")) {
final String roomName = schedule.getString("room");
Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName), RoomsQuery.PROJECTION, null, null, null);
if (cursor.moveToNext()) {
roomId = cursor.getString(RoomsQuery.ROOM_ID);
}
cursor.close();
}
final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(sessionUri);
builder.withValue(Sessions.BLOCK_ID, blockId);
builder.withValue(Sessions.ROOM_ID, roomId);
if (schedule.has("note")) {
final String note = schedule.getString("note");
if (note != null && note.trim().length() > 0) {
builder.withValue(Sessions.NOTE, note.trim());
}
}
sessionUpdateBatchMap.put(sessionId, builder.build());
}
}
}
batch.addAll(blockBatchMap.values());
batch.addAll(sessionUpdateBatchMap.values());
if (schedules.length() > 0) {
for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION, BlocksQuery.BLOCK_ID, resolver)) {
final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
}
for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI, SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
- final Uri lostSessionUri = Sessions.buildSessionUri(lostId);
- batch.add(ContentProviderOperation.newDelete(lostSessionUri).build());
+ Uri deleteUri = Sessions.buildSpeakersDirUri(lostId);
+ batch.add(ContentProviderOperation.newDelete(deleteUri).build());
+ deleteUri = Sessions.buildSessionUri(lostId);
+ batch.add(ContentProviderOperation.newDelete(deleteUri).build());
}
}
return batch;
}
private interface SessionsQuery {
String[] PROJECTION = {
Sessions.SESSION_ID,
};
int SESSION_ID = 0;
}
private interface BlocksQuery {
String[] PROJECTION = {
Blocks.BLOCK_ID,
};
int BLOCK_ID = 0;
}
private interface RoomsQuery {
String[] PROJECTION = {
BaseColumns._ID,
Rooms.ROOM_ID,
};
int _ID = 0;
int ROOM_ID = 1;
}
}
| true | true | public ArrayList<ContentProviderOperation> parse(JSONArray schedules, ContentResolver resolver) throws JSONException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();
Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
for (int i=0; i<schedules.length(); i++) {
JSONObject schedule = schedules.getJSONObject(i);
final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
final String blockId = Blocks.generateBlockId(startTime, endTime);
if (!blockBatchMap.containsKey(blockId)) {
final Uri blockUri = Blocks.buildBlockUri(blockId);
ContentProviderOperation.Builder builder;
if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
builder = ContentProviderOperation.newUpdate(blockUri);
} else {
builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
builder.withValue(Blocks.BLOCK_ID, blockId);
}
builder.withValue(Blocks.BLOCK_START, startTime);
builder.withValue(Blocks.BLOCK_END, endTime);
final String type = schedule.getString("type");
final String code = schedule.getString("code");
final String kind = schedule.getString("kind");
if (code.startsWith("D10")) {
builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
} else {
builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
}
builder.withValue(Blocks.BLOCK_TYPE, kind);
blockBatchMap.put(blockId, builder.build());
}
if (schedule.has("presentationUri")) {
final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
final String sessionId = presentationUri.getLastPathSegment();
final Uri sessionUri = Sessions.buildSessionUri(sessionId);
if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
String roomId = null;
if (schedule.has("room")) {
final String roomName = schedule.getString("room");
Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName), RoomsQuery.PROJECTION, null, null, null);
if (cursor.moveToNext()) {
roomId = cursor.getString(RoomsQuery.ROOM_ID);
}
cursor.close();
}
final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(sessionUri);
builder.withValue(Sessions.BLOCK_ID, blockId);
builder.withValue(Sessions.ROOM_ID, roomId);
if (schedule.has("note")) {
final String note = schedule.getString("note");
if (note != null && note.trim().length() > 0) {
builder.withValue(Sessions.NOTE, note.trim());
}
}
sessionUpdateBatchMap.put(sessionId, builder.build());
}
}
}
batch.addAll(blockBatchMap.values());
batch.addAll(sessionUpdateBatchMap.values());
if (schedules.length() > 0) {
for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION, BlocksQuery.BLOCK_ID, resolver)) {
final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
}
for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI, SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
final Uri lostSessionUri = Sessions.buildSessionUri(lostId);
batch.add(ContentProviderOperation.newDelete(lostSessionUri).build());
}
}
return batch;
}
| public ArrayList<ContentProviderOperation> parse(JSONArray schedules, ContentResolver resolver) throws JSONException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();
Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
for (int i=0; i<schedules.length(); i++) {
JSONObject schedule = schedules.getJSONObject(i);
final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
final String blockId = Blocks.generateBlockId(startTime, endTime);
if (!blockBatchMap.containsKey(blockId)) {
final Uri blockUri = Blocks.buildBlockUri(blockId);
ContentProviderOperation.Builder builder;
if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
builder = ContentProviderOperation.newUpdate(blockUri);
} else {
builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
builder.withValue(Blocks.BLOCK_ID, blockId);
}
builder.withValue(Blocks.BLOCK_START, startTime);
builder.withValue(Blocks.BLOCK_END, endTime);
final String type = schedule.getString("type");
final String code = schedule.getString("code");
final String kind = schedule.getString("kind");
if (code.startsWith("D10")) {
builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
} else {
builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
}
builder.withValue(Blocks.BLOCK_TYPE, kind);
blockBatchMap.put(blockId, builder.build());
}
if (schedule.has("presentationUri")) {
final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
final String sessionId = presentationUri.getLastPathSegment();
final Uri sessionUri = Sessions.buildSessionUri(sessionId);
if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
String roomId = null;
if (schedule.has("room")) {
final String roomName = schedule.getString("room");
Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName), RoomsQuery.PROJECTION, null, null, null);
if (cursor.moveToNext()) {
roomId = cursor.getString(RoomsQuery.ROOM_ID);
}
cursor.close();
}
final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(sessionUri);
builder.withValue(Sessions.BLOCK_ID, blockId);
builder.withValue(Sessions.ROOM_ID, roomId);
if (schedule.has("note")) {
final String note = schedule.getString("note");
if (note != null && note.trim().length() > 0) {
builder.withValue(Sessions.NOTE, note.trim());
}
}
sessionUpdateBatchMap.put(sessionId, builder.build());
}
}
}
batch.addAll(blockBatchMap.values());
batch.addAll(sessionUpdateBatchMap.values());
if (schedules.length() > 0) {
for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION, BlocksQuery.BLOCK_ID, resolver)) {
final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
}
for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI, SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
Uri deleteUri = Sessions.buildSpeakersDirUri(lostId);
batch.add(ContentProviderOperation.newDelete(deleteUri).build());
deleteUri = Sessions.buildSessionUri(lostId);
batch.add(ContentProviderOperation.newDelete(deleteUri).build());
}
}
return batch;
}
|
diff --git a/micropolis-java/src/micropolisj/engine/Micropolis.java b/micropolis-java/src/micropolisj/engine/Micropolis.java
index f10e839..30a5daf 100644
--- a/micropolis-java/src/micropolisj/engine/Micropolis.java
+++ b/micropolis-java/src/micropolisj/engine/Micropolis.java
@@ -1,2602 +1,2602 @@
// This file is part of MicropolisJ.
// Copyright (C) 2013 Jason Long
// Portions Copyright (C) 1989-2007 Electronic Arts Inc.
//
// MicropolisJ is free software; you can redistribute it and/or modify
// it under the terms of the GNU GPLv3, with additional terms.
// See the README file, included in this distribution, for details.
package micropolisj.engine;
import java.io.*;
import java.util.*;
import static micropolisj.engine.TileConstants.*;
/**
* The main simulation engine for Micropolis.
* The front-end should call animate() periodically
* to move the simulation forward in time.
*/
public class Micropolis
{
static final Random DEFAULT_PRNG = new Random();
Random PRNG;
// full size arrays
char [][] map;
boolean [][] powerMap;
// half-size arrays
/**
* For each 2x2 section of the city, the land value of the city (0-250).
* 0 is lowest land value; 250 is maximum land value.
* Updated each cycle by ptlScan().
*/
public int [][] landValueMem;
/**
* For each 2x2 section of the city, the pollution level of the city (0-255).
* 0 is no pollution; 255 is maximum pollution.
* Updated each cycle by ptlScan(); affects land value.
*/
public int [][] pollutionMem;
/**
* For each 2x2 section of the city, the crime level of the city (0-250).
* 0 is no crime; 250 is maximum crime.
* Updated each cycle by crimeScan(); affects land value.
*/
public int [][] crimeMem;
/**
* For each 2x2 section of the city, the population density (0-?).
* Used for map overlays and as a factor for crime rates.
*/
public int [][] popDensity;
/**
* For each 2x2 section of the city, the traffic density (0-255).
* If less than 64, no cars are animated.
* If between 64 and 192, then the "light traffic" animation is used.
* If 192 or higher, then the "heavy traffic" animation is used.
*/
public int [][] trfDensity;
// quarter-size arrays
/**
* For each 4x4 section of the city, an integer representing the natural
* land features in the vicinity of this part of the city.
*/
int [][] terrainMem;
// eighth-size arrays
/**
* For each 8x8 section of the city, the rate of growth.
* Capped to a number between -200 and 200.
* Used for reporting purposes only; the number has no affect.
*/
public int [][] rateOGMem; //rate of growth?
int [][] fireStMap; //firestations- cleared and rebuilt each sim cycle
public int [][] fireRate; //firestations reach- used for overlay graphs
int [][] policeMap; //police stations- cleared and rebuilt each sim cycle
public int [][] policeMapEffect;//police stations reach- used for overlay graphs
/** For each 8x8 section of city, this is an integer between 0 and 64,
* with higher numbers being closer to the center of the city. */
int [][] comRate;
static final int DEFAULT_WIDTH = 120;
static final int DEFAULT_HEIGHT = 100;
public final CityBudget budget = new CityBudget(this);
public boolean autoBulldoze = true;
public boolean autoBudget = false;
public Speed simSpeed = Speed.NORMAL;
public boolean noDisasters = false;
public int gameLevel;
boolean autoGo;
// census numbers, reset in phase 0 of each cycle, summed during map scan
int poweredZoneCount;
int unpoweredZoneCount;
int roadTotal;
int railTotal;
int firePop;
int resZoneCount;
int comZoneCount;
int indZoneCount;
int resPop;
int comPop;
int indPop;
int hospitalCount;
int churchCount;
int policeCount;
int fireStationCount;
int stadiumCount;
int coalCount;
int nuclearCount;
int seaportCount;
int airportCount;
int totalPop;
int lastCityPop;
// used in generateBudget()
int lastRoadTotal;
int lastRailTotal;
int lastTotalPop;
int lastFireStationCount;
int lastPoliceCount;
int trafficMaxLocationX;
int trafficMaxLocationY;
int pollutionMaxLocationX;
int pollutionMaxLocationY;
int crimeMaxLocationX;
int crimeMaxLocationY;
public int centerMassX;
public int centerMassY;
CityLocation meltdownLocation; //may be null
CityLocation crashLocation; //may be null
int needHospital; // -1 too many already, 0 just right, 1 not enough
int needChurch; // -1 too many already, 0 just right, 1 not enough
int crimeAverage;
int pollutionAverage;
int landValueAverage;
int trafficAverage;
int resValve; // ranges between -2000 and 2000, updated by setValves
int comValve; // ranges between -1500 and 1500
int indValve; // ranges between -1500 and 1500
boolean resCap; // residents demand a stadium, caps resValve at 0
boolean comCap; // commerce demands airport, caps comValve at 0
boolean indCap; // industry demands sea port, caps indValve at 0
int crimeRamp;
int polluteRamp;
//
// budget stuff
//
public int cityTax = 7;
public double roadPercent = 1.0;
public double policePercent = 1.0;
public double firePercent = 1.0;
int taxEffect = 7;
int roadEffect = 32;
int policeEffect = 1000;
int fireEffect = 1000;
int cashFlow; //net change in totalFunds in previous year
boolean newPower;
int floodCnt; //number of turns the flood will last
int floodX;
int floodY;
public int cityTime; //counts "weeks" (actually, 1/48'ths years)
int scycle; //same as cityTime, except mod 1024
int fcycle; //counts simulation steps (mod 1024)
int acycle; //animation cycle (mod 960)
public CityEval evaluation;
ArrayList<Sprite> sprites = new ArrayList<Sprite>();
static final int VALVERATE = 2;
public static final int CENSUSRATE = 4;
static final int TAXFREQ = 48;
public void spend(int amount)
{
budget.totalFunds -= amount;
fireFundsChanged();
}
public Micropolis()
{
this(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public Micropolis(int width, int height)
{
PRNG = DEFAULT_PRNG;
evaluation = new CityEval(this);
init(width, height);
}
protected void init(int width, int height)
{
map = new char[height][width];
powerMap = new boolean[height][width];
int hX = (width+1)/2;
int hY = (height+1)/2;
landValueMem = new int[hY][hX];
pollutionMem = new int[hY][hX];
crimeMem = new int[hY][hX];
popDensity = new int[hY][hX];
trfDensity = new int[hY][hX];
int qX = (width+3)/4;
int qY = (height+3)/4;
terrainMem = new int[qY][qX];
int smX = (width+7)/8;
int smY = (height+7)/8;
rateOGMem = new int[smY][smX];
fireStMap = new int[smY][smX];
policeMap = new int[smY][smX];
policeMapEffect = new int[smY][smX];
fireRate = new int[smY][smX];
comRate = new int[smY][smX];
centerMassX = hX;
centerMassY = hY;
}
void fireCensusChanged()
{
for (Listener l : listeners) {
l.censusChanged();
}
}
void fireCityMessage(MicropolisMessage message, CityLocation loc, boolean isPic)
{
for (Listener l : listeners) {
l.cityMessage(message, loc, isPic);
}
}
void fireCitySound(Sound sound, CityLocation loc)
{
for (Listener l : listeners) {
l.citySound(sound, loc);
}
}
void fireDemandChanged()
{
for (Listener l : listeners) {
l.demandChanged();
}
}
void fireEarthquakeStarted()
{
for (EarthquakeListener l : earthquakeListeners) {
l.earthquakeStarted();
}
}
void fireEvaluationChanged()
{
for (Listener l : listeners) {
l.evaluationChanged();
}
}
void fireFundsChanged()
{
for (Listener l : listeners) {
l.fundsChanged();
}
}
void fireMapOverlayDataChanged(MapState overlayDataType)
{
for (MapListener l : mapListeners) {
l.mapOverlayDataChanged(overlayDataType);
}
}
void fireOptionsChanged()
{
for (Listener l : listeners)
{
l.optionsChanged();
}
}
void fireSpriteMoved(Sprite sprite)
{
for (MapListener l : mapListeners)
{
l.spriteMoved(sprite);
}
}
void fireTileChanged(int xpos, int ypos)
{
for (MapListener l : mapListeners)
{
l.tileChanged(xpos, ypos);
}
}
void fireWholeMapChanged()
{
for (MapListener l : mapListeners)
{
l.wholeMapChanged();
}
}
ArrayList<Listener> listeners = new ArrayList<Listener>();
ArrayList<MapListener> mapListeners = new ArrayList<MapListener>();
ArrayList<EarthquakeListener> earthquakeListeners = new ArrayList<EarthquakeListener>();
public void addListener(Listener l)
{
this.listeners.add(l);
}
public void removeListener(Listener l)
{
this.listeners.remove(l);
}
public void addEarthquakeListener(EarthquakeListener l)
{
this.earthquakeListeners.add(l);
}
public void removeEarthquakeListener(EarthquakeListener l)
{
this.earthquakeListeners.remove(l);
}
public void addMapListener(MapListener l)
{
this.mapListeners.add(l);
}
public void removeMapListener(MapListener l)
{
this.mapListeners.remove(l);
}
/**
* The listener interface for receiving miscellaneous events that occur
* in the Micropolis city.
* Use the Micropolis class's addListener interface to register an object
* that implements this interface.
*/
public interface Listener
{
void cityMessage(MicropolisMessage message, CityLocation loc, boolean isPic);
void citySound(Sound sound, CityLocation loc);
/**
* Fired whenever the "census" is taken, and the various historical
* counters have been updated. (Once a month in game.)
*/
void censusChanged();
/**
* Fired whenever resValve, comValve, or indValve changes.
* (Twice a month in game.) */
void demandChanged();
/**
* Fired whenever the city evaluation is recalculated.
* (Once a year.)
*/
void evaluationChanged();
/**
* Fired whenever the mayor's money changes.
*/
void fundsChanged();
/**
* Fired whenever autoBulldoze, autoBudget, noDisasters,
* or simSpeed change.
*/
void optionsChanged();
}
public int getWidth()
{
return map[0].length;
}
public int getHeight()
{
return map.length;
}
public char getTile(int xpos, int ypos)
{
return map[ypos][xpos];
}
public void setTile(int xpos, int ypos, char newTile)
{
if (map[ypos][xpos] != newTile)
{
map[ypos][xpos] = newTile;
fireTileChanged(xpos, ypos);
}
}
final public boolean testBounds(int xpos, int ypos)
{
return xpos >= 0 && xpos < getWidth() &&
ypos >= 0 && ypos < getHeight();
}
final boolean hasPower(int x, int y)
{
return powerMap[y][x];
}
/**
* Checks whether the next call to animate() will collect taxes and
* process the budget.
*/
public boolean isBudgetTime()
{
return (
cityTime != 0 &&
(cityTime % TAXFREQ) == 0 &&
((fcycle + 1) % 16) == 10 &&
((acycle + 1) % 2) == 0
);
}
void step()
{
fcycle = (fcycle + 1) % 1024;
simulate(fcycle % 16);
}
void clearCensus()
{
poweredZoneCount = 0;
unpoweredZoneCount = 0;
firePop = 0;
roadTotal = 0;
railTotal = 0;
resPop = 0;
comPop = 0;
indPop = 0;
resZoneCount = 0;
comZoneCount = 0;
indZoneCount = 0;
hospitalCount = 0;
churchCount = 0;
policeCount = 0;
fireStationCount = 0;
stadiumCount = 0;
coalCount = 0;
nuclearCount = 0;
seaportCount = 0;
airportCount = 0;
powerPlants.clear();
for (int y = 0; y < fireStMap.length; y++) {
for (int x = 0; x < fireStMap[y].length; x++) {
fireStMap[y][x] = 0;
policeMap[y][x] = 0;
}
}
}
void simulate(int mod16)
{
final int band = getWidth() / 8;
switch (mod16)
{
case 0:
scycle = (scycle + 1) % 1024;
cityTime++;
if (scycle % 2 == 0) {
setValves();
}
clearCensus();
break;
case 1:
mapScan(0 * band, 1 * band);
break;
case 2:
mapScan(1 * band, 2 * band);
break;
case 3:
mapScan(2 * band, 3 * band);
break;
case 4:
mapScan(3 * band, 4 * band);
break;
case 5:
mapScan(4 * band, 5 * band);
break;
case 6:
mapScan(5 * band, 6 * band);
break;
case 7:
mapScan(6 * band, 7 * band);
break;
case 8:
mapScan(7 * band, getWidth());
break;
case 9:
if (cityTime % CENSUSRATE == 0) {
takeCensus();
if (cityTime % (CENSUSRATE*12) == 0) {
takeCensus2();
}
fireCensusChanged();
}
collectTaxPartial();
if (cityTime % TAXFREQ == 0) {
collectTax();
evaluation.cityEvaluation();
}
break;
case 10:
if (scycle % 5 == 0) { // every ~10 weeks
decROGMem();
}
decTrafficMem();
fireMapOverlayDataChanged(MapState.TRAFFIC_OVERLAY); //TDMAP
fireMapOverlayDataChanged(MapState.TRANSPORT); //RDMAP
fireMapOverlayDataChanged(MapState.ALL); //ALMAP
fireMapOverlayDataChanged(MapState.RESIDENTIAL); //REMAP
fireMapOverlayDataChanged(MapState.COMMERCIAL); //COMAP
fireMapOverlayDataChanged(MapState.INDUSTRIAL); //INMAP
doMessages();
break;
case 11:
powerScan();
fireMapOverlayDataChanged(MapState.POWER_OVERLAY);
newPower = true;
break;
case 12:
ptlScan();
break;
case 13:
crimeScan();
break;
case 14:
popDenScan();
break;
case 15:
fireAnalysis();
doDisasters();
break;
default:
throw new Error("unreachable");
}
}
private int computePopDen(int x, int y, char tile)
{
if (tile == FREEZ)
return doFreePop(x, y);
if (tile < COMBASE)
return residentialZonePop(tile);
if (tile < INDBASE)
return commercialZonePop(tile) * 8;
if (tile < PORTBASE)
return industrialZonePop(tile) * 8;
return 0;
}
private static int [][] doSmooth(int [][] tem)
{
final int h = tem.length;
final int w = tem[0].length;
int [][] tem2 = new int[h][w];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
int z = tem[y][x];
if (x > 0)
z += tem[y][x-1];
if (x + 1 < w)
z += tem[y][x+1];
if (y > 0)
z += tem[y-1][x];
if (y + 1 < h)
z += tem[y+1][x];
z /= 4;
if (z > 255)
z = 255;
tem2[y][x] = z;
}
}
return tem2;
}
public void calculateCenterMass()
{
popDenScan();
}
private void popDenScan()
{
int xtot = 0;
int ytot = 0;
int zoneCount = 0;
int width = getWidth();
int height = getHeight();
int [][] tem = new int[(height+1)/2][(width+1)/2];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
char tile = map[y][x];
if (isZoneCenter(tile))
{
tile &= LOMASK;
int den = computePopDen(x, y, (char)tile) * 8;
if (den > 254)
den = 254;
tem[y/2][x/2] = den;
xtot += x;
ytot += y;
zoneCount++;
}
}
}
tem = doSmooth(tem);
tem = doSmooth(tem);
tem = doSmooth(tem);
for (int x = 0; x < (width+1)/2; x++)
{
for (int y = 0; y < (height+1)/2; y++)
{
popDensity[y][x] = 2 * tem[y][x];
}
}
distIntMarket(); //set ComRate
// find center of mass for city
if (zoneCount != 0)
{
centerMassX = xtot / zoneCount;
centerMassY = ytot / zoneCount;
}
else
{
centerMassX = (width+1)/2;
centerMassY = (height+1)/2;
}
fireMapOverlayDataChanged(MapState.POPDEN_OVERLAY); //PDMAP
fireMapOverlayDataChanged(MapState.GROWTHRATE_OVERLAY); //RGMAP
}
private void distIntMarket()
{
for (int y = 0; y < comRate.length; y++)
{
for (int x = 0; x < comRate[y].length; x++)
{
int z = getDisCC(x*4, y*4);
z /= 4;
z = 64 - z;
comRate[y][x] = z;
}
}
}
//tends to empty RateOGMem[][]
private void decROGMem()
{
for (int y = 0; y < rateOGMem.length; y++)
{
for (int x = 0; x < rateOGMem[y].length; x++)
{
int z = rateOGMem[y][x];
if (z == 0)
continue;
if (z > 0)
{
rateOGMem[y][x]--;
if (z > 200)
{
rateOGMem[y][x] = 200; //prevent overflow?
}
continue;
}
if (z < 0)
{
rateOGMem[y][x]++;
if (z < -200)
{
rateOGMem[y][x] = -200;
}
continue;
}
}
}
}
//tends to empty trfDensity
private void decTrafficMem()
{
for (int y = 0; y < trfDensity.length; y++)
{
for (int x = 0; x < trfDensity[y].length; x++)
{
int z = trfDensity[y][x];
if (z != 0)
{
if (z > 200)
trfDensity[y][x] = z - 34;
else if (z > 24)
trfDensity[y][x] = z - 24;
else
trfDensity[y][x] = 0;
}
}
}
}
void crimeScan()
{
policeMap = smoothFirePoliceMap(policeMap);
policeMap = smoothFirePoliceMap(policeMap);
policeMap = smoothFirePoliceMap(policeMap);
for (int sy = 0; sy < policeMap.length; sy++) {
for (int sx = 0; sx < policeMap[sy].length; sx++) {
policeMapEffect[sy][sx] = policeMap[sy][sx];
}
}
int count = 0;
int sum = 0;
int cmax = 0;
for (int hy = 0; hy < landValueMem.length; hy++) {
for (int hx = 0; hx < landValueMem[hy].length; hx++) {
int val = landValueMem[hy][hx];
if (val != 0) {
count++;
int z = 128 - val + popDensity[hy][hx];
z = Math.min(300, z);
z -= policeMap[hy/4][hx/4];
z = Math.min(250, z);
z = Math.max(0, z);
crimeMem[hy][hx] = z;
sum += z;
if (z > cmax || (z == cmax && PRNG.nextInt(4) == 0)) {
cmax = z;
crimeMaxLocationX = hx*2;
crimeMaxLocationY = hy*2;
}
}
else {
crimeMem[hy][hx] = 0;
}
}
}
if (count != 0)
crimeAverage = sum / count;
else
crimeAverage = 0;
fireMapOverlayDataChanged(MapState.POLICE_OVERLAY);
}
void doDisasters()
{
if (floodCnt > 0) {
floodCnt--;
}
final int [] DisChance = { 480, 240, 60 };
if (noDisasters)
return;
if (PRNG.nextInt(DisChance[gameLevel]+1) != 0)
return;
switch (PRNG.nextInt(9))
{
case 0:
case 1:
setFire();
break;
case 2:
case 3:
makeFlood();
break;
case 4:
break;
case 5:
makeTornado();
break;
case 6:
makeEarthquake();
break;
case 7:
case 8:
if (pollutionAverage > 60) {
makeMonster();
}
break;
}
}
private int[][] smoothFirePoliceMap(int[][] omap)
{
int smX = omap[0].length;
int smY = omap.length;
int[][] nmap = new int[smY][smX];
for (int sy = 0; sy < smY; sy++) {
for (int sx = 0; sx < smX; sx++) {
int edge = 0;
if (sx > 0) { edge += omap[sy][sx-1]; }
if (sx + 1 < smX) { edge += omap[sy][sx+1]; }
if (sy > 0) { edge += omap[sy-1][sx]; }
if (sy + 1 < smY) { edge += omap[sy+1][sx]; }
edge = edge / 4 + omap[sy][sx];
nmap[sy][sx] = edge / 2;
}
}
return nmap;
}
void fireAnalysis()
{
fireStMap = smoothFirePoliceMap(fireStMap);
fireStMap = smoothFirePoliceMap(fireStMap);
fireStMap = smoothFirePoliceMap(fireStMap);
for (int sy = 0; sy < fireStMap.length; sy++) {
for (int sx = 0; sx < fireStMap[sy].length; sx++) {
fireRate[sy][sx] = fireStMap[sy][sx];
}
}
fireMapOverlayDataChanged(MapState.FIRE_OVERLAY);
}
private boolean testForCond(CityLocation loc, int dir)
{
int xsave = loc.x;
int ysave = loc.y;
boolean rv = false;
if (movePowerLocation(loc,dir))
{
rv = (
isConductive(map[loc.y][loc.x]) &&
map[loc.y][loc.x] != NUCLEAR &&
map[loc.y][loc.x] != POWERPLANT &&
!hasPower(loc.x, loc.y)
);
}
loc.x = xsave;
loc.y = ysave;
return rv;
}
private boolean movePowerLocation(CityLocation loc, int dir)
{
switch(dir)
{
case 0:
if (loc.y > 0)
{
loc.y--;
return true;
}
else
return false;
case 1:
if (loc.x + 1 < getWidth())
{
loc.x++;
return true;
}
else
return false;
case 2:
if (loc.y + 1 < getHeight())
{
loc.y++;
return true;
}
else
return false;
case 3:
if (loc.x > 0)
{
loc.x--;
return true;
}
else
return false;
case 4:
return true;
}
return false;
}
void powerScan()
{
// clear powerMap
for (boolean [] bb : powerMap)
{
Arrays.fill(bb, false);
}
//
// Note: brownouts are based on total number of power plants, not the number
// of powerplants connected to your city.
//
int maxPower = coalCount * 700 + nuclearCount * 2000;
int numPower = 0;
// This is kind of odd algorithm, but I haven't the heart to rewrite it at
// this time.
while (!powerPlants.isEmpty())
{
CityLocation loc = powerPlants.pop();
int aDir = 4;
int conNum;
do
{
if (++numPower > maxPower)
{
// trigger notification
sendMessage(MicropolisMessage.BROWNOUTS_REPORT);
return;
}
movePowerLocation(loc, aDir);
powerMap[loc.y][loc.x] = true;
conNum = 0;
int dir = 0;
while (dir < 4 && conNum < 2)
{
if (testForCond(loc, dir))
{
conNum++;
aDir = dir;
}
else
{
}
dir++;
}
if (conNum > 1)
{
powerPlants.add(new CityLocation(loc.x,loc.y));
}
}
while (conNum != 0);
}
}
public int getTrafficDensity(int xpos, int ypos)
{
if (testBounds(xpos, ypos)) {
return trfDensity[ypos/2][xpos/2];
} else {
return 0;
}
}
//power, terrain, land value
void ptlScan()
{
final int qX = (getWidth()+3)/4;
final int qY = (getHeight()+3)/4;
int [][] qtem = new int[qY][qX];
int landValueTotal = 0;
int landValueCount = 0;
final int HWLDX = (getWidth()+1)/2;
final int HWLDY = (getHeight()+1)/2;
int [][] tem = new int[HWLDY][HWLDX];
for (int x = 0; x < HWLDX; x++)
{
for (int y = 0; y < HWLDY; y++)
{
int plevel = 0;
int lvflag = 0;
int zx = 2*x;
int zy = 2*y;
for (int mx = zx; mx <= zx+1; mx++)
{
for (int my = zy; my <= zy+1; my++)
{
int tile = (map[my][mx] & LOMASK);
if (tile != DIRT)
{
if (tile < RUBBLE) //natural land features
{
//inc terrainMem
qtem[y/2][x/2] += 15;
continue;
}
plevel += getPollutionValue(tile);
if (isConstructed(tile))
lvflag++;
}
}
}
if (plevel < 0)
plevel = 250; //?
if (plevel > 255)
plevel = 255;
tem[y][x] = plevel;
if (lvflag != 0)
{
//land value equation
int dis = 34 - getDisCC(x, y);
dis *= 4;
dis += terrainMem[y/2][x/2];
dis -= pollutionMem[y][x];
if (crimeMem[y][x] > 190) {
dis -= 20;
}
if (dis > 250)
dis = 250;
if (dis < 1)
dis = 1;
landValueMem[y][x] = dis;
landValueTotal += dis;
landValueCount++;
}
else
{
landValueMem[y][x] = 0;
}
}
}
landValueAverage = landValueCount != 0 ? (landValueTotal/landValueCount) : 0;
tem = doSmooth(tem);
tem = doSmooth(tem);
int pcount = 0;
int ptotal = 0;
int pmax = 0;
for (int x = 0; x < HWLDX; x++)
{
for (int y = 0; y < HWLDY; y++)
{
int z = tem[y][x];
pollutionMem[y][x] = z;
if (z != 0)
{
pcount++;
ptotal += z;
if (z > pmax ||
(z == pmax && PRNG.nextInt(4) == 0))
{
pmax = z;
pollutionMaxLocationX = 2*x;
pollutionMaxLocationY = 2*y;
}
}
}
}
pollutionAverage = pcount != 0 ? (ptotal / pcount) : 0;
terrainMem = smoothTerrain(qtem);
fireMapOverlayDataChanged(MapState.POLLUTE_OVERLAY); //PLMAP
fireMapOverlayDataChanged(MapState.LANDVALUE_OVERLAY); //LVMAP
}
public CityLocation getLocationOfMaxPollution()
{
return new CityLocation(pollutionMaxLocationX, pollutionMaxLocationY);
}
static final int [] TaxTable = {
200, 150, 120, 100, 80, 50, 30, 0, -10, -40, -100,
-150, -200, -250, -300, -350, -400, -450, -500, -550, -600 };
public static class History
{
public int cityTime;
public int [] res = new int[240];
public int [] com = new int[240];
public int [] ind = new int[240];
public int [] money = new int[240];
public int [] pollution = new int[240];
public int [] crime = new int[240];
int resMax;
int comMax;
int indMax;
}
public History history = new History();
void setValves()
{
double normResPop = (double)resPop / 8.0;
totalPop = (int) (normResPop + comPop + indPop);
double employment;
if (normResPop != 0.0)
{
employment = (history.com[1] + history.ind[1]) / normResPop;
}
else
{
employment = 1;
}
double migration = normResPop * (employment - 1);
final double BIRTH_RATE = 0.02;
double births = (double)normResPop * BIRTH_RATE;
double projectedResPop = normResPop + migration + births;
double temp = (history.com[1] + history.ind[1]);
double laborBase;
if (temp != 0.0)
{
laborBase = history.res[1] / temp;
}
else
{
laborBase = 1;
}
// clamp laborBase to between 0.0 and 1.3
laborBase = Math.max(0.0, Math.min(1.3, laborBase));
double internalMarket = (double)(normResPop + comPop + indPop) / 3.7;
double projectedComPop = internalMarket * laborBase;
int z = gameLevel;
temp = 1.0;
switch (z)
{
case 0: temp = 1.2; break;
case 1: temp = 1.1; break;
case 2: temp = 0.98; break;
}
double projectedIndPop = indPop * laborBase * temp;
if (projectedIndPop < 5.0)
projectedIndPop = 5.0;
double resRatio;
if (normResPop != 0)
{
resRatio = (double)projectedResPop / (double)normResPop;
}
else
{
resRatio = 1.3;
}
double comRatio;
if (comPop != 0)
comRatio = (double)projectedComPop / (double)comPop;
else
comRatio = projectedComPop;
double indRatio;
if (indPop != 0)
indRatio = (double)projectedIndPop / (double)indPop;
else
indRatio = projectedIndPop;
if (resRatio > 2.0)
resRatio = 2.0;
if (comRatio > 2.0)
comRatio = 2.0;
if (indRatio > 2.0)
indRatio = 2.0;
int z2 = taxEffect + gameLevel;
if (z2 > 20)
z2 = 20;
- resRatio = (resRatio - 1) * 600 + TaxTable[z];
- comRatio = (comRatio - 1) * 600 + TaxTable[z];
- indRatio = (indRatio - 1) * 600 + TaxTable[z];
+ resRatio = (resRatio - 1) * 600 + TaxTable[z2];
+ comRatio = (comRatio - 1) * 600 + TaxTable[z2];
+ indRatio = (indRatio - 1) * 600 + TaxTable[z2];
// ratios are velocity changes to valves
resValve += (int) resRatio;
comValve += (int) comRatio;
indValve += (int) indRatio;
if (resValve > 2000)
resValve = 2000;
else if (resValve < -2000)
resValve = -2000;
if (comValve > 1500)
comValve = 1500;
else if (comValve < -1500)
comValve = -1500;
if (indValve > 1500)
indValve = 1500;
else if (indValve < -1500)
indValve = -1500;
if (resCap && resValve > 0) {
// residents demand stadium
resValve = 0;
}
if (comCap && comValve > 0) {
// commerce demands airport
comValve = 0;
}
if (indCap && indValve > 0) {
// industry demands sea port
indValve = 0;
}
fireDemandChanged();
}
int [][] smoothTerrain(int [][] qtem)
{
final int QWX = qtem[0].length;
final int QWY = qtem.length;
int [][] mem = new int[QWY][QWX];
for (int y = 0; y < QWY; y++)
{
for (int x = 0; x < QWX; x++)
{
int z = 0;
if (x > 0)
z += qtem[y][x-1];
if (x+1 < QWX)
z += qtem[y][x+1];
if (y > 0)
z += qtem[y-1][x];
if (y+1 < QWY)
z += qtem[y+1][x];
mem[y][x] = z / 4 + qtem[y][x] / 2;
}
}
return mem;
}
// calculate manhatten distance (in 2-units) from center of city
// capped at 32
int getDisCC(int x, int y)
{
assert x >= 0 && x <= getWidth()/2;
assert y >= 0 && y <= getHeight()/2;
int xdis = Math.abs(x - centerMassX/2);
int ydis = Math.abs(y - centerMassY/2);
int z = (xdis + ydis);
if (z > 32)
return 32;
else
return z;
}
void mapScan(int x0, int x1)
{
MapScanner scanner = new MapScanner(this);
for (int x = x0; x < x1; x++)
{
scanner.xpos = x;
for (int y = 0; y < getHeight(); y++)
{
scanner.ypos = y;
scanner.cchr = map[y][x];
scanner.scanTile();
}
}
}
void generateShip()
{
int edge = PRNG.nextInt(4);
if (edge == 0) {
for (int x = 4; x < getWidth() - 2; x++) {
if (getTile(x,0) == CHANNEL) {
makeShipAt(x, 0, ShipSprite.NORTH_EDGE);
return;
}
}
}
else if (edge == 1) {
for (int y = 1; y < getHeight() - 2; y++) {
if (getTile(0,y) == CHANNEL) {
makeShipAt(0, y, ShipSprite.EAST_EDGE);
return;
}
}
}
else if (edge == 2) {
for (int x = 4; x < getWidth() - 2; x++) {
if (getTile(x, getHeight()-1) == CHANNEL) {
makeShipAt(x, getHeight()-1, ShipSprite.SOUTH_EDGE);
return;
}
}
}
else {
for (int y = 1; y < getHeight() - 2; y++) {
if (getTile(getWidth()-1, y) == CHANNEL) {
makeShipAt(getWidth()-1, y, ShipSprite.EAST_EDGE);
return;
}
}
}
}
Sprite getSprite(SpriteKind kind)
{
for (Sprite s : sprites) {
if (s.kind == kind)
return s;
}
return null;
}
boolean hasSprite(SpriteKind kind)
{
return getSprite(kind) != null;
}
void makeShipAt(int xpos, int ypos, int edge)
{
assert !hasSprite(SpriteKind.SHI);
sprites.add(new ShipSprite(this, xpos, ypos, edge));
}
void generateCopter(int xpos, int ypos)
{
if (!hasSprite(SpriteKind.COP)) {
sprites.add(new HelicopterSprite(this, xpos, ypos));
}
}
void generatePlane(int xpos, int ypos)
{
if (!hasSprite(SpriteKind.AIR)) {
sprites.add(new AirplaneSprite(this, xpos, ypos));
}
}
void generateTrain(int xpos, int ypos)
{
if (totalPop > 20 &&
!hasSprite(SpriteKind.TRA) &&
PRNG.nextInt(26) == 0)
{
sprites.add(new TrainSprite(this, xpos, ypos));
}
}
Stack<CityLocation> powerPlants = new Stack<CityLocation>();
// counts the population in a certain type of residential zone
int doFreePop(int xpos, int ypos)
{
int count = 0;
for (int x = xpos - 1; x <= xpos + 1; x++)
{
for (int y = ypos - 1; y <= ypos + 1; y++)
{
if (testBounds(x,y))
{
char loc = (char) (map[y][x] & LOMASK);
if (loc >= LHTHR && loc <= HHTHR)
count++;
}
}
}
return count;
}
// called every several cycles; this takes the census data collected in this
// cycle and records it to the history
//
void takeCensus()
{
int resMax = 0;
int comMax = 0;
int indMax = 0;
for (int i = 118; i >= 0; i--)
{
if (history.res[i] > resMax)
resMax = history.res[i];
if (history.com[i] > comMax)
comMax = history.res[i];
if (history.ind[i] > indMax)
indMax = history.ind[i];
history.res[i + 1] = history.res[i];
history.com[i + 1] = history.com[i];
history.ind[i + 1] = history.ind[i];
history.crime[i + 1] = history.crime[i];
history.pollution[i + 1] = history.pollution[i];
history.money[i + 1] = history.money[i];
}
history.resMax = resMax;
history.comMax = comMax;
history.indMax = indMax;
//graph10max = Math.max(resMax, Math.max(comMax, indMax));
history.res[0] = resPop / 8;
history.com[0] = comPop;
history.ind[0] = indPop;
crimeRamp += (crimeAverage - crimeRamp) / 4;
history.crime[0] = Math.min(255, crimeRamp);
polluteRamp += (pollutionAverage - polluteRamp) / 4;
history.pollution[0] = Math.min(255, polluteRamp);
int moneyScaled = cashFlow / 20 + 128;
if (moneyScaled < 0)
moneyScaled = 0;
if (moneyScaled > 255)
moneyScaled = 255;
history.money[0] = moneyScaled;
history.cityTime = cityTime;
if (hospitalCount < resPop / 256)
{
needHospital = 1;
}
else if (hospitalCount > resPop / 256)
{
needHospital = -1;
}
else
{
needHospital = 0;
}
if (churchCount < resPop / 256)
{
needChurch = 1;
}
else if (churchCount > resPop / 256)
{
needChurch = -1;
}
else
{
needChurch = 0;
}
}
void takeCensus2()
{
// update long term graphs
int resMax = 0;
int comMax = 0;
int indMax = 0;
for (int i = 238; i >= 120; i--)
{
if (history.res[i] > resMax)
resMax = history.res[i];
if (history.com[i] > comMax)
comMax = history.res[i];
if (history.ind[i] > indMax)
indMax = history.ind[i];
history.res[i + 1] = history.res[i];
history.com[i + 1] = history.com[i];
history.ind[i + 1] = history.ind[i];
history.crime[i + 1] = history.crime[i];
history.pollution[i + 1] = history.pollution[i];
history.money[i + 1] = history.money[i];
}
history.res[120] = resPop / 8;
history.com[120] = comPop;
history.ind[120] = indPop;
history.crime[120] = history.crime[0];
history.pollution[120] = history.pollution[0];
history.money[120] = history.money[0];
}
/** Road/rail maintenance cost multiplier, for various difficulty settings.
*/
static final double [] RLevels = { 0.7, 0.9, 1.2 };
/** Tax income multiplier, for various difficulty settings.
*/
static final double [] FLevels = { 1.4, 1.2, 0.8 };
void collectTaxPartial()
{
lastRoadTotal = roadTotal;
lastRailTotal = railTotal;
lastTotalPop = totalPop;
lastFireStationCount = fireStationCount;
lastPoliceCount = policeCount;
BudgetNumbers b = generateBudget();
budget.taxFund += b.taxIncome;
budget.roadFundEscrow -= b.roadFunded;
budget.fireFundEscrow -= b.fireFunded;
budget.policeFundEscrow -= b.policeFunded;
taxEffect = b.taxRate;
roadEffect = b.roadRequest != 0 ?
(int)Math.floor(32.0 * (double)b.roadFunded / (double)b.roadRequest) :
32;
policeEffect = b.policeRequest != 0 ?
(int)Math.floor(1000.0 * (double)b.policeFunded / (double)b.policeRequest) :
1000;
fireEffect = b.fireRequest != 0 ?
(int)Math.floor(1000.0 * (double)b.fireFunded / (double)b.fireRequest) :
1000;
}
public static class FinancialHistory
{
public int cityTime;
public int totalFunds;
public int taxIncome;
public int operatingExpenses;
}
public ArrayList<FinancialHistory> financialHistory = new ArrayList<FinancialHistory>();
void collectTax()
{
int revenue = budget.taxFund / TAXFREQ;
int expenses = -(budget.roadFundEscrow + budget.fireFundEscrow + budget.policeFundEscrow) / TAXFREQ;
FinancialHistory hist = new FinancialHistory();
hist.cityTime = cityTime;
hist.taxIncome = revenue;
hist.operatingExpenses = expenses;
cashFlow = revenue - expenses;
spend(-cashFlow);
hist.totalFunds = budget.totalFunds;
financialHistory.add(0,hist);
budget.taxFund = 0;
budget.roadFundEscrow = 0;
budget.fireFundEscrow = 0;
budget.policeFundEscrow = 0;
}
/** Annual maintenance cost of each police station. */
static final int POLICE_STATION_MAINTENANCE = 100;
/** Annual maintenance cost of each fire station. */
static final int FIRE_STATION_MAINTENANCE = 100;
/**
* Calculate the current budget numbers.
*/
public BudgetNumbers generateBudget()
{
BudgetNumbers b = new BudgetNumbers();
b.taxRate = Math.max(0, cityTax);
b.roadPercent = Math.max(0.0, roadPercent);
b.firePercent = Math.max(0.0, firePercent);
b.policePercent = Math.max(0.0, policePercent);
b.previousBalance = budget.totalFunds;
b.taxIncome = (int)Math.round(lastTotalPop * landValueAverage / 120 * b.taxRate * FLevels[gameLevel]);
assert b.taxIncome >= 0;
b.roadRequest = (int)Math.round((lastRoadTotal + lastRailTotal * 2) * RLevels[gameLevel]);
b.fireRequest = FIRE_STATION_MAINTENANCE * lastFireStationCount;
b.policeRequest = POLICE_STATION_MAINTENANCE * lastPoliceCount;
b.roadFunded = (int)Math.round(b.roadRequest * b.roadPercent);
b.fireFunded = (int)Math.round(b.fireRequest * b.firePercent);
b.policeFunded = (int)Math.round(b.policeRequest * b.policePercent);
int yumDuckets = budget.totalFunds + b.taxIncome;
assert yumDuckets >= 0;
if (yumDuckets >= b.roadFunded)
{
yumDuckets -= b.roadFunded;
if (yumDuckets >= b.fireFunded)
{
yumDuckets -= b.fireFunded;
if (yumDuckets >= b.policeFunded)
{
yumDuckets -= b.policeFunded;
}
else
{
assert b.policeRequest != 0;
b.policeFunded = yumDuckets;
b.policePercent = (double)b.policeFunded / (double)b.policeRequest;
yumDuckets = 0;
}
}
else
{
assert b.fireRequest != 0;
b.fireFunded = yumDuckets;
b.firePercent = (double)b.fireFunded / (double)b.fireRequest;
b.policeFunded = 0;
b.policePercent = 0.0;
yumDuckets = 0;
}
}
else
{
assert b.roadRequest != 0;
b.roadFunded = yumDuckets;
b.roadPercent = (double)b.roadFunded / (double)b.roadRequest;
b.fireFunded = 0;
b.firePercent = 0.0;
b.policeFunded = 0;
b.policePercent = 0.0;
}
b.operatingExpenses = b.roadFunded + b.fireFunded + b.policeFunded;
b.newBalance = b.previousBalance + b.taxIncome - b.operatingExpenses;
return b;
}
/**
* The three main types of zones found in Micropolis.
*/
static enum ZoneType
{
RESIDENTIAL, COMMERCIAL, INDUSTRIAL;
}
TrafficGen traffic = new TrafficGen(this);
/**
* @return 1 if traffic "passed", 0 if traffic "failed", -1 if no roads found
*/
int makeTraffic(int xpos, int ypos, ZoneType zoneType)
{
traffic.mapX = xpos;
traffic.mapY = ypos;
traffic.sourceZone = zoneType;
return traffic.makeTraffic();
}
int getPopulationDensity(int xpos, int ypos)
{
return popDensity[ypos/2][xpos/2];
}
void doMeltdown(int xpos, int ypos)
{
meltdownLocation = new CityLocation(xpos, ypos);
makeExplosion(xpos - 1, ypos - 1);
makeExplosion(xpos - 1, ypos + 2);
makeExplosion(xpos + 2, ypos - 1);
makeExplosion(xpos + 2, ypos + 2);
for (int x = xpos - 1; x < xpos + 3; x++) {
for (int y = ypos - 1; y < ypos + 3; y++) {
setTile(x, y, (char)(FIRE + PRNG.nextInt(4)));
}
}
for (int z = 0; z < 200; z++) {
int x = xpos - 20 + PRNG.nextInt(41);
int y = ypos - 15 + PRNG.nextInt(31);
if (!testBounds(x,y))
continue;
int t = map[y][x];
if (isZoneCenter(t)) {
continue;
}
if (isCombustible(t) || t == DIRT) {
setTile(x, y, RADTILE);
}
}
clearMes();
sendMessageAtPic(MicropolisMessage.MELTDOWN_REPORT, xpos, ypos);
}
static final int [] MltdwnTab = { 30000, 20000, 10000 };
void loadHistoryArray(int [] array, DataInputStream dis)
throws IOException
{
for (int i = 0; i < 240; i++)
{
array[i] = dis.readShort();
}
}
void writeHistoryArray(int [] array, DataOutputStream out)
throws IOException
{
for (int i = 0; i < 240; i++)
{
out.writeShort(array[i]);
}
}
void loadMisc(DataInputStream dis)
throws IOException
{
dis.readShort(); //[0]... ignored?
dis.readShort(); //[1] externalMarket, ignored
resPop = dis.readShort(); //[2-4] populations
comPop = dis.readShort();
indPop = dis.readShort();
resValve = dis.readShort(); //[5-7] valves
comValve = dis.readShort();
indValve = dis.readShort();
cityTime = dis.readInt(); //[8-9] city time
crimeRamp = dis.readShort(); //[10]
polluteRamp = dis.readShort();
landValueAverage = dis.readShort(); //[12]
crimeAverage = dis.readShort();
pollutionAverage = dis.readShort(); //[14]
gameLevel = dis.readShort();
evaluation.cityClass = dis.readShort(); //[16]
evaluation.cityScore = dis.readShort();
for (int i = 18; i < 50; i++)
{
dis.readShort();
}
budget.totalFunds = dis.readInt(); //[50-51] total funds
autoBulldoze = dis.readShort() != 0; //52
autoBudget = dis.readShort() != 0;
autoGo = dis.readShort() != 0; //54
dis.readShort(); // userSoundOn (this setting not saved to game file
// in this edition of the game)
cityTax = dis.readShort(); //56
taxEffect = cityTax;
int simSpeedAsInt = dis.readShort();
if (simSpeedAsInt >= 0 && simSpeedAsInt <= 4)
simSpeed = Speed.values()[simSpeedAsInt];
else
simSpeed = Speed.NORMAL;
// read budget numbers, convert them to percentages
//
long n = dis.readInt(); //58,59... police percent
policePercent = (double)n / 65536.0;
n = dis.readInt(); //60,61... fire percent
firePercent = (double)n / 65536.0;
n = dis.readInt(); //62,63... road percent
roadPercent = (double)n / 65536.0;
for (int i = 64; i < 120; i++)
{
dis.readShort();
}
if (cityTime < 0) { cityTime = 0; }
if (cityTax < 0 || cityTax > 20) { cityTax = 7; }
if (gameLevel < 0 || gameLevel > 2) { gameLevel = 0; }
if (evaluation.cityClass < 0 || evaluation.cityClass > 5) { evaluation.cityClass = 0; }
if (evaluation.cityScore < 1 || evaluation.cityScore > 999) { evaluation.cityScore = 500; }
resCap = false;
comCap = false;
indCap = false;
}
void writeMisc(DataOutputStream out)
throws IOException
{
out.writeShort(0);
out.writeShort(0);
out.writeShort(resPop);
out.writeShort(comPop);
out.writeShort(indPop);
out.writeShort(resValve);
out.writeShort(comValve);
out.writeShort(indValve);
//8
out.writeInt(cityTime);
out.writeShort(crimeRamp);
out.writeShort(polluteRamp);
//12
out.writeShort(landValueAverage);
out.writeShort(crimeAverage);
out.writeShort(pollutionAverage);
out.writeShort(gameLevel);
//16
out.writeShort(evaluation.cityClass);
out.writeShort(evaluation.cityScore);
//18
for (int i = 18; i < 50; i++) {
out.writeShort(0);
}
//50
out.writeInt(budget.totalFunds);
out.writeShort(autoBulldoze ? 1 : 0);
out.writeShort(autoBudget ? 1 : 0);
//54
out.writeShort(autoGo ? 1 : 0);
out.writeShort(1); //userSoundOn
out.writeShort(cityTax);
out.writeShort(simSpeed.ordinal());
//58
out.writeInt((int)(policePercent * 65536));
out.writeInt((int)(firePercent * 65536));
out.writeInt((int)(roadPercent * 65536));
//64
for (int i = 64; i < 120; i++) {
out.writeShort(0);
}
}
void loadMap(DataInputStream dis)
throws IOException
{
for (int x = 0; x < DEFAULT_WIDTH; x++)
{
for (int y = 0; y < DEFAULT_HEIGHT; y++)
{
int z = dis.readShort();
z &= ~(1024 | 2048 | 8192 | 16384); // clear ZONEBIT,ANIMBIT,BURNBIT,CONDBIT on import
map[y][x] = (char) z;
}
}
}
void writeMap(DataOutputStream out)
throws IOException
{
for (int x = 0; x < DEFAULT_WIDTH; x++)
{
for (int y = 0; y < DEFAULT_HEIGHT; y++)
{
int z = map[y][x];
if (isConductive(z)) {
z |= 16384; //synthesize CONDBIT on export
}
if (isCombustible(z)) {
z |= 8192; //synthesize BURNBIT on export
}
if (isAnimated(z)) {
z |= 2048; //synthesize ANIMBIT on export
}
if (isZoneCenter(z)) {
z |= 1024; //synthesize ZONEBIT
}
out.writeShort(z);
}
}
}
public void load(File filename)
throws IOException
{
FileInputStream fis = new FileInputStream(filename);
if (fis.getChannel().size() > 27120) {
// some editions of the classic Simcity game
// start the file off with a 128-byte header,
// but otherwise use the same format as us,
// so read in that 128-byte header and continue
// as before.
byte [] bbHeader = new byte[128];
fis.read(bbHeader);
}
load(fis);
}
void checkPowerMap()
{
coalCount = 0;
nuclearCount = 0;
powerPlants.clear();
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
int tile = getTile(x,y);
if ((tile & LOMASK) == NUCLEAR) {
nuclearCount++;
powerPlants.add(new CityLocation(x,y));
}
else if ((tile & LOMASK) == POWERPLANT) {
coalCount++;
powerPlants.add(new CityLocation(x,y));
}
}
}
powerScan();
newPower = true;
assert powerPlants.isEmpty();
}
public void load(InputStream inStream)
throws IOException
{
DataInputStream dis = new DataInputStream(inStream);
loadHistoryArray(history.res, dis);
loadHistoryArray(history.com, dis);
loadHistoryArray(history.ind, dis);
loadHistoryArray(history.crime, dis);
loadHistoryArray(history.pollution, dis);
loadHistoryArray(history.money, dis);
loadMisc(dis);
loadMap(dis);
dis.close();
checkPowerMap();
fireWholeMapChanged();
fireDemandChanged();
fireFundsChanged();
}
public void save(File filename)
throws IOException
{
save(new FileOutputStream(filename));
}
public void save(OutputStream outStream)
throws IOException
{
DataOutputStream out = new DataOutputStream(outStream);
writeHistoryArray(history.res, out);
writeHistoryArray(history.com, out);
writeHistoryArray(history.ind, out);
writeHistoryArray(history.crime, out);
writeHistoryArray(history.pollution, out);
writeHistoryArray(history.money, out);
writeMisc(out);
writeMap(out);
out.close();
}
public void toggleAutoBudget()
{
autoBudget = !autoBudget;
fireOptionsChanged();
}
public void toggleAutoBulldoze()
{
autoBulldoze = !autoBulldoze;
fireOptionsChanged();
}
public void toggleDisasters()
{
noDisasters = !noDisasters;
fireOptionsChanged();
}
public void setSpeed(Speed newSpeed)
{
simSpeed = newSpeed;
fireOptionsChanged();
}
public void animate()
{
this.acycle = (this.acycle+1) % 960;
if (this.acycle % 2 == 0) {
step();
}
moveObjects();
animateTiles();
}
public Sprite [] allSprites()
{
return sprites.toArray(new Sprite[0]);
}
void moveObjects()
{
for (Sprite sprite : allSprites())
{
sprite.move();
if (sprite.frame == 0) {
sprites.remove(sprite);
}
}
}
void animateTiles()
{
for (int y = 0; y < map.length; y++)
{
for (int x = 0; x < map[y].length; x++)
{
char tilevalue = map[y][x];
TileSpec spec = Tiles.get(tilevalue & LOMASK);
if (spec != null && spec.animNext != null) {
int flags = tilevalue & ALLBITS;
setTile(x, y, (char)
(spec.animNext.tileNumber | flags)
);
}
}
}
}
public int getCityPopulation()
{
return lastCityPop;
}
void makeSound(int x, int y, Sound sound)
{
fireCitySound(sound, new CityLocation(x,y));
}
public void makeEarthquake()
{
makeSound(centerMassX, centerMassY, Sound.EXPLOSION_LOW);
fireEarthquakeStarted();
sendMessageAtPic(MicropolisMessage.EARTHQUAKE_REPORT, centerMassX, centerMassY);
int time = PRNG.nextInt(701) + 300;
for (int z = 0; z < time; z++) {
int x = PRNG.nextInt(getWidth());
int y = PRNG.nextInt(getHeight());
assert testBounds(x, y);
if (TileConstants.isVulnerable(getTile(x, y))) {
if (PRNG.nextInt(4) != 0) {
setTile(x, y, (char)(RUBBLE + BULLBIT + PRNG.nextInt(4)));
} else {
setTile(x, y, (char)(FIRE + PRNG.nextInt(8)));
}
}
}
}
void setFire()
{
int x = PRNG.nextInt(getWidth());
int y = PRNG.nextInt(getHeight());
int t = getTile(x, y);
if (TileConstants.isArsonable(t)) {
setTile(x, y, (char)(FIRE + PRNG.nextInt(8)));
crashLocation = new CityLocation(x, y);
sendMessageAtPic(MicropolisMessage.FIRE_REPORT, x, y);
}
}
public void makeFire()
{
// forty attempts at finding place to start fire
for (int t = 0; t < 40; t++)
{
int x = PRNG.nextInt(getWidth());
int y = PRNG.nextInt(getHeight());
int tile = map[y][x];
if (!isZoneCenter(tile) && isCombustible(tile))
{
tile &= LOMASK;
if (tile > 21 && tile < LASTZONE) {
setTile(x, y, (char)(FIRE + PRNG.nextInt(8)));
sendMessageAt(MicropolisMessage.FIRE_REPORT, x, y);
return;
}
}
}
}
/**
* Force a meltdown to occur.
* @return true if a metldown was initiated.
*/
public boolean makeMeltdown()
{
ArrayList<CityLocation> candidates = new ArrayList<CityLocation>();
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
if ((map[y][x] & LOMASK) == NUCLEAR) {
candidates.add(new CityLocation(x,y));
}
}
}
if (candidates.isEmpty()) {
// tell caller that no nuclear plants were found
return false;
}
int i = PRNG.nextInt(candidates.size());
CityLocation p = candidates.get(i);
doMeltdown(p.x, p.y);
return true;
}
public void makeMonster()
{
MonsterSprite monster = (MonsterSprite) getSprite(SpriteKind.GOD);
if (monster != null) {
// already have a monster in town
monster.soundCount = 1;
monster.count = 1000;
monster.flag = false;
monster.destX = pollutionMaxLocationX;
monster.destY = pollutionMaxLocationY;
return;
}
// try to find a suitable starting spot for monster
for (int i = 0; i < 300; i++) {
int x = PRNG.nextInt(getWidth() - 19) + 10;
int y = PRNG.nextInt(getHeight() - 9) + 5;
int t = getTile(x, y);
if ((t & LOMASK) == RIVER) {
makeMonsterAt(x, y);
return;
}
}
// no "nice" location found, just start in center of map then
makeMonsterAt(getWidth()/2, getHeight()/2);
}
void makeMonsterAt(int xpos, int ypos)
{
assert !hasSprite(SpriteKind.GOD);
sprites.add(new MonsterSprite(this, xpos, ypos));
}
public void makeTornado()
{
TornadoSprite tornado = (TornadoSprite) getSprite(SpriteKind.TOR);
if (tornado != null) {
// already have a tornado, so extend the length of the
// existing tornado
tornado.count = 200;
return;
}
//FIXME- this is not exactly like the original code
int xpos = PRNG.nextInt(getWidth() - 19) + 10;
int ypos = PRNG.nextInt(getHeight() - 19) + 10;
sprites.add(new TornadoSprite(this, xpos, ypos));
sendMessageAtPic(MicropolisMessage.TORNADO_REPORT, xpos, ypos);
}
public void makeFlood()
{
final int [] DX = { 0, 1, 0, -1 };
final int [] DY = { -1, 0, 1, 0 };
for (int z = 0; z < 300; z++) {
int x = PRNG.nextInt(getWidth());
int y = PRNG.nextInt(getHeight());
int tile = map[y][x] & LOMASK;
if (isRiverEdge(tile))
{
for (int t = 0; t < 4; t++) {
int xx = x + DX[t];
int yy = y + DY[t];
if (testBounds(xx,yy)) {
int c = map[yy][xx];
if (isFloodable(c)) {
setTile(xx, yy, FLOOD);
floodCnt = 30;
sendMessageAtPic(MicropolisMessage.FLOOD_REPORT, xx, yy);
floodX = xx;
floodY = yy;
return;
}
}
}
}
}
}
/**
* Makes all component tiles of a zone bulldozable.
* Should be called whenever the key zone tile of a zone is destroyed,
* since otherwise the user would no longer have a way of destroying
* the zone.
* @see #shutdownZone
*/
void killZone(int xpos, int ypos, int zoneTile)
{
rateOGMem[ypos/8][xpos/8] -= 20;
int sz = TileConstants.getZoneSizeFor(zoneTile);
int zoneBase = (zoneTile&LOMASK)-1-sz;
// this will take care of stopping smoke animations
shutdownZone(xpos, ypos, sz);
for (int y = 0; y < sz; y++) {
for (int x = 0; x < sz; x++, zoneBase++) {
int xtem = xpos - 1 + x;
int ytem = ypos - 1 + y;
if (!testBounds(xtem, ytem))
continue;
int t = getTile(xtem, ytem);
if (isConstructed(t)) {
setTile(xtem, ytem, (char)(t | BULLBIT));
}
}
}
}
/**
* If a zone has a different image (animation) for when it is
* powered, switch to that different image here.
* Note: pollution is not accumulated here; see ptlScan()
* instead.
* @see #shutdownZone
*/
void powerZone(int xpos, int ypos, int zoneSize)
{
for (int dx = 0; dx < zoneSize; dx++) {
for (int dy = 0; dy < zoneSize; dy++) {
int x = xpos - 1 + dx;
int y = ypos - 1 + dy;
int tile = getTile(x, y);
TileSpec ts = Tiles.get(tile & LOMASK);
if (ts != null && ts.onPower != null) {
setTile(x, y,
(char) (ts.onPower.tileNumber | (tile & ALLBITS))
);
}
}
}
}
/**
* If a zone has a different image (animation) for when it is
* powered, switch back to the original image.
* @see #powerZone
* @see #killZone
*/
void shutdownZone(int xpos, int ypos, int zoneSize)
{
for (int dx = 0; dx < zoneSize; dx++) {
for (int dy = 0; dy < zoneSize; dy++) {
int x = xpos - 1 + dx;
int y = ypos - 1 + dy;
int tile = getTile(x, y);
TileSpec ts = Tiles.get(tile & LOMASK);
if (ts != null && ts.onShutdown != null) {
setTile(x, y,
(char) (ts.onShutdown.tileNumber | (tile & ALLBITS))
);
}
}
}
}
void makeExplosion(int xpos, int ypos)
{
makeExplosionAt(xpos*16+8, ypos*16+8);
}
/**
* Uses x,y coordinates as 1/16th-length tiles.
*/
void makeExplosionAt(int x, int y)
{
sprites.add(new ExplosionSprite(this, x, y));
}
void checkGrowth()
{
if (cityTime % 4 == 0) {
int newPop = (resPop + comPop * 8 + indPop * 8) * 20;
if (lastCityPop != 0) {
MicropolisMessage z = null;
if (lastCityPop < 500000 && newPop >= 500000) {
z = MicropolisMessage.POP_500K_REACHED;
} else if (lastCityPop < 100000 && newPop >= 100000) {
z = MicropolisMessage.POP_100K_REACHED;
} else if (lastCityPop < 50000 && newPop >= 50000) {
z = MicropolisMessage.POP_50K_REACHED;
} else if (lastCityPop < 10000 && newPop >= 10000) {
z = MicropolisMessage.POP_10K_REACHED;
} else if (lastCityPop < 2000 && newPop >= 2000) {
z = MicropolisMessage.POP_2K_REACHED;
}
if (z != null) {
sendMessage(z, true);
}
}
lastCityPop = newPop;
}
}
void doMessages()
{
//MORE (scenario stuff)
checkGrowth();
int totalZoneCount = resZoneCount + comZoneCount + indZoneCount;
int powerCount = nuclearCount + coalCount;
int z = cityTime % 64;
switch (z) {
case 1:
if (totalZoneCount / 4 >= resZoneCount) {
sendMessage(MicropolisMessage.NEED_RES);
}
break;
case 5:
if (totalZoneCount / 8 >= comZoneCount) {
sendMessage(MicropolisMessage.NEED_COM);
}
break;
case 10:
if (totalZoneCount / 8 >= indZoneCount) {
sendMessage(MicropolisMessage.NEED_IND);
}
break;
case 14:
if (totalZoneCount > 10 && totalZoneCount * 2 > roadTotal) {
sendMessage(MicropolisMessage.NEED_ROADS);
}
break;
case 18:
if (totalZoneCount > 50 && totalZoneCount > railTotal) {
sendMessage(MicropolisMessage.NEED_RAILS);
}
break;
case 22:
if (totalZoneCount > 10 && powerCount == 0) {
sendMessage(MicropolisMessage.NEED_POWER);
}
break;
case 26:
resCap = (resPop > 500 && stadiumCount == 0);
if (resCap) {
sendMessage(MicropolisMessage.NEED_STADIUM);
}
break;
case 28:
indCap = (indPop > 70 && seaportCount == 0);
if (indCap) {
sendMessage(MicropolisMessage.NEED_SEAPORT);
}
break;
case 30:
comCap = (comPop > 100 && airportCount == 0);
if (comCap) {
sendMessage(MicropolisMessage.NEED_AIRPORT);
}
break;
case 32:
int TM = unpoweredZoneCount + poweredZoneCount;
if (TM != 0) {
if ((double)poweredZoneCount / (double)TM < 0.7) {
sendMessage(MicropolisMessage.BLACKOUTS);
}
}
break;
case 35:
if (pollutionAverage > 60) { // FIXME, consider changing threshold to 80
sendMessage(MicropolisMessage.HIGH_POLLUTION, true);
}
break;
case 42:
if (crimeAverage > 100) {
sendMessage(MicropolisMessage.HIGH_CRIME, true);
}
break;
case 45:
if (totalPop > 60 && fireStationCount == 0) {
sendMessage(MicropolisMessage.NEED_FIRESTATION);
}
break;
case 48:
if (totalPop > 60 && policeCount == 0) {
sendMessage(MicropolisMessage.NEED_POLICE);
}
break;
case 51:
if (cityTax > 12) {
sendMessage(MicropolisMessage.HIGH_TAXES);
}
break;
case 54:
if (roadEffect < 20 && roadTotal > 30) {
sendMessage(MicropolisMessage.ROADS_NEED_FUNDING);
}
break;
case 57:
if (fireEffect < 700 && totalPop > 20) {
sendMessage(MicropolisMessage.FIRE_NEED_FUNDING);
}
break;
case 60:
if (policeEffect < 700 && totalPop > 20) {
sendMessage(MicropolisMessage.POLICE_NEED_FUNDING);
}
break;
case 63:
if (trafficAverage > 60) {
sendMessage(MicropolisMessage.HIGH_TRAFFIC);
}
break;
default:
//nothing
}
}
void clearMes()
{
//TODO.
// What this does in the original code is clears the 'last message'
// properties, ensuring that the next message will be delivered even
// if it is a repeat.
}
void sendMessage(MicropolisMessage message)
{
fireCityMessage(message, null, false);
}
void sendMessage(MicropolisMessage message, boolean isPic)
{
fireCityMessage(message, null, true);
}
void sendMessageAt(MicropolisMessage message, int x, int y)
{
fireCityMessage(message, new CityLocation(x,y), false);
}
void sendMessageAtPic(MicropolisMessage message, int x, int y)
{
fireCityMessage(message, new CityLocation(x,y), true);
}
public ZoneStatus queryZoneStatus(int xpos, int ypos)
{
ZoneStatus zs = new ZoneStatus();
zs.building = getBuildingId(getTile(xpos, ypos));
int z;
z = (popDensity[ypos/2][xpos/2] / 64) % 4;
zs.popDensity = z + 1;
z = landValueMem[ypos/2][xpos/2];
z = z < 30 ? 4 : z < 80 ? 5 : z < 150 ? 6 : 7;
zs.landValue = z + 1;
z = ((crimeMem[ypos/2][xpos/2] / 64) % 4) + 8;
zs.crimeLevel = z + 1;
z = Math.max(13,((pollutionMem[ypos/2][xpos/2] / 64) % 4) + 12);
zs.pollution = z + 1;
z = rateOGMem[ypos/8][xpos/8];
z = z < 0 ? 16 : z == 0 ? 17 : z <= 100 ? 18 : 19;
zs.growthRate = z + 1;
return zs;
}
public int getResValve()
{
return resValve;
}
public int getComValve()
{
return comValve;
}
public int getIndValve()
{
return indValve;
}
public void setGameLevel(int newLevel)
{
assert GameLevel.isValid(newLevel);
gameLevel = newLevel;
fireOptionsChanged();
}
public void setFunds(int totalFunds)
{
budget.totalFunds = totalFunds;
}
}
| true | true | void setValves()
{
double normResPop = (double)resPop / 8.0;
totalPop = (int) (normResPop + comPop + indPop);
double employment;
if (normResPop != 0.0)
{
employment = (history.com[1] + history.ind[1]) / normResPop;
}
else
{
employment = 1;
}
double migration = normResPop * (employment - 1);
final double BIRTH_RATE = 0.02;
double births = (double)normResPop * BIRTH_RATE;
double projectedResPop = normResPop + migration + births;
double temp = (history.com[1] + history.ind[1]);
double laborBase;
if (temp != 0.0)
{
laborBase = history.res[1] / temp;
}
else
{
laborBase = 1;
}
// clamp laborBase to between 0.0 and 1.3
laborBase = Math.max(0.0, Math.min(1.3, laborBase));
double internalMarket = (double)(normResPop + comPop + indPop) / 3.7;
double projectedComPop = internalMarket * laborBase;
int z = gameLevel;
temp = 1.0;
switch (z)
{
case 0: temp = 1.2; break;
case 1: temp = 1.1; break;
case 2: temp = 0.98; break;
}
double projectedIndPop = indPop * laborBase * temp;
if (projectedIndPop < 5.0)
projectedIndPop = 5.0;
double resRatio;
if (normResPop != 0)
{
resRatio = (double)projectedResPop / (double)normResPop;
}
else
{
resRatio = 1.3;
}
double comRatio;
if (comPop != 0)
comRatio = (double)projectedComPop / (double)comPop;
else
comRatio = projectedComPop;
double indRatio;
if (indPop != 0)
indRatio = (double)projectedIndPop / (double)indPop;
else
indRatio = projectedIndPop;
if (resRatio > 2.0)
resRatio = 2.0;
if (comRatio > 2.0)
comRatio = 2.0;
if (indRatio > 2.0)
indRatio = 2.0;
int z2 = taxEffect + gameLevel;
if (z2 > 20)
z2 = 20;
resRatio = (resRatio - 1) * 600 + TaxTable[z];
comRatio = (comRatio - 1) * 600 + TaxTable[z];
indRatio = (indRatio - 1) * 600 + TaxTable[z];
// ratios are velocity changes to valves
resValve += (int) resRatio;
comValve += (int) comRatio;
indValve += (int) indRatio;
if (resValve > 2000)
resValve = 2000;
else if (resValve < -2000)
resValve = -2000;
if (comValve > 1500)
comValve = 1500;
else if (comValve < -1500)
comValve = -1500;
if (indValve > 1500)
indValve = 1500;
else if (indValve < -1500)
indValve = -1500;
if (resCap && resValve > 0) {
// residents demand stadium
resValve = 0;
}
if (comCap && comValve > 0) {
// commerce demands airport
comValve = 0;
}
if (indCap && indValve > 0) {
// industry demands sea port
indValve = 0;
}
fireDemandChanged();
}
| void setValves()
{
double normResPop = (double)resPop / 8.0;
totalPop = (int) (normResPop + comPop + indPop);
double employment;
if (normResPop != 0.0)
{
employment = (history.com[1] + history.ind[1]) / normResPop;
}
else
{
employment = 1;
}
double migration = normResPop * (employment - 1);
final double BIRTH_RATE = 0.02;
double births = (double)normResPop * BIRTH_RATE;
double projectedResPop = normResPop + migration + births;
double temp = (history.com[1] + history.ind[1]);
double laborBase;
if (temp != 0.0)
{
laborBase = history.res[1] / temp;
}
else
{
laborBase = 1;
}
// clamp laborBase to between 0.0 and 1.3
laborBase = Math.max(0.0, Math.min(1.3, laborBase));
double internalMarket = (double)(normResPop + comPop + indPop) / 3.7;
double projectedComPop = internalMarket * laborBase;
int z = gameLevel;
temp = 1.0;
switch (z)
{
case 0: temp = 1.2; break;
case 1: temp = 1.1; break;
case 2: temp = 0.98; break;
}
double projectedIndPop = indPop * laborBase * temp;
if (projectedIndPop < 5.0)
projectedIndPop = 5.0;
double resRatio;
if (normResPop != 0)
{
resRatio = (double)projectedResPop / (double)normResPop;
}
else
{
resRatio = 1.3;
}
double comRatio;
if (comPop != 0)
comRatio = (double)projectedComPop / (double)comPop;
else
comRatio = projectedComPop;
double indRatio;
if (indPop != 0)
indRatio = (double)projectedIndPop / (double)indPop;
else
indRatio = projectedIndPop;
if (resRatio > 2.0)
resRatio = 2.0;
if (comRatio > 2.0)
comRatio = 2.0;
if (indRatio > 2.0)
indRatio = 2.0;
int z2 = taxEffect + gameLevel;
if (z2 > 20)
z2 = 20;
resRatio = (resRatio - 1) * 600 + TaxTable[z2];
comRatio = (comRatio - 1) * 600 + TaxTable[z2];
indRatio = (indRatio - 1) * 600 + TaxTable[z2];
// ratios are velocity changes to valves
resValve += (int) resRatio;
comValve += (int) comRatio;
indValve += (int) indRatio;
if (resValve > 2000)
resValve = 2000;
else if (resValve < -2000)
resValve = -2000;
if (comValve > 1500)
comValve = 1500;
else if (comValve < -1500)
comValve = -1500;
if (indValve > 1500)
indValve = 1500;
else if (indValve < -1500)
indValve = -1500;
if (resCap && resValve > 0) {
// residents demand stadium
resValve = 0;
}
if (comCap && comValve > 0) {
// commerce demands airport
comValve = 0;
}
if (indCap && indValve > 0) {
// industry demands sea port
indValve = 0;
}
fireDemandChanged();
}
|
diff --git a/src/main/java/name/richardson/james/bukkit/utilities/updater/PluginUpdater.java b/src/main/java/name/richardson/james/bukkit/utilities/updater/PluginUpdater.java
index 1f8db61..60e027b 100644
--- a/src/main/java/name/richardson/james/bukkit/utilities/updater/PluginUpdater.java
+++ b/src/main/java/name/richardson/james/bukkit/utilities/updater/PluginUpdater.java
@@ -1,161 +1,161 @@
package name.richardson.james.bukkit.utilities.updater;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.xml.sax.SAXException;
import name.richardson.james.bukkit.utilities.internals.Logger;
import name.richardson.james.bukkit.utilities.plugin.SimplePlugin;
public class PluginUpdater implements Runnable {
private final Logger logger = new Logger(PluginUpdater.class);
private final SimplePlugin plugin;
private MavenManifest manifest;
private boolean installUpdates;
public PluginUpdater(SimplePlugin plugin, boolean install) {
this.plugin = plugin;
this.installUpdates = install;
if (plugin.isDebugging()) logger.setDebugging(true);
}
private boolean isNewVersionAvailable() {
DefaultArtifactVersion current = new DefaultArtifactVersion(plugin.getDescription().getVersion());
logger.debug("Current local version: " + current.toString());
DefaultArtifactVersion target = new DefaultArtifactVersion(manifest.getCurrentVersion());
logger.debug("Latest remote version: " + target.toString());
if (current.compareTo(target) == -1) {
return true;
} else {
return false;
}
}
private URL getMavenMetaDataURL() throws MalformedURLException {
StringBuilder path = new StringBuilder();
path.append(this.plugin.getRepositoryURL());
path.append("/");
path.append(this.plugin.getGroupID().replace(".", "/"));
path.append("/");
path.append(this.plugin.getArtifactID());
path.append("/maven-metadata.xml");
return new URL(path.toString());
}
private URL getPluginURL() throws MalformedURLException {
String version = manifest.getCurrentVersion();
StringBuilder path = new StringBuilder();
path.append(this.plugin.getRepositoryURL());
path.append("/");
path.append(this.plugin.getGroupID().replace(".", "/"));
path.append("/");
path.append(this.plugin.getArtifactID());
path.append("/");
path.append(version);
path.append("/");
path.append(this.plugin.getArtifactID());
path.append("-");
path.append(version);
path.append(".jar");
return new URL(path.toString());
}
public void run() {
this.logger.setPrefix("[" + plugin.getName() + "] ");
logger.debug(this.plugin.getMessage("updater-checking-for-new-version"));
try {
this.parseMavenMetaData();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
} catch (SAXException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
} catch (ParserConfigurationException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
}
if (this.isNewVersionAvailable()) {
if (this.installUpdates) {
try {
// create the path for the updated plugin
StringBuilder path = new StringBuilder();
path.append(this.plugin.getServer().getUpdateFolderFile().getAbsolutePath());
path.append(File.separatorChar);
path.append(this.plugin.getDescription().getName());
path.append(".jar");
// create the URL of the updated plugin
// download the update to the update folder
logger.debug("Path to save updated plugin: " + path);
File storage = new File(path.toString());
storage.createNewFile();
// normalise the plugin name as necessary
this.normalisePluginFileName();
this.fetchFile(this.getPluginURL(), storage);
- logger.info(this.plugin.getMessage("updater-plugin-updated"));
+ logger.info(this.plugin.getSimpleFormattedMessage("updater-plugin-updated", this.manifest.getCurrentVersion()));
} catch (MalformedURLException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-get-plugin"));
e.printStackTrace();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
}
} else {
logger.info(this.plugin.getSimpleFormattedMessage("updater-newer-version-available", this.manifest.getCurrentVersion()));
}
}
}
// This is used to search the plugin directory and then change the name of the plugin
// if necessary. The .jar should match the name of the plugin as defined in plugin.yml.
// This is necessary otherwise the updater in Bukkit will not work.
private File getPluginFile() {
File plugins = plugin.getDataFolder().getParentFile();
String[] files = plugins.list(new PluginFilter(this.plugin));
logger.debug(files.toString());
return new File(plugin.getDataFolder().getParentFile().toString() + File.separatorChar + files[0]);
}
private void normalisePluginFileName() {
String name = plugin.getName() + ".jar";
File plugin = this.getPluginFile();
if (!plugin.getName().equals(name)) {
logger.debug("Plugin file name is inconsistent. Renaming to " + name + ".");
File file = new File(plugin.getParentFile().toString() + File.separatorChar + name);
plugin.renameTo(file);
}
}
private void parseMavenMetaData() throws IOException, SAXException, ParserConfigurationException {
File temp = File.createTempFile(this.plugin.getClass().getSimpleName() + "-", null);
this.fetchFile(this.getMavenMetaDataURL(), temp);
this.manifest = new MavenManifest(temp);
}
private void fetchFile(URL url, File storage) throws IOException {
logger.debug("Fetching resource from " + url.toString());
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
logger.debug("Saving resources to " + storage.getPath());
FileOutputStream fos = new FileOutputStream(storage);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
rbc.close();
fos.close();
}
}
| true | true | public void run() {
this.logger.setPrefix("[" + plugin.getName() + "] ");
logger.debug(this.plugin.getMessage("updater-checking-for-new-version"));
try {
this.parseMavenMetaData();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
} catch (SAXException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
} catch (ParserConfigurationException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
}
if (this.isNewVersionAvailable()) {
if (this.installUpdates) {
try {
// create the path for the updated plugin
StringBuilder path = new StringBuilder();
path.append(this.plugin.getServer().getUpdateFolderFile().getAbsolutePath());
path.append(File.separatorChar);
path.append(this.plugin.getDescription().getName());
path.append(".jar");
// create the URL of the updated plugin
// download the update to the update folder
logger.debug("Path to save updated plugin: " + path);
File storage = new File(path.toString());
storage.createNewFile();
// normalise the plugin name as necessary
this.normalisePluginFileName();
this.fetchFile(this.getPluginURL(), storage);
logger.info(this.plugin.getMessage("updater-plugin-updated"));
} catch (MalformedURLException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-get-plugin"));
e.printStackTrace();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
}
} else {
logger.info(this.plugin.getSimpleFormattedMessage("updater-newer-version-available", this.manifest.getCurrentVersion()));
}
}
}
| public void run() {
this.logger.setPrefix("[" + plugin.getName() + "] ");
logger.debug(this.plugin.getMessage("updater-checking-for-new-version"));
try {
this.parseMavenMetaData();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
} catch (SAXException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
} catch (ParserConfigurationException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-read-metadata"));
e.printStackTrace();
}
if (this.isNewVersionAvailable()) {
if (this.installUpdates) {
try {
// create the path for the updated plugin
StringBuilder path = new StringBuilder();
path.append(this.plugin.getServer().getUpdateFolderFile().getAbsolutePath());
path.append(File.separatorChar);
path.append(this.plugin.getDescription().getName());
path.append(".jar");
// create the URL of the updated plugin
// download the update to the update folder
logger.debug("Path to save updated plugin: " + path);
File storage = new File(path.toString());
storage.createNewFile();
// normalise the plugin name as necessary
this.normalisePluginFileName();
this.fetchFile(this.getPluginURL(), storage);
logger.info(this.plugin.getSimpleFormattedMessage("updater-plugin-updated", this.manifest.getCurrentVersion()));
} catch (MalformedURLException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-get-plugin"));
e.printStackTrace();
} catch (IOException e) {
logger.warning(this.plugin.getMessage("updater-unable-to-save-file"));
e.printStackTrace();
}
} else {
logger.info(this.plugin.getSimpleFormattedMessage("updater-newer-version-available", this.manifest.getCurrentVersion()));
}
}
}
|
diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListener.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListener.java
index 8edcfa91dc..66b77e3236 100644
--- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListener.java
+++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListener.java
@@ -1,329 +1,327 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* 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.springframework.integration.jms;
import java.util.Map;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.Message;
import org.springframework.integration.gateway.MessagingGatewaySupport;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.jms.support.destination.DynamicDestinationResolver;
import org.springframework.util.Assert;
/**
* JMS MessageListener that converts a JMS Message into a Spring Integration
* Message and sends that Message to a channel. If the 'expectReply' value is
* <code>true</code>, it will also wait for a Spring Integration reply Message
* and convert that into a JMS reply.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Oleg Zhurakousky
*/
public class ChannelPublishingJmsMessageListener extends MessagingGatewaySupport
implements SessionAwareMessageListener<javax.jms.Message>, InitializingBean {
private volatile boolean expectReply;
private volatile MessageConverter messageConverter = new SimpleMessageConverter();
private volatile boolean extractRequestPayload = true;
private volatile boolean extractReplyPayload = true;
private volatile Object defaultReplyDestination;
private volatile long replyTimeToLive = javax.jms.Message.DEFAULT_TIME_TO_LIVE;
private volatile int replyPriority = javax.jms.Message.DEFAULT_PRIORITY;
private volatile int replyDeliveryMode = javax.jms.Message.DEFAULT_DELIVERY_MODE;
private volatile boolean explicitQosEnabledForReplies;
private volatile DestinationResolver destinationResolver = new DynamicDestinationResolver();
private volatile JmsHeaderMapper headerMapper = new DefaultJmsHeaderMapper();
public String getComponentType(){
return "jms:inbound-gateway";
}
/**
* Specify whether a JMS reply Message is expected.
*/
public void setExpectReply(boolean expectReply) {
this.expectReply = expectReply;
}
/**
* Set the default reply destination to send reply messages to. This will
* be applied in case of a request message that does not carry a
* "JMSReplyTo" field.
*/
public void setDefaultReplyDestination(Destination defaultReplyDestination) {
this.defaultReplyDestination = defaultReplyDestination;
}
/**
* Set the name of the default reply queue to send reply messages to.
* This will be applied in case of a request message that does not carry a
* "JMSReplyTo" field.
* <p>Alternatively, specify a JMS Destination object as "defaultReplyDestination".
* @see #setDestinationResolver
* @see #setDefaultReplyDestination(javax.jms.Destination)
*/
public void setDefaultReplyQueueName(String destinationName) {
this.defaultReplyDestination = new DestinationNameHolder(destinationName, false);
}
/**
* Set the name of the default reply topic to send reply messages to.
* This will be applied in case of a request message that does not carry a
* "JMSReplyTo" field.
* <p>Alternatively, specify a JMS Destination object as "defaultReplyDestination".
* @see #setDestinationResolver
* @see #setDefaultReplyDestination(javax.jms.Destination)
*/
public void setDefaultReplyTopicName(String destinationName) {
this.defaultReplyDestination = new DestinationNameHolder(destinationName, true);
}
/**
* Specify the time-to-live property for JMS reply Messages.
* @see javax.jms.MessageProducer#setTimeToLive(long)
*/
public void setReplyTimeToLive(long replyTimeToLive) {
this.replyTimeToLive = replyTimeToLive;
}
/**
* Specify the priority value for JMS reply Messages.
* @see javax.jms.MessageProducer#setPriority(int)
*/
public void setReplyPriority(int replyPriority) {
this.replyPriority = replyPriority;
}
/**
* Specify the delivery mode for JMS reply Messages.
* @see javax.jms.MessageProducer#setDeliveryMode(int)
*/
public void setReplyDeliveryPersistent(boolean replyDeliveryPersistent) {
this.replyDeliveryMode = replyDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
}
/**
* Specify whether explicit QoS should be enabled for replies
* (for timeToLive, priority, and deliveryMode settings).
*/
public void setExplicitQosEnabledForReplies(boolean explicitQosEnabledForReplies) {
this.explicitQosEnabledForReplies = explicitQosEnabledForReplies;
}
/**
* Set the DestinationResolver that should be used to resolve reply
* destination names for this listener.
* <p>The default resolver is a DynamicDestinationResolver. Specify a
* JndiDestinationResolver for resolving destination names as JNDI locations.
* @see org.springframework.jms.support.destination.DynamicDestinationResolver
* @see org.springframework.jms.support.destination.JndiDestinationResolver
*/
public void setDestinationResolver(DestinationResolver destinationResolver) {
Assert.notNull(destinationResolver, "destinationResolver must not be null");
this.destinationResolver = destinationResolver;
}
/**
* Provide a {@link MessageConverter} implementation to use when
* converting between JMS Messages and Spring Integration Messages.
* If none is provided, a {@link SimpleMessageConverter} will
* be used.
*
* @param messageConverter
*/
public void setMessageConverter(MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
/**
* Provide a {@link JmsHeaderMapper} implementation to use when
* converting between JMS Messages and Spring Integration Messages.
* If none is provided, a {@link DefaultJmsHeaderMapper} will be used.
*/
public void setHeaderMapper(JmsHeaderMapper headerMapper) {
this.headerMapper = headerMapper;
}
/**
* Specify whether the JMS request Message's body should be extracted prior
* to converting into a Spring Integration Message. This value is set to
* <code>true</code> by default. To send the JMS Message itself as a
* Spring Integration Message payload, set this to <code>false</code>.
*/
public void setExtractRequestPayload(boolean extractRequestPayload) {
this.extractRequestPayload = extractRequestPayload;
}
/**
* Specify whether the Spring Integration reply Message's payload should be
* extracted prior to converting into a JMS Message. This value is set to
* <code>true</code> by default. To send the Spring Integration Message
* itself as the JMS Message's body, set this to <code>false</code>.
*/
public void setExtractReplyPayload(boolean extractReplyPayload) {
this.extractReplyPayload = extractReplyPayload;
}
@SuppressWarnings("unchecked")
public void onMessage(javax.jms.Message jmsMessage, Session session) throws JMSException {
Object result = jmsMessage;
if (this.extractRequestPayload) {
result = this.messageConverter.fromMessage(jmsMessage);
if (logger.isDebugEnabled()) {
logger.debug("converted JMS Message [" + jmsMessage + "] to integration Message payload [" + result + "]");
}
}
Map<String, Object> headers = (Map<String, Object>) headerMapper.toHeaders(jmsMessage);
Message<?> requestMessage = (result instanceof Message<?>) ?
MessageBuilder.fromMessage((Message<?>) result).copyHeaders(headers).build() :
MessageBuilder.withPayload(result).copyHeaders(headers).build();
if (!this.expectReply) {
this.send(requestMessage);
}
else {
Message<?> replyMessage = this.sendAndReceiveMessage(requestMessage);
if (replyMessage != null) {
Destination destination = this.getReplyDestination(jmsMessage, session);
if (destination != null){
// convert SI Message to JMS Message
Object replyResult = replyMessage;
if (this.extractReplyPayload){
replyResult = replyMessage.getPayload();
}
try {
javax.jms.Message jmsReply = this.messageConverter.toMessage(replyResult, session);
// map SI Message Headers to JMS Message Properties/Headers
headerMapper.fromHeaders(replyMessage.getHeaders(), jmsReply);
if (jmsReply.getJMSCorrelationID() == null) {
jmsReply.setJMSCorrelationID(jmsMessage.getJMSMessageID());
}
MessageProducer producer = session.createProducer(destination);
try {
if (this.explicitQosEnabledForReplies) {
producer.send(jmsReply,
this.replyDeliveryMode, this.replyPriority, this.replyTimeToLive);
}
else {
producer.send(jmsReply);
}
}
finally {
producer.close();
}
- } catch (RuntimeException e) {
- //e.printStackTrace();
- logger.error("Failed to generate JMS Reply Message from: " + replyResult + "\n" +
- "A typical cause is that the Object from which the JMS Message is created or some member of its " +
- "hierarchy is not Serializable.", e);
+ }
+ catch (RuntimeException e) {
+ logger.error("Failed to generate JMS Reply Message from: " + replyResult, e);
throw e;
}
}
}
}
}
/**
* Determine a reply destination for the given message.
* <p>
* This implementation first checks the boolean 'error' flag which signifies that the reply is an error message. If
* reply is not an error it will first check the JMS Reply-To {@link Destination} of the supplied request message;
* if that is not <code>null</code> it is returned; if it is <code>null</code>, then the configured
* {@link #resolveDefaultReplyDestination default reply destination} is returned; if this too is <code>null</code>,
* then an {@link InvalidDestinationException} is thrown.
* @param request the original incoming JMS message
* @param session the JMS Session to operate on
* @return the reply destination (never <code>null</code>)
* @throws JMSException if thrown by JMS API methods
* @throws InvalidDestinationException if no {@link Destination} can be determined
* @see #setDefaultReplyDestination
* @see javax.jms.Message#getJMSReplyTo()
*/
private Destination getReplyDestination(javax.jms.Message request, Session session) throws JMSException {
Destination replyTo = request.getJMSReplyTo();
if (replyTo == null) {
replyTo = resolveDefaultReplyDestination(session);
if (replyTo == null) {
throw new InvalidDestinationException("Cannot determine reply destination: " +
"Request message does not contain reply-to destination, and no default reply destination set.");
}
}
return replyTo;
}
/**
* Resolve the default reply destination into a JMS {@link Destination}, using this
* listener's {@link DestinationResolver} in case of a destination name.
* @return the located {@link Destination}
* @throws javax.jms.JMSException if resolution failed
* @see #setDefaultReplyDestination
* @see #setDefaultReplyQueueName
* @see #setDefaultReplyTopicName
* @see #setDestinationResolver
*/
private Destination resolveDefaultReplyDestination(Session session) throws JMSException {
if (this.defaultReplyDestination instanceof Destination) {
return (Destination) this.defaultReplyDestination;
}
if (this.defaultReplyDestination instanceof DestinationNameHolder) {
DestinationNameHolder nameHolder = (DestinationNameHolder) this.defaultReplyDestination;
return this.destinationResolver.resolveDestinationName(session, nameHolder.name, nameHolder.isTopic);
}
return null;
}
/**
* Internal class combining a destination name
* and its target destination type (queue or topic).
*/
private static class DestinationNameHolder {
public final String name;
public final boolean isTopic;
public DestinationNameHolder(String name, boolean isTopic) {
this.name = name;
this.isTopic = isTopic;
}
}
}
| true | true | public void onMessage(javax.jms.Message jmsMessage, Session session) throws JMSException {
Object result = jmsMessage;
if (this.extractRequestPayload) {
result = this.messageConverter.fromMessage(jmsMessage);
if (logger.isDebugEnabled()) {
logger.debug("converted JMS Message [" + jmsMessage + "] to integration Message payload [" + result + "]");
}
}
Map<String, Object> headers = (Map<String, Object>) headerMapper.toHeaders(jmsMessage);
Message<?> requestMessage = (result instanceof Message<?>) ?
MessageBuilder.fromMessage((Message<?>) result).copyHeaders(headers).build() :
MessageBuilder.withPayload(result).copyHeaders(headers).build();
if (!this.expectReply) {
this.send(requestMessage);
}
else {
Message<?> replyMessage = this.sendAndReceiveMessage(requestMessage);
if (replyMessage != null) {
Destination destination = this.getReplyDestination(jmsMessage, session);
if (destination != null){
// convert SI Message to JMS Message
Object replyResult = replyMessage;
if (this.extractReplyPayload){
replyResult = replyMessage.getPayload();
}
try {
javax.jms.Message jmsReply = this.messageConverter.toMessage(replyResult, session);
// map SI Message Headers to JMS Message Properties/Headers
headerMapper.fromHeaders(replyMessage.getHeaders(), jmsReply);
if (jmsReply.getJMSCorrelationID() == null) {
jmsReply.setJMSCorrelationID(jmsMessage.getJMSMessageID());
}
MessageProducer producer = session.createProducer(destination);
try {
if (this.explicitQosEnabledForReplies) {
producer.send(jmsReply,
this.replyDeliveryMode, this.replyPriority, this.replyTimeToLive);
}
else {
producer.send(jmsReply);
}
}
finally {
producer.close();
}
} catch (RuntimeException e) {
//e.printStackTrace();
logger.error("Failed to generate JMS Reply Message from: " + replyResult + "\n" +
"A typical cause is that the Object from which the JMS Message is created or some member of its " +
"hierarchy is not Serializable.", e);
throw e;
}
}
}
}
}
| public void onMessage(javax.jms.Message jmsMessage, Session session) throws JMSException {
Object result = jmsMessage;
if (this.extractRequestPayload) {
result = this.messageConverter.fromMessage(jmsMessage);
if (logger.isDebugEnabled()) {
logger.debug("converted JMS Message [" + jmsMessage + "] to integration Message payload [" + result + "]");
}
}
Map<String, Object> headers = (Map<String, Object>) headerMapper.toHeaders(jmsMessage);
Message<?> requestMessage = (result instanceof Message<?>) ?
MessageBuilder.fromMessage((Message<?>) result).copyHeaders(headers).build() :
MessageBuilder.withPayload(result).copyHeaders(headers).build();
if (!this.expectReply) {
this.send(requestMessage);
}
else {
Message<?> replyMessage = this.sendAndReceiveMessage(requestMessage);
if (replyMessage != null) {
Destination destination = this.getReplyDestination(jmsMessage, session);
if (destination != null){
// convert SI Message to JMS Message
Object replyResult = replyMessage;
if (this.extractReplyPayload){
replyResult = replyMessage.getPayload();
}
try {
javax.jms.Message jmsReply = this.messageConverter.toMessage(replyResult, session);
// map SI Message Headers to JMS Message Properties/Headers
headerMapper.fromHeaders(replyMessage.getHeaders(), jmsReply);
if (jmsReply.getJMSCorrelationID() == null) {
jmsReply.setJMSCorrelationID(jmsMessage.getJMSMessageID());
}
MessageProducer producer = session.createProducer(destination);
try {
if (this.explicitQosEnabledForReplies) {
producer.send(jmsReply,
this.replyDeliveryMode, this.replyPriority, this.replyTimeToLive);
}
else {
producer.send(jmsReply);
}
}
finally {
producer.close();
}
}
catch (RuntimeException e) {
logger.error("Failed to generate JMS Reply Message from: " + replyResult, e);
throw e;
}
}
}
}
}
|
diff --git a/src/net/ant/rc/rpi/Shell.java b/src/net/ant/rc/rpi/Shell.java
index 7ec2c26..2d70acd 100644
--- a/src/net/ant/rc/rpi/Shell.java
+++ b/src/net/ant/rc/rpi/Shell.java
@@ -1,49 +1,49 @@
package net.ant.rc.rpi;
import org.apache.log4j.Logger;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Ant
* Date: 19.10.13
* Time: 3:00
*/
public class Shell {
public static String execute(String command){
Logger logger = Logger.getLogger("log4j.logger.net.ant.rc");
if (command == null) return null;
String[] c;
if ("reboot".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/reboot"};
}else
if ("shutdown".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/shutdown", "now"};
}else
if ("temperature".equals(command)){
c = new String[]{"cat", "/sys/class/thermal/thermal_zone0/temp"};
}else{
return null;
}
try {
Process p = Runtime.getRuntime().exec(c);
byte[] buf = new byte[500];
Thread.sleep(3000);
if(p.exitValue()==1){
p.getErrorStream().read(buf);
}else{
p.getInputStream().read(buf);
}
return new String(buf);
} catch (IOException e) {
- logger.error(e.getMessage(), e);
+ logger.error(e.getMessage());
return e.getMessage();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
return e.getMessage();
}
}
}
| true | true | public static String execute(String command){
Logger logger = Logger.getLogger("log4j.logger.net.ant.rc");
if (command == null) return null;
String[] c;
if ("reboot".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/reboot"};
}else
if ("shutdown".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/shutdown", "now"};
}else
if ("temperature".equals(command)){
c = new String[]{"cat", "/sys/class/thermal/thermal_zone0/temp"};
}else{
return null;
}
try {
Process p = Runtime.getRuntime().exec(c);
byte[] buf = new byte[500];
Thread.sleep(3000);
if(p.exitValue()==1){
p.getErrorStream().read(buf);
}else{
p.getInputStream().read(buf);
}
return new String(buf);
} catch (IOException e) {
logger.error(e.getMessage(), e);
return e.getMessage();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
return e.getMessage();
}
}
| public static String execute(String command){
Logger logger = Logger.getLogger("log4j.logger.net.ant.rc");
if (command == null) return null;
String[] c;
if ("reboot".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/reboot"};
}else
if ("shutdown".equals(command)){
c = new String[]{"/usr/bin/sudo", "/sbin/shutdown", "now"};
}else
if ("temperature".equals(command)){
c = new String[]{"cat", "/sys/class/thermal/thermal_zone0/temp"};
}else{
return null;
}
try {
Process p = Runtime.getRuntime().exec(c);
byte[] buf = new byte[500];
Thread.sleep(3000);
if(p.exitValue()==1){
p.getErrorStream().read(buf);
}else{
p.getInputStream().read(buf);
}
return new String(buf);
} catch (IOException e) {
logger.error(e.getMessage());
return e.getMessage();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
return e.getMessage();
}
}
|
diff --git a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/core/tests/AllTests.java b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/core/tests/AllTests.java
index 49880817..8bfb25fd 100755
--- a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/core/tests/AllTests.java
+++ b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/core/tests/AllTests.java
@@ -1,49 +1,49 @@
package org.eclipse.dltk.ruby.core.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.dltk.ruby.core.tests.assist.RubySelectionTests;
import org.eclipse.dltk.ruby.core.tests.launching.RubyLaunchingTests;
import org.eclipse.dltk.ruby.core.tests.parser.RubyParserTests;
import org.eclipse.dltk.ruby.core.tests.search.mixin.AutoMixinTests;
import org.eclipse.dltk.ruby.core.tests.search.mixin.MixinModelManipulationTests;
import org.eclipse.dltk.ruby.core.tests.text.completion.RubyCompletionTests;
import org.eclipse.dltk.ruby.core.tests.typeinference.MethodsTest;
import org.eclipse.dltk.ruby.core.tests.typeinference.SimpleTest;
import org.eclipse.dltk.ruby.core.tests.typeinference.StatementsTest;
import org.eclipse.dltk.ruby.core.tests.typeinference.VariablesTest;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.dltk.ruby.core");
// $JUnit-BEGIN$
suite.addTest(AutoMixinTests.suite());
suite.addTest(MixinModelManipulationTests.suite());
suite.addTest(RubySelectionTests.suite());
suite.addTest(RubyCompletionTests.suite());
suite.addTestSuite(RubyParserTests.class);
// FIXME: fix running of this tests under mac os x
// suite.addTest(StdlibRubyParserTests.suite());
// suite.addTest(JRuby1RubyParserTests.suite());
// XXX: uncomment this tests, when type hierarchies
// support will be implemented
// suite.addTest(TypeHierarchyTests.suite());
// Type inference
suite.addTest(VariablesTest.suite());
suite.addTest(MethodsTest.suite());
suite.addTest(StatementsTest.suite());
suite.addTest(SimpleTest.suite());
// Launching
- suite.addTestSuite(RubyLaunchingTests.class);
+ suite.addTest(RubyLaunchingTests.suite());
// $JUnit-END$
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.dltk.ruby.core");
// $JUnit-BEGIN$
suite.addTest(AutoMixinTests.suite());
suite.addTest(MixinModelManipulationTests.suite());
suite.addTest(RubySelectionTests.suite());
suite.addTest(RubyCompletionTests.suite());
suite.addTestSuite(RubyParserTests.class);
// FIXME: fix running of this tests under mac os x
// suite.addTest(StdlibRubyParserTests.suite());
// suite.addTest(JRuby1RubyParserTests.suite());
// XXX: uncomment this tests, when type hierarchies
// support will be implemented
// suite.addTest(TypeHierarchyTests.suite());
// Type inference
suite.addTest(VariablesTest.suite());
suite.addTest(MethodsTest.suite());
suite.addTest(StatementsTest.suite());
suite.addTest(SimpleTest.suite());
// Launching
suite.addTestSuite(RubyLaunchingTests.class);
// $JUnit-END$
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.dltk.ruby.core");
// $JUnit-BEGIN$
suite.addTest(AutoMixinTests.suite());
suite.addTest(MixinModelManipulationTests.suite());
suite.addTest(RubySelectionTests.suite());
suite.addTest(RubyCompletionTests.suite());
suite.addTestSuite(RubyParserTests.class);
// FIXME: fix running of this tests under mac os x
// suite.addTest(StdlibRubyParserTests.suite());
// suite.addTest(JRuby1RubyParserTests.suite());
// XXX: uncomment this tests, when type hierarchies
// support will be implemented
// suite.addTest(TypeHierarchyTests.suite());
// Type inference
suite.addTest(VariablesTest.suite());
suite.addTest(MethodsTest.suite());
suite.addTest(StatementsTest.suite());
suite.addTest(SimpleTest.suite());
// Launching
suite.addTest(RubyLaunchingTests.suite());
// $JUnit-END$
return suite;
}
|
diff --git a/src/main/java/hudson/plugins/jacoco/ExecutionFileLoader.java b/src/main/java/hudson/plugins/jacoco/ExecutionFileLoader.java
index 5d37888..6f759fe 100644
--- a/src/main/java/hudson/plugins/jacoco/ExecutionFileLoader.java
+++ b/src/main/java/hudson/plugins/jacoco/ExecutionFileLoader.java
@@ -1,148 +1,157 @@
package hudson.plugins.jacoco;
import hudson.FilePath;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.codehaus.plexus.util.FileUtils;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IBundleCoverage;
import org.jacoco.core.data.ExecutionDataReader;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.maven.FileFilter;
import edu.emory.mathcs.backport.java.util.Arrays;
public class ExecutionFileLoader implements Serializable {
private String name;
private FilePath srcDir;
private FilePath classDir;
private FilePath execFile;
private FilePath generatedHTMLsDir;
private String[] includes;
private String[] excludes;
private String title;
private ExecutionDataStore executionDataStore;
private SessionInfoStore sessionInfoStore;
private IBundleCoverage bundleCoverage;
private ArrayList<FilePath> execFiles;
public ExecutionFileLoader() {
execFiles=new ArrayList<FilePath>();
}
public void addExecFile(FilePath execFile) {
execFiles.add(execFile);
}
public IBundleCoverage getBundleCoverage() {
return bundleCoverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setBundleCoverage(IBundleCoverage bundleCoverage) {
this.bundleCoverage = bundleCoverage;
}
public FilePath getGeneratedHTMLsDir() {
return generatedHTMLsDir;
}
public void setGeneratedHTMLsDir(FilePath generatedHTMLsDir) {
this.generatedHTMLsDir = generatedHTMLsDir;
}
public FilePath getSrcDir() {
return srcDir;
}
public void setSrcDir(FilePath srcDir) {
this.srcDir = srcDir;
}
public FilePath getClassDir() {
return classDir;
}
public void setClassDir(FilePath classDir) {
this.classDir = classDir;
}
public FilePath getExecFile() {
return execFile;
}
public void setExecFile(FilePath execFile) {
this.execFile = execFile;
}
private void loadExecutionData() throws IOException {
executionDataStore = new ExecutionDataStore();
sessionInfoStore = new SessionInfoStore();
for (final Iterator<FilePath> i = execFiles.iterator(); i.hasNext();) {
InputStream isc = null;
try {
File executionDataFile = new File(i.next().getRemote());
final FileInputStream fis = new FileInputStream(executionDataFile);
final ExecutionDataReader reader = new ExecutionDataReader(fis);
reader.setSessionInfoVisitor(sessionInfoStore);
reader.setExecutionDataVisitor(executionDataStore);
reader.read();
isc = fis;
} catch (final IOException e) {
e.printStackTrace();
} finally {
org.apache.tools.ant.util.FileUtils.close(isc);
}
}
}
private IBundleCoverage analyzeStructure() throws IOException {
File classDirectory = new File(classDir.getRemote());
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionDataStore,
coverageBuilder);
- if ((includes==null)|| ("".equals(includes[0]))) {
+ if (includes==null) {
String[] in = {"**"};
includes = in;
- }
- if ((excludes==null) || ("".equals(excludes[0]))) {
+ } else if (includes.length == 0) {
+ String[] in = {"**"};
+ includes = in;
+ } else if ((includes.length == 1) && ("".equals(includes[0]))) {
+ String[] in = {"**"};
+ includes = in;
+ }
+ if (excludes==null) {
+ String[] ex = {"{0}"};
+ excludes = ex;
+ } else if (excludes.length==0) {
String[] ex = {"{0}"};
excludes = ex;
}
@SuppressWarnings("unchecked")
final FileFilter fileFilter = new FileFilter(Arrays.asList(includes), Arrays.asList(excludes));
@SuppressWarnings("unchecked")
final List<File> filesToAnalyze = FileUtils.getFiles(classDirectory, fileFilter.getIncludes(), fileFilter.getExcludes());
for (final File file : filesToAnalyze) {
analyzer.analyzeAll(file);
}
return coverageBuilder.getBundle(name);
}
public IBundleCoverage loadBundleCoverage() throws IOException {
loadExecutionData();
this.bundleCoverage = analyzeStructure();
return this.bundleCoverage;
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
public void setExcludes(String[] excludes) {
this.excludes = excludes;
}
}
| false | true | private IBundleCoverage analyzeStructure() throws IOException {
File classDirectory = new File(classDir.getRemote());
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionDataStore,
coverageBuilder);
if ((includes==null)|| ("".equals(includes[0]))) {
String[] in = {"**"};
includes = in;
}
if ((excludes==null) || ("".equals(excludes[0]))) {
String[] ex = {"{0}"};
excludes = ex;
}
@SuppressWarnings("unchecked")
final FileFilter fileFilter = new FileFilter(Arrays.asList(includes), Arrays.asList(excludes));
@SuppressWarnings("unchecked")
final List<File> filesToAnalyze = FileUtils.getFiles(classDirectory, fileFilter.getIncludes(), fileFilter.getExcludes());
for (final File file : filesToAnalyze) {
analyzer.analyzeAll(file);
}
return coverageBuilder.getBundle(name);
}
| private IBundleCoverage analyzeStructure() throws IOException {
File classDirectory = new File(classDir.getRemote());
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionDataStore,
coverageBuilder);
if (includes==null) {
String[] in = {"**"};
includes = in;
} else if (includes.length == 0) {
String[] in = {"**"};
includes = in;
} else if ((includes.length == 1) && ("".equals(includes[0]))) {
String[] in = {"**"};
includes = in;
}
if (excludes==null) {
String[] ex = {"{0}"};
excludes = ex;
} else if (excludes.length==0) {
String[] ex = {"{0}"};
excludes = ex;
}
@SuppressWarnings("unchecked")
final FileFilter fileFilter = new FileFilter(Arrays.asList(includes), Arrays.asList(excludes));
@SuppressWarnings("unchecked")
final List<File> filesToAnalyze = FileUtils.getFiles(classDirectory, fileFilter.getIncludes(), fileFilter.getExcludes());
for (final File file : filesToAnalyze) {
analyzer.analyzeAll(file);
}
return coverageBuilder.getBundle(name);
}
|
diff --git a/test/RCACaseFunctionalTest.java b/test/RCACaseFunctionalTest.java
index 6460c2c..2d0f79c 100644
--- a/test/RCACaseFunctionalTest.java
+++ b/test/RCACaseFunctionalTest.java
@@ -1,165 +1,165 @@
/*
* Copyright (C) 2012 by Eero Laukkanen, Risto Virtanen, Jussi Patana, Juha Viljanen,
* Joona Koistinen, Pekka Rihtniemi, Mika Kekäle, Roope Hovi, Mikko Valjus,
* Timo Lehtinen, Jaakko Harjuhahto
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import job.Bootstrap;
import models.RCACase;
import models.User;
import org.junit.Before;
import org.junit.Test;
import play.mvc.Http;
import play.mvc.Router;
import play.test.Fixtures;
import play.test.FunctionalTest;
import java.util.TreeSet;
/**
* @author Risto Virtanen
*/
public class RCACaseFunctionalTest extends FunctionalTest {
@Before
public void setUp() {
Fixtures.deleteAllModels();
new Bootstrap().doJob();
}
@Test
public void testNullUserTest() {
Http.Response response = GET(Router.reverse("RCACaseController.createRCACase").url);
assertStatus(Http.StatusCode.FOUND, response);
assertHeaderEquals("Location", "/login", response);
}
@Test
public void nonexistentRCACaseTest() {
Http.Request request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", "9999");
Http.Response response = GET(request, request.url);
assertStatus(Http.StatusCode.NOT_FOUND, response);
}
@Test
public void getCSVForRCACaseTest() {
RCACase rcaCase = RCACase.find("caseName", "Test RCA case").first();
assertNotNull(rcaCase);
Http.Request request = newRequest();
request.url = "/login";
request.params.put("username", Bootstrap.ADMIN_USER_EMAIL);
request.params.put("password", Bootstrap.ADMIN_USER_PASSWORD);
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("RCACaseController.extractCSV").url;
request.method = "GET";
request.params.put("rcaCaseId", "9999");
Http.Response response = GET(request, request.url);
assertStatus(Http.StatusCode.NOT_FOUND, response);
request.params.put("rcaCaseId", rcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
}
@Test
public void checkIfCurrentUserHasRightsForRCACaseTest() {
RCACase privateRcaCase = RCACase.find("caseName", "Admin's own private RCA case").first();
assertNotNull(privateRcaCase);
Http.Request request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash);
Http.Response response = GET(request, request.url);
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", Bootstrap.TEST_USER_EMAIL);
request.params.put("password", Bootstrap.TEST_USER_PASSWORD);
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
User tester = User.find("email", Bootstrap.TEST_USER_EMAIL).first();
tester.addRCACase(privateRcaCase);
tester.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
User newUser = new User("testing", "testing");
newUser.caseIds = null;
newUser.save();
response = GET("/logout");
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", "testing");
request.params.put("password", "testing");
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.caseIds = new TreeSet<Long>();
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.addRCACase(privateRcaCase);
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
- request.params.put("id", privateRcaCase.id.toString());
+ request.params.put("URLHash", privateRcaCase.URLHash.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
}
}
| false | true | public void checkIfCurrentUserHasRightsForRCACaseTest() {
RCACase privateRcaCase = RCACase.find("caseName", "Admin's own private RCA case").first();
assertNotNull(privateRcaCase);
Http.Request request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
Http.Response response = GET(request, request.url);
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", Bootstrap.TEST_USER_EMAIL);
request.params.put("password", Bootstrap.TEST_USER_PASSWORD);
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
User tester = User.find("email", Bootstrap.TEST_USER_EMAIL).first();
tester.addRCACase(privateRcaCase);
tester.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
User newUser = new User("testing", "testing");
newUser.caseIds = null;
newUser.save();
response = GET("/logout");
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", "testing");
request.params.put("password", "testing");
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.caseIds = new TreeSet<Long>();
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.addRCACase(privateRcaCase);
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("id", privateRcaCase.id.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
}
| public void checkIfCurrentUserHasRightsForRCACaseTest() {
RCACase privateRcaCase = RCACase.find("caseName", "Admin's own private RCA case").first();
assertNotNull(privateRcaCase);
Http.Request request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash);
Http.Response response = GET(request, request.url);
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", Bootstrap.TEST_USER_EMAIL);
request.params.put("password", Bootstrap.TEST_USER_PASSWORD);
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
User tester = User.find("email", Bootstrap.TEST_USER_EMAIL).first();
tester.addRCACase(privateRcaCase);
tester.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
User newUser = new User("testing", "testing");
newUser.caseIds = null;
newUser.save();
response = GET("/logout");
assertStatus(Http.StatusCode.FOUND, response);
request = newRequest();
request.url = "/login";
request.params.put("username", "testing");
request.params.put("password", "testing");
POST(request, request.url);
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.caseIds = new TreeSet<Long>();
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash);
response = GET(request, request.url);
assertStatus(Http.StatusCode.FORBIDDEN, response);
newUser.addRCACase(privateRcaCase);
newUser.save();
request = newRequest();
request.url = Router.reverse("PublicRCACaseController.show").url;
request.method = "GET";
request.params.put("URLHash", privateRcaCase.URLHash.toString());
response = GET(request, request.url);
assertStatus(Http.StatusCode.OK, response);
}
|
diff --git a/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java b/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java
index dad40cd5..2422938b 100644
--- a/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java
+++ b/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java
@@ -1,62 +1,62 @@
/*
* 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.karaf.web;
import java.io.File;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.karaf.main.Main;
public class WebAppListener implements ServletContextListener {
private Main main;
public void contextInitialized(ServletContextEvent sce) {
try {
System.err.println("contextInitialized");
- String root = new File(sce.getServletContext().getRealPath("/") + "WEB-INF/karaf").getAbsolutePath();
+ String root = new File(sce.getServletContext().getRealPath("/") + "/WEB-INF/karaf").getAbsolutePath();
System.err.println("Root: " + root);
System.setProperty("karaf.home", root);
System.setProperty("karaf.base", root);
System.setProperty("karaf.data", root + "/data");
System.setProperty("karaf.history", root + "/data/history.txt");
System.setProperty("karaf.instances", root + "/instances");
System.setProperty("karaf.startLocalConsole", "false");
System.setProperty("karaf.startRemoteShell", "true");
System.setProperty("karaf.lock", "false");
main = new Main(new String[0]);
main.launch();
} catch (Exception e) {
main = null;
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
try {
System.err.println("contextDestroyed");
if (main != null) {
main.destroy(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public void contextInitialized(ServletContextEvent sce) {
try {
System.err.println("contextInitialized");
String root = new File(sce.getServletContext().getRealPath("/") + "WEB-INF/karaf").getAbsolutePath();
System.err.println("Root: " + root);
System.setProperty("karaf.home", root);
System.setProperty("karaf.base", root);
System.setProperty("karaf.data", root + "/data");
System.setProperty("karaf.history", root + "/data/history.txt");
System.setProperty("karaf.instances", root + "/instances");
System.setProperty("karaf.startLocalConsole", "false");
System.setProperty("karaf.startRemoteShell", "true");
System.setProperty("karaf.lock", "false");
main = new Main(new String[0]);
main.launch();
} catch (Exception e) {
main = null;
e.printStackTrace();
}
}
| public void contextInitialized(ServletContextEvent sce) {
try {
System.err.println("contextInitialized");
String root = new File(sce.getServletContext().getRealPath("/") + "/WEB-INF/karaf").getAbsolutePath();
System.err.println("Root: " + root);
System.setProperty("karaf.home", root);
System.setProperty("karaf.base", root);
System.setProperty("karaf.data", root + "/data");
System.setProperty("karaf.history", root + "/data/history.txt");
System.setProperty("karaf.instances", root + "/instances");
System.setProperty("karaf.startLocalConsole", "false");
System.setProperty("karaf.startRemoteShell", "true");
System.setProperty("karaf.lock", "false");
main = new Main(new String[0]);
main.launch();
} catch (Exception e) {
main = null;
e.printStackTrace();
}
}
|
diff --git a/Character_Abyssal/src/net/sf/anathema/character/abyssal/AbyssalCharacterModule.java b/Character_Abyssal/src/net/sf/anathema/character/abyssal/AbyssalCharacterModule.java
index eb87714342..e46f8a63c5 100644
--- a/Character_Abyssal/src/net/sf/anathema/character/abyssal/AbyssalCharacterModule.java
+++ b/Character_Abyssal/src/net/sf/anathema/character/abyssal/AbyssalCharacterModule.java
@@ -1,82 +1,82 @@
package net.sf.anathema.character.abyssal;
import net.sf.anathema.character.abyssal.caste.AbyssalCaste;
import net.sf.anathema.character.abyssal.resonance.AbyssalResonanceModelFactory;
import net.sf.anathema.character.abyssal.resonance.AbyssalResonanceParser;
import net.sf.anathema.character.abyssal.resonance.AbyssalResonancePersisterFactory;
import net.sf.anathema.character.abyssal.resonance.AbyssalResonanceTemplate;
import net.sf.anathema.character.abyssal.resonance.AbyssalResonanceViewFactory;
import net.sf.anathema.character.generic.backgrounds.IBackgroundTemplate;
import net.sf.anathema.character.generic.framework.ICharacterGenerics;
import net.sf.anathema.character.generic.framework.additionaltemplate.IAdditionalViewFactory;
import net.sf.anathema.character.generic.framework.additionaltemplate.model.IAdditionalModelFactory;
import net.sf.anathema.character.generic.framework.additionaltemplate.persistence.IAdditionalPersisterFactory;
import net.sf.anathema.character.generic.framework.module.CharacterModule;
import net.sf.anathema.character.generic.framework.module.NullObjectCharacterModuleAdapter;
import net.sf.anathema.character.generic.impl.backgrounds.CharacterTypeBackgroundTemplate;
import net.sf.anathema.character.generic.impl.backgrounds.TemplateTypeBackgroundTemplate;
import net.sf.anathema.character.generic.impl.caste.CasteCollection;
import net.sf.anathema.character.generic.template.TemplateType;
import net.sf.anathema.lib.registry.IIdentificateRegistry;
import net.sf.anathema.lib.registry.IRegistry;
import net.sf.anathema.lib.util.Identificate;
import static net.sf.anathema.character.generic.type.CharacterType.ABYSSAL;
@CharacterModule
public class AbyssalCharacterModule extends NullObjectCharacterModuleAdapter {
@SuppressWarnings("unused")
private static final TemplateType abyssalTemplateType = new TemplateType(ABYSSAL);
private static final TemplateType loyalAbyssalTemplateType = new TemplateType(ABYSSAL,
new Identificate("default")); //$NON-NLS-1$
@SuppressWarnings("unused")
private static final TemplateType renegadeAbyssalTemplateType = new TemplateType(ABYSSAL,
new Identificate("RenegadeAbyssal")); //$NON-NLS-1$
@SuppressWarnings("unused")
public static final String BACKGROUND_ID_ABYSSAL_COMMAND = "AbyssalCommand"; //$NON-NLS-1$
public static final String BACKGROUND_ID_LIEGE = "Liege"; //$NON-NLS-1$
public static final String BACKGROUND_ID_SPIES = "Spies"; //$NON-NLS-1$
public static final String BACKGROUND_ID_UNDERWORLD_MANSE = "UnderworldManse"; //$NON-NLS-1$
public static final String BACKGROUND_ID_WHISPERS = "Whispers"; //$NON-NLS-1$
@Override
public void registerCommonData(ICharacterGenerics characterGenerics) {
characterGenerics.getAdditionalTemplateParserRegistry().register(AbyssalResonanceTemplate.ID,
new AbyssalResonanceParser());
characterGenerics.getCasteCollectionRegistry().register(ABYSSAL, new CasteCollection(AbyssalCaste.values()));
}
@Override
public void addCharacterTemplates(ICharacterGenerics characterGenerics) {
registerParsedTemplate(characterGenerics, "template/LoyalAbyssal2nd.template", "moep_Abyssals_"); //$NON-NLS-1$
registerParsedTemplate(characterGenerics, "template/RenegadeAbyssal2nd.template", "moep_Abyssals_"); //$NON-NLS-1$
}
@Override
public void addBackgroundTemplates(ICharacterGenerics generics) {
IIdentificateRegistry<IBackgroundTemplate> backgroundRegistry = generics.getBackgroundRegistry();
- backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_ABYSSAL_COMMAND, loyalAbyssalTemplateType));
+ backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_ABYSSAL_COMMAND, loyalAbyssalTemplateType));
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_LIEGE, loyalAbyssalTemplateType));
- backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_SPIES, loyalAbyssalTemplateType));
- backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_UNDERWORLD_MANSE, loyalAbyssalTemplateType));
+ backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_SPIES, loyalAbyssalTemplateType));
+ backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_UNDERWORLD_MANSE, loyalAbyssalTemplateType));
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_WHISPERS, ABYSSAL));
}
@Override
public void addAdditionalTemplateData(ICharacterGenerics characterGenerics) {
IRegistry<String, IAdditionalModelFactory> additionalModelFactoryRegistry = characterGenerics.getAdditionalModelFactoryRegistry();
String templateId = AbyssalResonanceTemplate.ID;
additionalModelFactoryRegistry.register(templateId, new AbyssalResonanceModelFactory());
IRegistry<String, IAdditionalViewFactory> additionalViewFactoryRegistry = characterGenerics.getAdditionalViewFactoryRegistry();
additionalViewFactoryRegistry.register(templateId, new AbyssalResonanceViewFactory());
IRegistry<String, IAdditionalPersisterFactory> persisterFactory = characterGenerics.getAdditonalPersisterFactoryRegistry();
persisterFactory.register(templateId, new AbyssalResonancePersisterFactory());
}
}
| false | true | public void addBackgroundTemplates(ICharacterGenerics generics) {
IIdentificateRegistry<IBackgroundTemplate> backgroundRegistry = generics.getBackgroundRegistry();
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_ABYSSAL_COMMAND, loyalAbyssalTemplateType));
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_LIEGE, loyalAbyssalTemplateType));
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_SPIES, loyalAbyssalTemplateType));
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_UNDERWORLD_MANSE, loyalAbyssalTemplateType));
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_WHISPERS, ABYSSAL));
}
| public void addBackgroundTemplates(ICharacterGenerics generics) {
IIdentificateRegistry<IBackgroundTemplate> backgroundRegistry = generics.getBackgroundRegistry();
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_ABYSSAL_COMMAND, loyalAbyssalTemplateType));
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_LIEGE, loyalAbyssalTemplateType));
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_SPIES, loyalAbyssalTemplateType));
backgroundRegistry.add(new TemplateTypeBackgroundTemplate(BACKGROUND_ID_UNDERWORLD_MANSE, loyalAbyssalTemplateType));
backgroundRegistry.add(new CharacterTypeBackgroundTemplate(BACKGROUND_ID_WHISPERS, ABYSSAL));
}
|
diff --git a/trunk/Crux/src/br/com/sysmap/crux/core/rebind/scanner/screen/config/WidgetConfig.java b/trunk/Crux/src/br/com/sysmap/crux/core/rebind/scanner/screen/config/WidgetConfig.java
index 8ed3e0b54..f1e8f0556 100644
--- a/trunk/Crux/src/br/com/sysmap/crux/core/rebind/scanner/screen/config/WidgetConfig.java
+++ b/trunk/Crux/src/br/com/sysmap/crux/core/rebind/scanner/screen/config/WidgetConfig.java
@@ -1,223 +1,226 @@
/*
* Copyright 2009 Sysmap Solutions Software e Consultoria Ltda.
*
* 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 br.com.sysmap.crux.core.rebind.scanner.screen.config;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import br.com.sysmap.crux.core.client.screen.WidgetFactory;
import br.com.sysmap.crux.core.i18n.MessagesFactory;
import br.com.sysmap.crux.core.server.ServerMessages;
import br.com.sysmap.crux.core.server.scan.ClassScanner;
/**
*
* @author Thiago da Rosa de Bustamante
*
*/
public class WidgetConfig
{
private static Map<String, String> config = null;
private static Set<String> lazyWidgets = null;
private static Map<String, String> widgets = null;
private static Map<String, Set<String>> registeredLibraries = null;
private static ServerMessages messages = (ServerMessages)MessagesFactory.getMessages(ServerMessages.class);
private static final Log logger = LogFactory.getLog(WidgetConfig.class);
private static final Lock lock = new ReentrantLock();
/**
*
*/
public static void initialize()
{
if (config != null)
{
return;
}
try
{
lock.lock();
if (config != null)
{
return;
}
initializeWidgetConfig();
}
finally
{
lock.unlock();
}
}
@SuppressWarnings("unchecked")
protected static void initializeWidgetConfig()
{
config = new HashMap<String, String>(100);
widgets = new HashMap<String, String>();
lazyWidgets = new HashSet<String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass.getCanonicalName());
if (annot.lazy())
{
lazyWidgets.add(widgetType);
}
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
- widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
+ if (type instanceof Class)
+ {
+ widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
+ }
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
/**
*
* @param id
* @return
*/
public static String getClientClass(String id)
{
if (config == null)
{
initializeWidgetConfig();
}
return config.get(id);
}
/**
*
* @param library
* @param id
* @return
*/
public static String getClientClass(String library, String id)
{
if (config == null)
{
initializeWidgetConfig();
}
return config.get(library+"_"+id);
}
/**
*
* @return
*/
public static Set<String> getRegisteredLibraries()
{
if (registeredLibraries == null)
{
initializeWidgetConfig();
}
return registeredLibraries.keySet();
}
/**
*
* @param library
* @return
*/
public static Set<String> getRegisteredLibraryFactories(String library)
{
if (registeredLibraries == null)
{
initializeWidgetConfig();
}
return registeredLibraries.get(library);
}
public static String getWidgetType(Class<?> widgetClass)
{
if (widgets == null)
{
initializeWidgetConfig();
}
return widgets.get(widgetClass.getCanonicalName());
}
public static boolean isLazyType(String type)
{
if (lazyWidgets == null)
{
initializeWidgetConfig();
}
return lazyWidgets.contains(type);
}
/**
* @return
*/
public static String getLazyContainerType()
{
if (lazyWidgets == null)
{
initializeWidgetConfig();
}
Iterator<String> lazies = lazyWidgets.iterator();
if (lazies.hasNext())
{
return lazies.next();
}
return null;
}
}
| true | true | protected static void initializeWidgetConfig()
{
config = new HashMap<String, String>(100);
widgets = new HashMap<String, String>();
lazyWidgets = new HashSet<String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass.getCanonicalName());
if (annot.lazy())
{
lazyWidgets.add(widgetType);
}
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
| protected static void initializeWidgetConfig()
{
config = new HashMap<String, String>(100);
widgets = new HashMap<String, String>();
lazyWidgets = new HashSet<String>();
registeredLibraries = new HashMap<String, Set<String>>();
Set<String> factoriesNames = ClassScanner.searchClassesByAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (factoriesNames != null)
{
for (String name : factoriesNames)
{
try
{
Class<? extends WidgetFactory<?>> factoryClass = (Class<? extends WidgetFactory<?>>)Class.forName(name);
br.com.sysmap.crux.core.client.declarative.DeclarativeFactory annot =
factoryClass.getAnnotation(br.com.sysmap.crux.core.client.declarative.DeclarativeFactory.class);
if (!registeredLibraries.containsKey(annot.library()))
{
registeredLibraries.put(annot.library(), new HashSet<String>());
}
registeredLibraries.get(annot.library()).add(annot.id());
String widgetType = annot.library() + "_" + annot.id();
config.put(widgetType, factoryClass.getCanonicalName());
if (annot.lazy())
{
lazyWidgets.add(widgetType);
}
Type type = ((ParameterizedType)factoryClass.getGenericSuperclass()).getActualTypeArguments()[0];
if (type instanceof ParameterizedType)
{
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class)
{
widgets.put(((Class<?>)rawType).getCanonicalName(), widgetType);
}
}
if (type instanceof Class)
{
widgets.put(((Class<?>)type).getCanonicalName(), widgetType);
}
}
catch (ClassNotFoundException e)
{
throw new WidgetConfigException(messages.widgetConfigInitializeError(e.getLocalizedMessage()),e);
}
}
}
if (logger.isInfoEnabled())
{
logger.info(messages.widgetCongigWidgetsRegistered());
}
}
|
diff --git a/src/org/biojavax/bio/seq/io/INSDseqFormat.java b/src/org/biojavax/bio/seq/io/INSDseqFormat.java
index 59c52098c..705ab6a58 100644
--- a/src/org/biojavax/bio/seq/io/INSDseqFormat.java
+++ b/src/org/biojavax/bio/seq/io/INSDseqFormat.java
@@ -1,1499 +1,1499 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojavax.bio.seq.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.io.ParseException;
import org.biojava.bio.seq.io.SeqIOListener;
import org.biojava.bio.seq.io.SymbolTokenization;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.SimpleSymbolList;
import org.biojava.bio.symbol.Symbol;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.utils.ChangeVetoException;
import org.biojava.utils.xml.PrettyXMLWriter;
import org.biojava.utils.xml.XMLWriter;
import org.biojavax.Comment;
import org.biojavax.CrossRef;
import org.biojavax.DocRef;
import org.biojavax.Namespace;
import org.biojavax.Note;
import org.biojavax.RankedCrossRef;
import org.biojavax.RankedDocRef;
import org.biojavax.RichAnnotation;
import org.biojavax.SimpleCrossRef;
import org.biojavax.SimpleDocRef;
import org.biojavax.SimpleRankedCrossRef;
import org.biojavax.SimpleRankedDocRef;
import org.biojavax.SimpleRichAnnotation;
import org.biojavax.RichObjectFactory;
import org.biojavax.SimpleNote;
import org.biojavax.bio.seq.RichFeature;
import org.biojavax.bio.seq.RichLocation;
import org.biojavax.bio.seq.RichSequence;
import org.biojavax.bio.taxa.NCBITaxon;
import org.biojavax.bio.taxa.SimpleNCBITaxon;
import org.biojavax.ontology.ComparableTerm;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Format reader for INSDseq files. This version of INSDseq format will generate
* and write RichSequence objects. Loosely Based on code from the old, deprecated,
* org.biojava.bio.seq.io.GenbankXmlFormat object.
*
* Understands http://www.ebi.ac.uk/embl/Documentation/DTD/INSDSeq_v1.3.dtd.txt
*
* @author Alan Li (code based on his work)
* @author Richard Holland
*/
public class INSDseqFormat implements RichSequenceFormat {
/**
* The name of this format
*/
public static final String INSDSEQ_FORMAT = "INSDseq";
public static final String INSDSEQS_GROUP_TAG = "INSDSet";
public static final String INSDSEQ_TAG = "INSDSeq";
protected static final String LOCUS_TAG = "INSDSeq_locus";
protected static final String LENGTH_TAG = "INSDSeq_length";
protected static final String TOPOLOGY_TAG = "INSDSeq_topology";
protected static final String STRANDED_TAG = "INSDSeq_strandedness";
protected static final String MOLTYPE_TAG = "INSDSeq_moltype";
protected static final String DIVISION_TAG = "INSDSeq_division";
protected static final String UPDATE_DATE_TAG = "INSDSeq_update-date";
protected static final String CREATE_DATE_TAG = "INSDSeq_create-date";
protected static final String DEFINITION_TAG = "INSDSeq_definition";
protected static final String DATABASE_XREF_TAG = "INSDSeq_database-reference";
protected static final String ACCESSION_TAG = "INSDSeq_primary-accession";
protected static final String ACC_VERSION_TAG = "INSDSeq_accession-version";
protected static final String SECONDARY_ACCESSIONS_GROUP_TAG = "INSDSeq_secondary-accessions";
protected static final String SECONDARY_ACCESSION_TAG = "INSDSecondary-accn";
protected static final String KEYWORDS_GROUP_TAG = "INSDSeq_keywords";
protected static final String KEYWORD_TAG = "INSDKeyword";
protected static final String SOURCE_TAG = "INSDSeq_source";
protected static final String ORGANISM_TAG = "INSDSeq_organism";
protected static final String TAXONOMY_TAG = "INSDSeq_taxonomy";
protected static final String REFERENCES_GROUP_TAG = "INSDSeq_references";
protected static final String REFERENCE_TAG = "INSDReference";
protected static final String REFERENCE_LOCATION_TAG = "INSDReference_reference";
protected static final String TITLE_TAG = "INSDReference_title";
protected static final String JOURNAL_TAG = "INSDReference_journal";
protected static final String PUBMED_TAG = "INSDReference_pubmed";
protected static final String MEDLINE_TAG = "INSDReference_medline";
protected static final String REMARK_TAG = "INSDReference_remark";
protected static final String AUTHORS_GROUP_TAG = "INSDReference_authors";
protected static final String AUTHOR_TAG = "INSDAuthor";
protected static final String COMMENT_TAG = "INSDSeq_comment";
protected static final String FEATURES_GROUP_TAG = "INSDSeq_feature-table";
protected static final String FEATURE_TAG = "INSDFeature";
protected static final String FEATURE_KEY_TAG = "INSDFeature_key";
protected static final String FEATURE_LOC_TAG = "INSDFeature_location";
protected static final String FEATUREQUALS_GROUP_TAG = "INSDFeature_quals";
protected static final String FEATUREQUAL_TAG = "INSDQualifier";
protected static final String FEATUREQUAL_NAME_TAG = "INSDQualifier_name";
protected static final String FEATUREQUAL_VALUE_TAG = "INSDQualifier_value";
protected static final String SEQUENCE_TAG = "INSDSeq_sequence";
protected static final String CONTIG_TAG = "INSDSeq_contig";
/**
* Implements some INSDseq-specific terms.
*/
public static class Terms extends RichSequenceFormat.Terms {
private static ComparableTerm INSDSEQ_TERM = null;
/**
* Getter for the INSDseq term
* @return The INSDseq Term
*/
public static ComparableTerm getINSDseqTerm() {
if (INSDSEQ_TERM==null) INSDSEQ_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("INSDseq");
return INSDSEQ_TERM;
}
}
/**
* {@inheritDoc}
*/
public int getLineWidth() {
return 0;
}
/**
* {@inheritDoc}
*/
public void setLineWidth(int width) {
if (width!=0) throw new IllegalArgumentException("XML files don't have widths");
}
private boolean elideSymbols = false;
/**
* {@inheritDoc}
*/
public boolean getElideSymbols() {
return elideSymbols;
}
/**
* {@inheritDoc}
*/
public void setElideSymbols(boolean elideSymbols) {
this.elideSymbols = elideSymbols;
}
/**
* {@inheritDoc}
*/
public boolean readSequence(BufferedReader reader,
SymbolTokenization symParser,
SeqIOListener listener)
throws IllegalSymbolException, IOException, ParseException {
if (!(listener instanceof RichSeqIOListener)) throw new IllegalArgumentException("Only accepting RichSeqIOListeners today");
return this.readRichSequence(reader,symParser,(RichSeqIOListener)listener,null);
}
// contains all the sequences from the file
private List sequenceBuffer = null;
private Iterator seqBufferIterator = null;
/**
* {@inheritDoc}
* NOTE: This reads the whole XML file and parses it into an internal
* buffer, from which sequences are read by subsequent calls to this
* method.
*/
public boolean readRichSequence(BufferedReader reader,
SymbolTokenization symParser,
RichSeqIOListener rlistener,
Namespace ns)
throws IllegalSymbolException, IOException, ParseException {
if (this.sequenceBuffer==null) {
// load the whole lot into a buffer for now
this.sequenceBuffer = new ArrayList();
SAXParser m_xmlParser;
INSDseqHandler m_handler;
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
try {
m_xmlParser = factory.newSAXParser();
} catch(ParserConfigurationException ex) {
throw new ParseException(ex);
} catch(SAXException ex) {
throw new ParseException(ex);
}
InputSource source = new InputSource(reader);
m_handler = new INSDseqHandler(this.sequenceBuffer);
try {
m_xmlParser.parse(source, m_handler);
} catch(SAXException ex) {
throw new ParseException(ex);
}
this.seqBufferIterator = sequenceBuffer.iterator();
}
// read the next sequence
if (this.seqBufferIterator.hasNext()) this.readRichSequence((INSDseq)seqBufferIterator.next(),symParser,rlistener,ns);
// return true if there are more in our buffer
return this.seqBufferIterator.hasNext();
}
// converts an INSDseq object into an actual RichSequence object
private void readRichSequence(INSDseq input,
SymbolTokenization symParser,
RichSeqIOListener rlistener,
Namespace ns) throws IllegalSymbolException, ParseException {
if (input.getContig()!=null) throw new ParseException("Cannot handle contigs yet");
rlistener.startSequence();
NCBITaxon tax = null;
String organism = null;
String accession = null;
if (ns==null) ns=RichObjectFactory.getDefaultNamespace();
rlistener.setNamespace(ns);
// process in same order as if writing sequence to file
rlistener.setName(input.getLocus().trim());
if (input.getPrimaryAccession()!=null) {
accession = input.getPrimaryAccession().trim();
rlistener.setAccession(accession);
}
if (input.getAccessionVersion()!=null) {
String parts[] = input.getAccessionVersion().trim().split("\\.");
accession = parts[0];
rlistener.setAccession(accession);
if (parts.length>1) rlistener.setVersion(Integer.parseInt(parts[1]));
}
if (!input.getSecondaryAccessions().isEmpty()) {
for (Iterator i = input.getSecondaryAccessions().iterator(); i.hasNext();) {
rlistener.addSequenceProperty(Terms.getAccessionTerm(),((String)i.next()).trim());
}
}
rlistener.setDivision(input.getDivision().trim());
rlistener.addSequenceProperty(Terms.getMolTypeTerm(),input.getMoltype().trim());
rlistener.addSequenceProperty(Terms.getModificationTerm(),input.getUpdateDate().trim());
if (input.getStrandedness()!=null) rlistener.addSequenceProperty(Terms.getStrandedTerm(),input.getStrandedness().trim());
if (input.getTopology()!=null && "circular".equals(input.getTopology().trim())) rlistener.setCircular(true);
if (input.getDefinition()!=null) rlistener.setDescription(input.getDefinition().trim());
if (!input.getKeywords().isEmpty()) {
for (Iterator i = input.getKeywords().iterator(); i.hasNext();) {
rlistener.addSequenceProperty(Terms.getKeywordsTerm(), ((String)i.next()).trim());
}
}
if (input.getComment()!=null) rlistener.setComment(input.getComment().trim());
if (input.getDatabaseXref()!=null) {
// database_identifier; primary_identifier; secondary_identifier....
String[] parts = input.getDatabaseXref().split(";");
// construct a DBXREF out of the dbname part[0] and accession part[1]
CrossRef crossRef = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{parts[0].trim(),parts[1].trim()});
// assign remaining bits of info as annotations
for (int j = 2; j < parts.length; j++) {
Note note = new SimpleNote(Terms.getIdentifierTerm(),parts[j].trim(),j);
try {
((RichAnnotation)crossRef.getAnnotation()).addNote(note);
} catch (ChangeVetoException ce) {
ParseException pe = new ParseException("Could not annotate identifier terms");
pe.initCause(ce);
throw pe;
}
}
RankedCrossRef rcrossRef = new SimpleRankedCrossRef(crossRef, 1);
rlistener.setRankedCrossRef(rcrossRef);
}
if (!input.getReferences().isEmpty()) {
for (Iterator i = input.getReferences().iterator(); i.hasNext();) {
INSDseqRef r = (INSDseqRef)i.next();
// first line of section has rank and location
int ref_rank;
int ref_start = -999;
int ref_end = -999;
String ref = r.getLocation();
String regex = "^(\\d+)\\s*(\\(bases\\s+(\\d+)\\s+to\\s+(\\d+)\\)|\\(sites\\))?";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(ref);
if (m.matches()) {
ref_rank = Integer.parseInt(m.group(1));
if(m.group(2) != null){
if (m.group(3)!= null)
ref_start = Integer.parseInt(m.group(3));
if(m.group(4) != null)
ref_end = Integer.parseInt(m.group(4));
}
} else {
throw new ParseException("Bad reference line found: "+ref);
}
// rest can be in any order
String authors = "";
for (Iterator j = r.getAuthors().iterator(); j.hasNext();) {
authors+=(String)j.next();
if (j.hasNext()) authors+=", ";
}
String title = r.getTitle();
String journal = r.getJournal();
String medline = r.getMedline();
String pubmed = r.getPubmed();
String remark = r.getRemark();
// create the pubmed crossref and assign to the bioentry
CrossRef pcr = null;
if (pubmed!=null) {
pcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{Terms.PUBMED_KEY, pubmed});
RankedCrossRef rpcr = new SimpleRankedCrossRef(pcr, 0);
rlistener.setRankedCrossRef(rpcr);
}
// create the medline crossref and assign to the bioentry
CrossRef mcr = null;
if (medline!=null) {
mcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{Terms.MEDLINE_KEY, medline});
RankedCrossRef rmcr = new SimpleRankedCrossRef(mcr, 0);
rlistener.setRankedCrossRef(rmcr);
}
// create the docref object
try {
DocRef dr = (DocRef)RichObjectFactory.getObject(SimpleDocRef.class,new Object[]{authors,journal});
if (title!=null) dr.setTitle(title);
// assign either the pubmed or medline to the docref - medline gets priority
if (mcr!=null) dr.setCrossref(mcr);
else if (pcr!=null) dr.setCrossref(pcr);
// assign the remarks
dr.setRemark(remark);
// assign the docref to the bioentry
RankedDocRef rdr = new SimpleRankedDocRef(dr,
(ref_start != -999 ? new Integer(ref_start) : null),
(ref_end != -999 ? new Integer(ref_end) : null),
ref_rank);
rlistener.setRankedDocRef(rdr);
} catch (ChangeVetoException e) {
throw new ParseException(e);
}
}
}
if (!input.getFeatures().isEmpty()) {
for (Iterator i = input.getFeatures().iterator(); i.hasNext();) {
INSDseqFeat f = (INSDseqFeat)i.next();
// start next one, with lots of lovely info in it
RichFeature.Template templ = new RichFeature.Template();
templ.annotation = new SimpleRichAnnotation();
templ.sourceTerm = Terms.getINSDseqTerm();
templ.typeTerm = RichObjectFactory.getDefaultOntology().getOrCreateTerm(f.getKey());
templ.featureRelationshipSet = new TreeSet();
templ.rankedCrossRefs = new TreeSet();
String tidyLocStr = f.getLocation().replaceAll("\\s+","");
templ.location = GenbankLocationParser.parseLocation(ns, accession, tidyLocStr);
rlistener.startFeature(templ);
for (Iterator j = f.getQualifiers().iterator(); j.hasNext();) {
INSDseqFeatQual q = (INSDseqFeatQual)j.next();
String key = q.getName();
String val = q.getValue();
if (key.equals("db_xref")) {
String regex = "^(\\S+?):(\\S+)$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(val);
if (m.matches()) {
String dbname = m.group(1);
String raccession = m.group(2);
if (dbname.equals("taxon")) {
// Set the Taxon instead of a dbxref
tax = (NCBITaxon)RichObjectFactory.getObject(SimpleNCBITaxon.class, new Object[]{Integer.valueOf(raccession)});
rlistener.setTaxon(tax);
try {
if (organism!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism);
} catch (ChangeVetoException e) {
throw new ParseException(e);
}
} else {
try {
CrossRef cr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{dbname, raccession});
RankedCrossRef rcr = new SimpleRankedCrossRef(cr, 0);
rlistener.getCurrentFeature().addRankedCrossRef(rcr);
} catch (ChangeVetoException e) {
throw new ParseException(e);
}
}
} else {
throw new ParseException("Bad dbxref found: "+val);
}
} else if (key.equals("organism")) {
try {
organism = val;
if (tax!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism);
} catch (ChangeVetoException e) {
throw new ParseException(e);
}
} else {
if (key.equals("translation")) {
// strip spaces from sequence
val = val.replaceAll("\\s+","");
}
rlistener.addFeatureProperty(RichObjectFactory.getDefaultOntology().getOrCreateTerm(key),val);
}
}
rlistener.endFeature();
}
}
if (input.getSequence()!=null) {
try {
SymbolList sl = new SimpleSymbolList(symParser,
input.getSequence().trim().replaceAll("\\s+","").replaceAll("[\\.|~]","-"));
rlistener.addSymbols(symParser.getAlphabet(),
(Symbol[])(sl.toList().toArray(new Symbol[0])),
0, sl.length());
} catch (Exception e) {
throw new ParseException(e);
}
}
rlistener.endSequence();
}
/**
* {@inheritDoc}
*/
public void writeSequence(Sequence seq, PrintStream os) throws IOException {
this.writeSequence(seq, getDefaultFormat(), os, null);
}
/**
* {@inheritDoc}
*/
public void writeSequence(Sequence seq, String format, PrintStream os) throws IOException {
this.writeSequence(seq, format, os, null);
}
/**
* {@inheritDoc}
* Namespace is ignored as INSDseq has no concept of it.
*/
public void writeSequence(Sequence seq, PrintStream os, Namespace ns) throws IOException {
this.writeSequence(seq, getDefaultFormat(), os, ns);
}
/**
* {@inheritDoc}
* Namespace is ignored as INSDseq has no concept of it.
*/
public void writeSequence(Sequence seq, String format, PrintStream os, Namespace ns) throws IOException {
// INSDseq only really - others are treated identically for now
if (!(
format.equalsIgnoreCase(INSDSEQ_FORMAT)
))
throw new IllegalArgumentException("Unknown format: "+format);
RichSequence rs;
try {
if (seq instanceof RichSequence) rs = (RichSequence)seq;
else rs = RichSequence.Tools.enrich(seq);
} catch (ChangeVetoException e) {
IOException e2 = new IOException("Unable to enrich sequence");
e2.initCause(e);
throw e2;
}
SymbolTokenization tok;
try {
tok = rs.getAlphabet().getTokenization("token");
} catch (Exception e) {
throw new RuntimeException("Unable to get alphabet tokenizer",e);
}
Set notes = rs.getNoteSet();
List accessions = new ArrayList();
List kws = new ArrayList();
String stranded = null;
String mdat = null;
String moltype = rs.getAlphabet().getName();
for (Iterator i = notes.iterator(); i.hasNext();) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getStrandedTerm())) stranded=n.getValue();
else if (n.getTerm().equals(Terms.getModificationTerm())) mdat=n.getValue();
else if (n.getTerm().equals(Terms.getMolTypeTerm())) moltype=n.getValue();
else if (n.getTerm().equals(Terms.getAccessionTerm())) accessions.add(n.getValue());
else if (n.getTerm().equals(Terms.getKeywordsTerm())) kws.add(n.getValue());
}
// make an XML writer
PrintWriter pw = new PrintWriter(os);
XMLWriter xml = new PrettyXMLWriter(pw);
xml.printRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml.printRaw("<!DOCTYPE INSDSeq PUBLIC \"-//EMBL-EBI//INSD INSDSeq/EN\" \"http://www.ebi.ac.uk/dtd/INSD_INSDSeq.dtd\">");
// send it events based on contents of sequence object
xml.openTag(INSDSEQS_GROUP_TAG);
xml.openTag(INSDSEQ_TAG);
xml.openTag(LOCUS_TAG);
xml.print(rs.getName());
xml.closeTag(LOCUS_TAG);
xml.openTag(LENGTH_TAG);
xml.print(""+rs.length());
xml.closeTag(LENGTH_TAG);
if (stranded!=null) {
xml.openTag(STRANDED_TAG);
xml.print(stranded);
xml.closeTag(STRANDED_TAG);
}
if (moltype!=null) {
xml.openTag(MOLTYPE_TAG);
xml.print(moltype);
xml.closeTag(MOLTYPE_TAG);
}
xml.openTag(TOPOLOGY_TAG);
if (rs.getCircular()) xml.print("circular");
else xml.print("linear");
xml.closeTag(TOPOLOGY_TAG);
if (rs.getDivision()!=null) {
xml.openTag(DIVISION_TAG);
xml.print(rs.getDivision());
xml.closeTag(DIVISION_TAG);
}
if (mdat!=null) {
xml.openTag(UPDATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(UPDATE_DATE_TAG);
xml.openTag(CREATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(CREATE_DATE_TAG);
}
if (rs.getDescription()!=null) {
xml.openTag(DEFINITION_TAG);
xml.print(rs.getDescription());
xml.closeTag(DEFINITION_TAG);
}
xml.openTag(ACC_VERSION_TAG);
xml.print(rs.getAccession()+"."+rs.getVersion());
xml.closeTag(ACC_VERSION_TAG);
if (!accessions.isEmpty()) {
xml.openTag(SECONDARY_ACCESSIONS_GROUP_TAG);
for (Iterator i = accessions.iterator(); i.hasNext(); ) {
xml.openTag(SECONDARY_ACCESSION_TAG);
xml.print((String)i.next());
xml.closeTag(SECONDARY_ACCESSION_TAG);
}
xml.closeTag(SECONDARY_ACCESSIONS_GROUP_TAG);
}
if (!kws.isEmpty()) {
xml.openTag(KEYWORDS_GROUP_TAG);
for (Iterator i = kws.iterator(); i.hasNext(); ) {
xml.openTag(KEYWORD_TAG);
xml.print((String)i.next());
xml.closeTag(KEYWORD_TAG);
}
xml.closeTag(KEYWORDS_GROUP_TAG);
}
NCBITaxon tax = rs.getTaxon();
if (tax!=null) {
String[] sciNames = (String[])tax.getNames(NCBITaxon.SCIENTIFIC).toArray(new String[0]);
if (sciNames.length>0) {
xml.openTag(SOURCE_TAG);
xml.print(sciNames[0]);
xml.closeTag(SOURCE_TAG);
xml.openTag(ORGANISM_TAG);
xml.print(sciNames[0]);
xml.closeTag(ORGANISM_TAG);
}
}
// references - rank (bases x to y)
if (!rs.getRankedDocRefs().isEmpty()) {
xml.openTag(REFERENCES_GROUP_TAG);
for (Iterator r = rs.getRankedDocRefs().iterator(); r.hasNext();) {
RankedDocRef rdr = (RankedDocRef)r.next();
DocRef d = rdr.getDocumentReference();
Integer rstart = rdr.getStart();
if (rstart==null) rstart = new Integer(1);
Integer rend = rdr.getEnd();
if (rend==null) rend = new Integer(rs.length());
xml.openTag(REFERENCE_LOCATION_TAG);
xml.print(rdr.getRank()+" (bases "+rstart+" to "+rend+")");
xml.closeTag(REFERENCE_LOCATION_TAG);
if (d.getAuthors()!=null) {
xml.openTag(AUTHORS_GROUP_TAG);
- String[] auths = d.getAuthors().split(",");
+ String[] auths = d.getAuthors().split(",\\s+");
for (int i = 0; i < auths.length; i++) {
xml.openTag(AUTHOR_TAG);
xml.print(auths[i].trim());
xml.closeTag(AUTHOR_TAG);
}
xml.closeTag(AUTHORS_GROUP_TAG);
}
xml.openTag(TITLE_TAG);
xml.print(d.getTitle());
xml.closeTag(TITLE_TAG);
xml.openTag(JOURNAL_TAG);
xml.print(d.getLocation());
xml.closeTag(JOURNAL_TAG);
CrossRef c = d.getCrossref();
if (c!=null) {
if (c.getDbname().equals(Terms.PUBMED_KEY)) {
xml.openTag(PUBMED_TAG);
xml.print(c.getAccession());
xml.closeTag(PUBMED_TAG);
} else if (c.getDbname().equals(Terms.MEDLINE_KEY)) {
xml.openTag(MEDLINE_TAG);
xml.print(c.getAccession());
xml.closeTag(MEDLINE_TAG);
}
}
if (d.getRemark()!=null) {
xml.openTag(REMARK_TAG);
xml.print(d.getRemark());
xml.closeTag(REMARK_TAG);
}
}
xml.closeTag(REFERENCES_GROUP_TAG);
}
if (!rs.getComments().isEmpty()) {
xml.openTag(COMMENT_TAG);
for (Iterator i = rs.getComments().iterator(); i.hasNext(); ) xml.println(((Comment)i.next()).getComment());
xml.closeTag(COMMENT_TAG);
}
// db references - only first one is output
if (!rs.getRankedCrossRefs().isEmpty()) {
Iterator r = rs.getRankedCrossRefs().iterator();
r.next();
RankedCrossRef rcr = (RankedCrossRef)r.next();
CrossRef c = rcr.getCrossRef();
Set noteset = c.getNoteSet();
StringBuffer sb = new StringBuffer();
sb.append(c.getDbname().toUpperCase());
sb.append("; ");
sb.append(c.getAccession());
boolean hasSecondary = false;
for (Iterator i = noteset.iterator(); i.hasNext(); ) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getIdentifierTerm())) {
sb.append("; ");
sb.append(n.getValue());
hasSecondary = true;
}
}
if (!hasSecondary) sb.append("; -");
xml.openTag(DATABASE_XREF_TAG);
xml.print(sb.toString());
xml.closeTag(DATABASE_XREF_TAG);
}
if (!rs.getFeatureSet().isEmpty()) {
xml.openTag(FEATURES_GROUP_TAG);
for (Iterator i = rs.getFeatureSet().iterator(); i.hasNext(); ) {
RichFeature f = (RichFeature)i.next();
xml.openTag(FEATURE_TAG);
xml.openTag(FEATURE_KEY_TAG);
xml.print(f.getTypeTerm().getName());
xml.closeTag(FEATURE_KEY_TAG);
xml.openTag(FEATURE_LOC_TAG);
xml.print(GenbankLocationParser.writeLocation((RichLocation)f.getLocation()));
xml.closeTag(FEATURE_LOC_TAG);
xml.openTag(FEATUREQUALS_GROUP_TAG);
for (Iterator j = f.getNoteSet().iterator(); j.hasNext();) {
Note n = (Note)j.next();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print(""+n.getTerm().getName());
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(n.getValue());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in to source feature only db_xref="taxon:xyz" where present
if (f.getType().equals("source") && tax!=null) {
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print("taxon:"+tax.getNCBITaxID());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in other dbxrefs where present
for (Iterator j = f.getRankedCrossRefs().iterator(); j.hasNext();) {
RankedCrossRef rcr = (RankedCrossRef)j.next();
CrossRef cr = rcr.getCrossRef();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(cr.getDbname()+":"+cr.getAccession());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
xml.closeTag(FEATUREQUALS_GROUP_TAG);
xml.closeTag(FEATURE_TAG);
}
xml.closeTag(FEATURES_GROUP_TAG);
}
xml.openTag(SEQUENCE_TAG);
xml.print(rs.seqString());
xml.closeTag(SEQUENCE_TAG);
xml.closeTag(INSDSEQ_TAG);
xml.closeTag(INSDSEQS_GROUP_TAG);
pw.flush();
}
/**
* {@inheritDoc}
*/
public String getDefaultFormat() {
return INSDSEQ_FORMAT;
}
// SAX event handler for parsing http://www.ebi.ac.uk/embl/Documentation/DTD/INSDSeq_v1.3.dtd.txt
private class INSDseqHandler extends DefaultHandler {
private INSDseq m_currentSequence;
private List m_sequences;
private StringBuffer m_currentString;
// construct a new handler that will populate the given list of sequences
private INSDseqHandler(List m_sequences) {
this.m_sequences = m_sequences;
this.m_currentString = new StringBuffer();
}
// process an opening tag
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (qName.equals(INSDSEQ_TAG)) {
this.m_currentSequence = new INSDseq();
this.m_sequences.add(this.m_currentSequence);
} else if (qName.equals(REFERENCE_TAG))
this.m_currentSequence.startReference();
else if (qName.equals(FEATURE_TAG))
this.m_currentSequence.startFeature();
else if (qName.equals(FEATUREQUAL_TAG))
this.m_currentSequence.getCurrentFeature().startQualifier();
}
// process a closing tag - we will have read the text already
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals(LOCUS_TAG))
this.m_currentSequence.setLocus(this.m_currentString.toString().trim());
else if (qName.equals(STRANDED_TAG))
this.m_currentSequence.setStrandedness(this.m_currentString.toString().trim());
else if (qName.equals(MOLTYPE_TAG))
this.m_currentSequence.setMoltype(this.m_currentString.toString().trim());
else if (qName.equals(TOPOLOGY_TAG))
this.m_currentSequence.setTopology(this.m_currentString.toString().trim());
else if (qName.equals(DIVISION_TAG))
this.m_currentSequence.setDivision(this.m_currentString.toString().trim());
else if (qName.equals(UPDATE_DATE_TAG))
this.m_currentSequence.setUpdateDate(this.m_currentString.toString().trim());
else if (qName.equals(DEFINITION_TAG))
this.m_currentSequence.setDefinition(this.m_currentString.toString().trim());
else if (qName.equals(ACCESSION_TAG))
this.m_currentSequence.setPrimaryAccession(this.m_currentString.toString().trim());
else if (qName.equals(ACC_VERSION_TAG))
this.m_currentSequence.setAccessionVersion(this.m_currentString.toString().trim());
else if (qName.equals(SECONDARY_ACCESSION_TAG))
this.m_currentSequence.addSecondaryAccession(this.m_currentString.toString().trim());
else if (qName.equals(KEYWORD_TAG))
this.m_currentSequence.addKeyword(this.m_currentString.toString().trim());
else if (qName.equals(COMMENT_TAG))
this.m_currentSequence.setComment(this.m_currentString.toString().trim());
else if (qName.equals(DATABASE_XREF_TAG))
this.m_currentSequence.setDatabaseXref(this.m_currentString.toString().trim());
else if (qName.equals(SEQUENCE_TAG))
this.m_currentSequence.setSequence(this.m_currentString.toString().trim());
else if (qName.equals(CONTIG_TAG))
this.m_currentSequence.setContig(this.m_currentString.toString().trim());
else if (qName.equals(REFERENCE_LOCATION_TAG))
this.m_currentSequence.getCurrentReference().setLocation(this.m_currentString.toString().trim());
else if (qName.equals(AUTHOR_TAG))
this.m_currentSequence.getCurrentReference().addAuthor(this.m_currentString.toString().trim());
else if (qName.equals(TITLE_TAG))
this.m_currentSequence.getCurrentReference().setTitle(this.m_currentString.toString().trim());
else if (qName.equals(JOURNAL_TAG))
this.m_currentSequence.getCurrentReference().setJournal(this.m_currentString.toString().trim());
else if (qName.equals(MEDLINE_TAG))
this.m_currentSequence.getCurrentReference().setMedline(this.m_currentString.toString().trim());
else if (qName.equals(PUBMED_TAG))
this.m_currentSequence.getCurrentReference().setPubmed(this.m_currentString.toString().trim());
else if (qName.equals(REMARK_TAG))
this.m_currentSequence.getCurrentReference().setRemark(this.m_currentString.toString().trim());
else if (qName.equals(FEATURE_KEY_TAG))
this.m_currentSequence.getCurrentFeature().setKey(this.m_currentString.toString().trim());
else if (qName.equals(FEATURE_LOC_TAG))
this.m_currentSequence.getCurrentFeature().setLocation(this.m_currentString.toString().trim());
else if (qName.equals(FEATUREQUAL_NAME_TAG))
this.m_currentSequence.getCurrentFeature().getCurrentQualifier().setName(this.m_currentString.toString().trim());
else if (qName.equals(FEATUREQUAL_VALUE_TAG))
this.m_currentSequence.getCurrentFeature().getCurrentQualifier().setValue(this.m_currentString.toString().trim());
// drop old string
this.m_currentString.setLength(0);
}
// process text inside tags
public void characters(char[] ch, int start, int length) {
this.m_currentString.append(ch, start, length);
}
// return the set of sequences found
public List getSequences() {
return this.m_sequences;
}
}
// stores a sequence
private class INSDseq {
private List refs = new ArrayList();
private INSDseqRef ref = null;
private List feats = new ArrayList();
private INSDseqFeat feat = null;
public void startReference() {
this.ref = new INSDseqRef();
this.refs.add(this.ref);
}
public List getReferences() {
return this.refs;
}
public INSDseqRef getCurrentReference() {
return this.ref;
}
public void startFeature() {
this.feat = new INSDseqFeat();
this.feats.add(this.feat);
}
public List getFeatures() {
return this.feats;
}
public INSDseqFeat getCurrentFeature() {
return this.feat;
}
/**
* Holds value of property locus.
*/
private String locus;
/**
* Getter for property locus.
* @return Value of property locus.
*/
public String getLocus() {
return this.locus;
}
/**
* Setter for property locus.
* @param locus New value of property locus.
*/
public void setLocus(String locus) {
this.locus = locus;
}
/**
* Holds value of property strandedness.
*/
private String strandedness;
/**
* Getter for property strandedness.
* @return Value of property strandedness.
*/
public String getStrandedness() {
return this.strandedness;
}
/**
* Setter for property strandedness.
* @param strandedness New value of property strandedness.
*/
public void setStrandedness(String strandedness) {
this.strandedness = strandedness;
}
/**
* Holds value of property moltype.
*/
private String moltype;
/**
* Getter for property moltype.
* @return Value of property moltype.
*/
public String getMoltype() {
return this.moltype;
}
/**
* Setter for property moltype.
* @param moltype New value of property moltype.
*/
public void setMoltype(String moltype) {
this.moltype = moltype;
}
/**
* Holds value of property topology.
*/
private String topology;
/**
* Getter for property topology.
* @return Value of property topology.
*/
public String getTopology() {
return this.topology;
}
/**
* Setter for property topology.
* @param topology New value of property topology.
*/
public void setTopology(String topology) {
this.topology = topology;
}
/**
* Holds value of property division.
*/
private String division;
/**
* Getter for property division.
* @return Value of property division.
*/
public String getDivision() {
return this.division;
}
/**
* Setter for property division.
* @param division New value of property division.
*/
public void setDivision(String division) {
this.division = division;
}
/**
* Holds value of property updateDate.
*/
private String updateDate;
/**
* Getter for property updateDate.
* @return Value of property updateDate.
*/
public String getUpdateDate() {
return this.updateDate;
}
/**
* Setter for property updateDate.
* @param updateDate New value of property updateDate.
*/
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
/**
* Holds value of property definition.
*/
private String definition;
/**
* Getter for property definition.
* @return Value of property definition.
*/
public String getDefinition() {
return this.definition;
}
/**
* Setter for property definition.
* @param definition New value of property definition.
*/
public void setDefinition(String definition) {
this.definition = definition;
}
/**
* Holds value of property primaryAccession.
*/
private String primaryAccession;
/**
* Getter for property primaryAccession.
* @return Value of property primaryAccession.
*/
public String getPrimaryAccession() {
return this.primaryAccession;
}
/**
* Setter for property primaryAccession.
* @param primaryAccession New value of property primaryAccession.
*/
public void setPrimaryAccession(String primaryAccession) {
this.primaryAccession = primaryAccession;
}
/**
* Holds value of property accessionVersion.
*/
private String accessionVersion;
/**
* Getter for property accessionVersion.
* @return Value of property accessionVersion.
*/
public String getAccessionVersion() {
return this.accessionVersion;
}
/**
* Setter for property accessionVersion.
* @param accessionVersion New value of property accessionVersion.
*/
public void setAccessionVersion(String accessionVersion) {
this.accessionVersion = accessionVersion;
}
/**
* Holds value of property comment.
*/
private String comment;
/**
* Getter for property comment.
* @return Value of property comment.
*/
public String getComment() {
return this.comment;
}
/**
* Setter for property comment.
* @param comment New value of property comment.
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Holds value of property sequence.
*/
private String sequence;
/**
* Getter for property sequence.
* @return Value of property sequence.
*/
public String getSequence() {
return this.sequence;
}
/**
* Setter for property sequence.
* @param sequence New value of property sequence.
*/
public void setSequence(String sequence) {
this.sequence = sequence;
}
/**
* Holds value of property contig.
*/
private String contig;
/**
* Getter for property contig.
* @return Value of property contig.
*/
public String getContig() {
return this.contig;
}
/**
* Setter for property contig.
* @param contig New value of property contig.
*/
public void setContig(String contig) {
this.contig = contig;
}
private List secAccs = new ArrayList();
public void addSecondaryAccession(String secAcc) {
this.secAccs.add(secAcc);
}
public List getSecondaryAccessions() {
return this.secAccs;
}
private List kws = new ArrayList();
public void addKeyword(String kw) {
this.kws.add(kw);
}
public List getKeywords() {
return this.kws;
}
/**
* Holds value of property databaseXref.
*/
private String databaseXref;
/**
* Getter for property databaseXref.
* @return Value of property databaseXref.
*/
public String getDatabaseXref() {
return this.databaseXref;
}
/**
* Setter for property databaseXref.
* @param databaseXref New value of property databaseXref.
*/
public void setDatabaseXref(String databaseXref) {
this.databaseXref = databaseXref;
}
}
// stores a feature
private class INSDseqFeat {
private List quals = new ArrayList();
private INSDseqFeatQual qual = null;
public void startQualifier() {
this.qual = new INSDseqFeatQual();
this.quals.add(this.qual);
}
public List getQualifiers() {
return this.quals;
}
public INSDseqFeatQual getCurrentQualifier() {
return this.qual;
}
/**
* Holds value of property key.
*/
private String key;
/**
* Getter for property key.
* @return Value of property key.
*/
public String getKey() {
return this.key;
}
/**
* Setter for property key.
* @param key New value of property key.
*/
public void setKey(String key) {
this.key = key;
}
/**
* Holds value of property location.
*/
private String location;
/**
* Getter for property location.
* @return Value of property location.
*/
public String getLocation() {
return this.location;
}
/**
* Setter for property location.
* @param location New value of property location.
*/
public void setLocation(String location) {
this.location = location;
}
}
// stores a qualifier
private class INSDseqFeatQual {
/**
* Holds value of property name.
*/
private String name;
/**
* Getter for property name.
* @return Value of property name.
*/
public String getName() {
return this.name;
}
/**
* Setter for property name.
* @param name New value of property name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Holds value of property value.
*/
private String value;
/**
* Getter for property value.
* @return Value of property value.
*/
public String getValue() {
return this.value;
}
/**
* Setter for property value.
* @param value New value of property value.
*/
public void setValue(String value) {
this.value = value;
}
}
// stores a reference
private class INSDseqRef {
private List auths = new ArrayList();
public void addAuthor(String auth) {
this.auths.add(auth);
}
public List getAuthors() {
return this.auths;
}
/**
* Holds value of property location.
*/
private String location;
/**
* Getter for property location.
* @return Value of property location.
*/
public String getLocation() {
return this.location;
}
/**
* Setter for property location.
* @param location New value of property location.
*/
public void setLocation(String location) {
this.location = location;
}
/**
* Holds value of property title.
*/
private String title;
/**
* Getter for property title.
* @return Value of property title.
*/
public String getTitle() {
return this.title;
}
/**
* Setter for property title.
* @param title New value of property title.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Holds value of property journal.
*/
private String journal;
/**
* Getter for property journal.
* @return Value of property journal.
*/
public String getJournal() {
return this.journal;
}
/**
* Setter for property journal.
* @param journal New value of property journal.
*/
public void setJournal(String journal) {
this.journal = journal;
}
/**
* Holds value of property medline.
*/
private String medline;
/**
* Getter for property medline.
* @return Value of property medline.
*/
public String getMedline() {
return this.medline;
}
/**
* Setter for property medline.
* @param medline New value of property medline.
*/
public void setMedline(String medline) {
this.medline = medline;
}
/**
* Holds value of property pubmed.
*/
private String pubmed;
/**
* Getter for property pubmed.
* @return Value of property pubmed.
*/
public String getPubmed() {
return this.pubmed;
}
/**
* Setter for property pubmed.
* @param pubmed New value of property pubmed.
*/
public void setPubmed(String pubmed) {
this.pubmed = pubmed;
}
/**
* Holds value of property remark.
*/
private String remark;
/**
* Getter for property remark.
* @return Value of property remark.
*/
public String getRemark() {
return this.remark;
}
/**
* Setter for property remark.
* @param remark New value of property remark.
*/
public void setRemark(String remark) {
this.remark = remark;
}
}
}
| true | true | public void writeSequence(Sequence seq, String format, PrintStream os, Namespace ns) throws IOException {
// INSDseq only really - others are treated identically for now
if (!(
format.equalsIgnoreCase(INSDSEQ_FORMAT)
))
throw new IllegalArgumentException("Unknown format: "+format);
RichSequence rs;
try {
if (seq instanceof RichSequence) rs = (RichSequence)seq;
else rs = RichSequence.Tools.enrich(seq);
} catch (ChangeVetoException e) {
IOException e2 = new IOException("Unable to enrich sequence");
e2.initCause(e);
throw e2;
}
SymbolTokenization tok;
try {
tok = rs.getAlphabet().getTokenization("token");
} catch (Exception e) {
throw new RuntimeException("Unable to get alphabet tokenizer",e);
}
Set notes = rs.getNoteSet();
List accessions = new ArrayList();
List kws = new ArrayList();
String stranded = null;
String mdat = null;
String moltype = rs.getAlphabet().getName();
for (Iterator i = notes.iterator(); i.hasNext();) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getStrandedTerm())) stranded=n.getValue();
else if (n.getTerm().equals(Terms.getModificationTerm())) mdat=n.getValue();
else if (n.getTerm().equals(Terms.getMolTypeTerm())) moltype=n.getValue();
else if (n.getTerm().equals(Terms.getAccessionTerm())) accessions.add(n.getValue());
else if (n.getTerm().equals(Terms.getKeywordsTerm())) kws.add(n.getValue());
}
// make an XML writer
PrintWriter pw = new PrintWriter(os);
XMLWriter xml = new PrettyXMLWriter(pw);
xml.printRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml.printRaw("<!DOCTYPE INSDSeq PUBLIC \"-//EMBL-EBI//INSD INSDSeq/EN\" \"http://www.ebi.ac.uk/dtd/INSD_INSDSeq.dtd\">");
// send it events based on contents of sequence object
xml.openTag(INSDSEQS_GROUP_TAG);
xml.openTag(INSDSEQ_TAG);
xml.openTag(LOCUS_TAG);
xml.print(rs.getName());
xml.closeTag(LOCUS_TAG);
xml.openTag(LENGTH_TAG);
xml.print(""+rs.length());
xml.closeTag(LENGTH_TAG);
if (stranded!=null) {
xml.openTag(STRANDED_TAG);
xml.print(stranded);
xml.closeTag(STRANDED_TAG);
}
if (moltype!=null) {
xml.openTag(MOLTYPE_TAG);
xml.print(moltype);
xml.closeTag(MOLTYPE_TAG);
}
xml.openTag(TOPOLOGY_TAG);
if (rs.getCircular()) xml.print("circular");
else xml.print("linear");
xml.closeTag(TOPOLOGY_TAG);
if (rs.getDivision()!=null) {
xml.openTag(DIVISION_TAG);
xml.print(rs.getDivision());
xml.closeTag(DIVISION_TAG);
}
if (mdat!=null) {
xml.openTag(UPDATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(UPDATE_DATE_TAG);
xml.openTag(CREATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(CREATE_DATE_TAG);
}
if (rs.getDescription()!=null) {
xml.openTag(DEFINITION_TAG);
xml.print(rs.getDescription());
xml.closeTag(DEFINITION_TAG);
}
xml.openTag(ACC_VERSION_TAG);
xml.print(rs.getAccession()+"."+rs.getVersion());
xml.closeTag(ACC_VERSION_TAG);
if (!accessions.isEmpty()) {
xml.openTag(SECONDARY_ACCESSIONS_GROUP_TAG);
for (Iterator i = accessions.iterator(); i.hasNext(); ) {
xml.openTag(SECONDARY_ACCESSION_TAG);
xml.print((String)i.next());
xml.closeTag(SECONDARY_ACCESSION_TAG);
}
xml.closeTag(SECONDARY_ACCESSIONS_GROUP_TAG);
}
if (!kws.isEmpty()) {
xml.openTag(KEYWORDS_GROUP_TAG);
for (Iterator i = kws.iterator(); i.hasNext(); ) {
xml.openTag(KEYWORD_TAG);
xml.print((String)i.next());
xml.closeTag(KEYWORD_TAG);
}
xml.closeTag(KEYWORDS_GROUP_TAG);
}
NCBITaxon tax = rs.getTaxon();
if (tax!=null) {
String[] sciNames = (String[])tax.getNames(NCBITaxon.SCIENTIFIC).toArray(new String[0]);
if (sciNames.length>0) {
xml.openTag(SOURCE_TAG);
xml.print(sciNames[0]);
xml.closeTag(SOURCE_TAG);
xml.openTag(ORGANISM_TAG);
xml.print(sciNames[0]);
xml.closeTag(ORGANISM_TAG);
}
}
// references - rank (bases x to y)
if (!rs.getRankedDocRefs().isEmpty()) {
xml.openTag(REFERENCES_GROUP_TAG);
for (Iterator r = rs.getRankedDocRefs().iterator(); r.hasNext();) {
RankedDocRef rdr = (RankedDocRef)r.next();
DocRef d = rdr.getDocumentReference();
Integer rstart = rdr.getStart();
if (rstart==null) rstart = new Integer(1);
Integer rend = rdr.getEnd();
if (rend==null) rend = new Integer(rs.length());
xml.openTag(REFERENCE_LOCATION_TAG);
xml.print(rdr.getRank()+" (bases "+rstart+" to "+rend+")");
xml.closeTag(REFERENCE_LOCATION_TAG);
if (d.getAuthors()!=null) {
xml.openTag(AUTHORS_GROUP_TAG);
String[] auths = d.getAuthors().split(",");
for (int i = 0; i < auths.length; i++) {
xml.openTag(AUTHOR_TAG);
xml.print(auths[i].trim());
xml.closeTag(AUTHOR_TAG);
}
xml.closeTag(AUTHORS_GROUP_TAG);
}
xml.openTag(TITLE_TAG);
xml.print(d.getTitle());
xml.closeTag(TITLE_TAG);
xml.openTag(JOURNAL_TAG);
xml.print(d.getLocation());
xml.closeTag(JOURNAL_TAG);
CrossRef c = d.getCrossref();
if (c!=null) {
if (c.getDbname().equals(Terms.PUBMED_KEY)) {
xml.openTag(PUBMED_TAG);
xml.print(c.getAccession());
xml.closeTag(PUBMED_TAG);
} else if (c.getDbname().equals(Terms.MEDLINE_KEY)) {
xml.openTag(MEDLINE_TAG);
xml.print(c.getAccession());
xml.closeTag(MEDLINE_TAG);
}
}
if (d.getRemark()!=null) {
xml.openTag(REMARK_TAG);
xml.print(d.getRemark());
xml.closeTag(REMARK_TAG);
}
}
xml.closeTag(REFERENCES_GROUP_TAG);
}
if (!rs.getComments().isEmpty()) {
xml.openTag(COMMENT_TAG);
for (Iterator i = rs.getComments().iterator(); i.hasNext(); ) xml.println(((Comment)i.next()).getComment());
xml.closeTag(COMMENT_TAG);
}
// db references - only first one is output
if (!rs.getRankedCrossRefs().isEmpty()) {
Iterator r = rs.getRankedCrossRefs().iterator();
r.next();
RankedCrossRef rcr = (RankedCrossRef)r.next();
CrossRef c = rcr.getCrossRef();
Set noteset = c.getNoteSet();
StringBuffer sb = new StringBuffer();
sb.append(c.getDbname().toUpperCase());
sb.append("; ");
sb.append(c.getAccession());
boolean hasSecondary = false;
for (Iterator i = noteset.iterator(); i.hasNext(); ) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getIdentifierTerm())) {
sb.append("; ");
sb.append(n.getValue());
hasSecondary = true;
}
}
if (!hasSecondary) sb.append("; -");
xml.openTag(DATABASE_XREF_TAG);
xml.print(sb.toString());
xml.closeTag(DATABASE_XREF_TAG);
}
if (!rs.getFeatureSet().isEmpty()) {
xml.openTag(FEATURES_GROUP_TAG);
for (Iterator i = rs.getFeatureSet().iterator(); i.hasNext(); ) {
RichFeature f = (RichFeature)i.next();
xml.openTag(FEATURE_TAG);
xml.openTag(FEATURE_KEY_TAG);
xml.print(f.getTypeTerm().getName());
xml.closeTag(FEATURE_KEY_TAG);
xml.openTag(FEATURE_LOC_TAG);
xml.print(GenbankLocationParser.writeLocation((RichLocation)f.getLocation()));
xml.closeTag(FEATURE_LOC_TAG);
xml.openTag(FEATUREQUALS_GROUP_TAG);
for (Iterator j = f.getNoteSet().iterator(); j.hasNext();) {
Note n = (Note)j.next();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print(""+n.getTerm().getName());
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(n.getValue());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in to source feature only db_xref="taxon:xyz" where present
if (f.getType().equals("source") && tax!=null) {
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print("taxon:"+tax.getNCBITaxID());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in other dbxrefs where present
for (Iterator j = f.getRankedCrossRefs().iterator(); j.hasNext();) {
RankedCrossRef rcr = (RankedCrossRef)j.next();
CrossRef cr = rcr.getCrossRef();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(cr.getDbname()+":"+cr.getAccession());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
xml.closeTag(FEATUREQUALS_GROUP_TAG);
xml.closeTag(FEATURE_TAG);
}
xml.closeTag(FEATURES_GROUP_TAG);
}
xml.openTag(SEQUENCE_TAG);
xml.print(rs.seqString());
xml.closeTag(SEQUENCE_TAG);
xml.closeTag(INSDSEQ_TAG);
xml.closeTag(INSDSEQS_GROUP_TAG);
pw.flush();
}
| public void writeSequence(Sequence seq, String format, PrintStream os, Namespace ns) throws IOException {
// INSDseq only really - others are treated identically for now
if (!(
format.equalsIgnoreCase(INSDSEQ_FORMAT)
))
throw new IllegalArgumentException("Unknown format: "+format);
RichSequence rs;
try {
if (seq instanceof RichSequence) rs = (RichSequence)seq;
else rs = RichSequence.Tools.enrich(seq);
} catch (ChangeVetoException e) {
IOException e2 = new IOException("Unable to enrich sequence");
e2.initCause(e);
throw e2;
}
SymbolTokenization tok;
try {
tok = rs.getAlphabet().getTokenization("token");
} catch (Exception e) {
throw new RuntimeException("Unable to get alphabet tokenizer",e);
}
Set notes = rs.getNoteSet();
List accessions = new ArrayList();
List kws = new ArrayList();
String stranded = null;
String mdat = null;
String moltype = rs.getAlphabet().getName();
for (Iterator i = notes.iterator(); i.hasNext();) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getStrandedTerm())) stranded=n.getValue();
else if (n.getTerm().equals(Terms.getModificationTerm())) mdat=n.getValue();
else if (n.getTerm().equals(Terms.getMolTypeTerm())) moltype=n.getValue();
else if (n.getTerm().equals(Terms.getAccessionTerm())) accessions.add(n.getValue());
else if (n.getTerm().equals(Terms.getKeywordsTerm())) kws.add(n.getValue());
}
// make an XML writer
PrintWriter pw = new PrintWriter(os);
XMLWriter xml = new PrettyXMLWriter(pw);
xml.printRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml.printRaw("<!DOCTYPE INSDSeq PUBLIC \"-//EMBL-EBI//INSD INSDSeq/EN\" \"http://www.ebi.ac.uk/dtd/INSD_INSDSeq.dtd\">");
// send it events based on contents of sequence object
xml.openTag(INSDSEQS_GROUP_TAG);
xml.openTag(INSDSEQ_TAG);
xml.openTag(LOCUS_TAG);
xml.print(rs.getName());
xml.closeTag(LOCUS_TAG);
xml.openTag(LENGTH_TAG);
xml.print(""+rs.length());
xml.closeTag(LENGTH_TAG);
if (stranded!=null) {
xml.openTag(STRANDED_TAG);
xml.print(stranded);
xml.closeTag(STRANDED_TAG);
}
if (moltype!=null) {
xml.openTag(MOLTYPE_TAG);
xml.print(moltype);
xml.closeTag(MOLTYPE_TAG);
}
xml.openTag(TOPOLOGY_TAG);
if (rs.getCircular()) xml.print("circular");
else xml.print("linear");
xml.closeTag(TOPOLOGY_TAG);
if (rs.getDivision()!=null) {
xml.openTag(DIVISION_TAG);
xml.print(rs.getDivision());
xml.closeTag(DIVISION_TAG);
}
if (mdat!=null) {
xml.openTag(UPDATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(UPDATE_DATE_TAG);
xml.openTag(CREATE_DATE_TAG);
xml.print(mdat);
xml.closeTag(CREATE_DATE_TAG);
}
if (rs.getDescription()!=null) {
xml.openTag(DEFINITION_TAG);
xml.print(rs.getDescription());
xml.closeTag(DEFINITION_TAG);
}
xml.openTag(ACC_VERSION_TAG);
xml.print(rs.getAccession()+"."+rs.getVersion());
xml.closeTag(ACC_VERSION_TAG);
if (!accessions.isEmpty()) {
xml.openTag(SECONDARY_ACCESSIONS_GROUP_TAG);
for (Iterator i = accessions.iterator(); i.hasNext(); ) {
xml.openTag(SECONDARY_ACCESSION_TAG);
xml.print((String)i.next());
xml.closeTag(SECONDARY_ACCESSION_TAG);
}
xml.closeTag(SECONDARY_ACCESSIONS_GROUP_TAG);
}
if (!kws.isEmpty()) {
xml.openTag(KEYWORDS_GROUP_TAG);
for (Iterator i = kws.iterator(); i.hasNext(); ) {
xml.openTag(KEYWORD_TAG);
xml.print((String)i.next());
xml.closeTag(KEYWORD_TAG);
}
xml.closeTag(KEYWORDS_GROUP_TAG);
}
NCBITaxon tax = rs.getTaxon();
if (tax!=null) {
String[] sciNames = (String[])tax.getNames(NCBITaxon.SCIENTIFIC).toArray(new String[0]);
if (sciNames.length>0) {
xml.openTag(SOURCE_TAG);
xml.print(sciNames[0]);
xml.closeTag(SOURCE_TAG);
xml.openTag(ORGANISM_TAG);
xml.print(sciNames[0]);
xml.closeTag(ORGANISM_TAG);
}
}
// references - rank (bases x to y)
if (!rs.getRankedDocRefs().isEmpty()) {
xml.openTag(REFERENCES_GROUP_TAG);
for (Iterator r = rs.getRankedDocRefs().iterator(); r.hasNext();) {
RankedDocRef rdr = (RankedDocRef)r.next();
DocRef d = rdr.getDocumentReference();
Integer rstart = rdr.getStart();
if (rstart==null) rstart = new Integer(1);
Integer rend = rdr.getEnd();
if (rend==null) rend = new Integer(rs.length());
xml.openTag(REFERENCE_LOCATION_TAG);
xml.print(rdr.getRank()+" (bases "+rstart+" to "+rend+")");
xml.closeTag(REFERENCE_LOCATION_TAG);
if (d.getAuthors()!=null) {
xml.openTag(AUTHORS_GROUP_TAG);
String[] auths = d.getAuthors().split(",\\s+");
for (int i = 0; i < auths.length; i++) {
xml.openTag(AUTHOR_TAG);
xml.print(auths[i].trim());
xml.closeTag(AUTHOR_TAG);
}
xml.closeTag(AUTHORS_GROUP_TAG);
}
xml.openTag(TITLE_TAG);
xml.print(d.getTitle());
xml.closeTag(TITLE_TAG);
xml.openTag(JOURNAL_TAG);
xml.print(d.getLocation());
xml.closeTag(JOURNAL_TAG);
CrossRef c = d.getCrossref();
if (c!=null) {
if (c.getDbname().equals(Terms.PUBMED_KEY)) {
xml.openTag(PUBMED_TAG);
xml.print(c.getAccession());
xml.closeTag(PUBMED_TAG);
} else if (c.getDbname().equals(Terms.MEDLINE_KEY)) {
xml.openTag(MEDLINE_TAG);
xml.print(c.getAccession());
xml.closeTag(MEDLINE_TAG);
}
}
if (d.getRemark()!=null) {
xml.openTag(REMARK_TAG);
xml.print(d.getRemark());
xml.closeTag(REMARK_TAG);
}
}
xml.closeTag(REFERENCES_GROUP_TAG);
}
if (!rs.getComments().isEmpty()) {
xml.openTag(COMMENT_TAG);
for (Iterator i = rs.getComments().iterator(); i.hasNext(); ) xml.println(((Comment)i.next()).getComment());
xml.closeTag(COMMENT_TAG);
}
// db references - only first one is output
if (!rs.getRankedCrossRefs().isEmpty()) {
Iterator r = rs.getRankedCrossRefs().iterator();
r.next();
RankedCrossRef rcr = (RankedCrossRef)r.next();
CrossRef c = rcr.getCrossRef();
Set noteset = c.getNoteSet();
StringBuffer sb = new StringBuffer();
sb.append(c.getDbname().toUpperCase());
sb.append("; ");
sb.append(c.getAccession());
boolean hasSecondary = false;
for (Iterator i = noteset.iterator(); i.hasNext(); ) {
Note n = (Note)i.next();
if (n.getTerm().equals(Terms.getIdentifierTerm())) {
sb.append("; ");
sb.append(n.getValue());
hasSecondary = true;
}
}
if (!hasSecondary) sb.append("; -");
xml.openTag(DATABASE_XREF_TAG);
xml.print(sb.toString());
xml.closeTag(DATABASE_XREF_TAG);
}
if (!rs.getFeatureSet().isEmpty()) {
xml.openTag(FEATURES_GROUP_TAG);
for (Iterator i = rs.getFeatureSet().iterator(); i.hasNext(); ) {
RichFeature f = (RichFeature)i.next();
xml.openTag(FEATURE_TAG);
xml.openTag(FEATURE_KEY_TAG);
xml.print(f.getTypeTerm().getName());
xml.closeTag(FEATURE_KEY_TAG);
xml.openTag(FEATURE_LOC_TAG);
xml.print(GenbankLocationParser.writeLocation((RichLocation)f.getLocation()));
xml.closeTag(FEATURE_LOC_TAG);
xml.openTag(FEATUREQUALS_GROUP_TAG);
for (Iterator j = f.getNoteSet().iterator(); j.hasNext();) {
Note n = (Note)j.next();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print(""+n.getTerm().getName());
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(n.getValue());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in to source feature only db_xref="taxon:xyz" where present
if (f.getType().equals("source") && tax!=null) {
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print("taxon:"+tax.getNCBITaxID());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
// add-in other dbxrefs where present
for (Iterator j = f.getRankedCrossRefs().iterator(); j.hasNext();) {
RankedCrossRef rcr = (RankedCrossRef)j.next();
CrossRef cr = rcr.getCrossRef();
xml.openTag(FEATUREQUAL_TAG);
xml.openTag(FEATUREQUAL_NAME_TAG);
xml.print("db_xref");
xml.closeTag(FEATUREQUAL_NAME_TAG);
xml.openTag(FEATUREQUAL_VALUE_TAG);
xml.print(cr.getDbname()+":"+cr.getAccession());
xml.closeTag(FEATUREQUAL_VALUE_TAG);
xml.closeTag(FEATUREQUAL_TAG);
}
xml.closeTag(FEATUREQUALS_GROUP_TAG);
xml.closeTag(FEATURE_TAG);
}
xml.closeTag(FEATURES_GROUP_TAG);
}
xml.openTag(SEQUENCE_TAG);
xml.print(rs.seqString());
xml.closeTag(SEQUENCE_TAG);
xml.closeTag(INSDSEQ_TAG);
xml.closeTag(INSDSEQS_GROUP_TAG);
pw.flush();
}
|
diff --git a/src/org/mozilla/javascript/Parser.java b/src/org/mozilla/javascript/Parser.java
index 224b2bcb..28fa5263 100644
--- a/src/org/mozilla/javascript/Parser.java
+++ b/src/org/mozilla/javascript/Parser.java
@@ -1,1557 +1,1556 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape 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 http://www.mozilla.org/NPL/
*
* 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.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Mike Ang
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.IOException;
/**
* This class implements the JavaScript parser.
*
* It is based on the C source files jsparse.c and jsparse.h
* in the jsref package.
*
* @see TokenStream
*
* @author Mike McCabe
* @author Brendan Eich
*/
class Parser {
public Parser(IRFactory nf) {
this.nf = nf;
}
private void mustMatchToken(TokenStream ts, int toMatch, String messageId)
throws IOException, JavaScriptException
{
int tt;
if ((tt = ts.getToken()) != toMatch) {
reportError(ts, messageId);
ts.ungetToken(tt); // In case the parser decides to continue
}
}
private void reportError(TokenStream ts, String messageId)
throws JavaScriptException
{
this.ok = false;
ts.reportSyntaxError(messageId, null);
/* Throw an exception to unwind the recursive descent parse.
* We use JavaScriptException here even though it is really
* a different use of the exception than it is usually used
* for.
*/
throw new JavaScriptException(messageId);
}
/*
* Build a parse tree from the given TokenStream.
*
* @param ts the TokenStream to parse
*
* @return an Object representing the parsed
* program. If the parse fails, null will be returned. (The
* parse failure will result in a call to the current Context's
* ErrorReporter.)
*/
public Object parse(TokenStream ts)
throws IOException
{
this.ok = true;
sourceTop = 0;
functionNumber = 0;
int tt; // last token from getToken();
int baseLineno = ts.getLineno(); // line number where source starts
/* so we have something to add nodes to until
* we've collected all the source */
Object tempBlock = nf.createLeaf(TokenStream.BLOCK);
while (true) {
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
if (tt <= ts.EOF) {
break;
}
if (tt == ts.FUNCTION) {
try {
nf.addChildToBack(tempBlock, function(ts, false));
} catch (JavaScriptException e) {
this.ok = false;
break;
}
} else {
ts.ungetToken(tt);
nf.addChildToBack(tempBlock, statement(ts));
}
}
if (!this.ok) {
// XXX ts.clearPushback() call here?
return null;
}
Object pn = nf.createScript(tempBlock, ts.getSourceName(),
baseLineno, ts.getLineno(),
sourceToString(0));
return pn;
}
/*
* The C version of this function takes an argument list,
* which doesn't seem to be needed for tree generation...
* it'd only be useful for checking argument hiding, which
* I'm not doing anyway...
*/
private Object parseFunctionBody(TokenStream ts)
throws IOException
{
int oldflags = ts.flags;
ts.flags &= ~(TokenStream.TSF_RETURN_EXPR
| TokenStream.TSF_RETURN_VOID);
ts.flags |= TokenStream.TSF_FUNCTION;
Object pn = nf.createBlock(ts.getLineno());
try {
int tt;
while((tt = ts.peekToken()) > ts.EOF && tt != ts.RC) {
if (tt == TokenStream.FUNCTION) {
ts.getToken();
nf.addChildToBack(pn, function(ts, false));
} else {
nf.addChildToBack(pn, statement(ts));
}
}
} catch (JavaScriptException e) {
this.ok = false;
} finally {
// also in finally block:
// flushNewLines, clearPushback.
ts.flags = oldflags;
}
return pn;
}
private Object function(TokenStream ts, boolean isExpr)
throws IOException, JavaScriptException
{
int baseLineno = ts.getLineno(); // line number where source starts
String name;
Object memberExprNode = null;
if (ts.matchToken(ts.NAME)) {
name = ts.getString();
if (!ts.matchToken(ts.LP)) {
if (Context.getContext().hasFeature
(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME))
{
// Extension to ECMA: if 'function <name>' does not follow
// by '(', assume <name> starts memberExpr
sourceAddString(ts.NAME, name);
Object memberExprHead = nf.createName(name);
name = null;
memberExprNode = memberExprTail(ts, false, memberExprHead);
}
mustMatchToken(ts, ts.LP, "msg.no.paren.parms");
}
}
else if (ts.matchToken(ts.LP)) {
// Anonymous function
name = null;
}
else {
name = null;
if (Context.getContext().hasFeature
(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME))
{
// Note that memberExpr can not start with '(' like
// in (1+2).toString, because 'function (' already
// processed as anonymous function
memberExprNode = memberExpr(ts, false);
}
mustMatchToken(ts, ts.LP, "msg.no.paren.parms");
}
if (memberExprNode != null) {
// transform 'function' <memberExpr> to <memberExpr> = function
// even in the decompilated source
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.NOP);
}
// save a reference to the function in the enclosing source.
sourceAdd((char) ts.FUNCTION);
sourceAdd((char)functionNumber);
++functionNumber;
// Save current source top to restore it on exit not to include
// function to parent source
int savedSourceTop = sourceTop;
int savedFunctionNumber = functionNumber;
Object args;
Object body;
String source;
try {
functionNumber = 0;
// FUNCTION as the first token in a Source means it's a function
// definition, and not a reference.
sourceAdd((char) ts.FUNCTION);
if (name != null) { sourceAddString(ts.NAME, name); }
sourceAdd((char) ts.LP);
args = nf.createLeaf(ts.LP);
if (!ts.matchToken(ts.RP)) {
boolean first = true;
do {
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
mustMatchToken(ts, ts.NAME, "msg.no.parm");
String s = ts.getString();
nf.addChildToBack(args, nf.createName(s));
sourceAddString(ts.NAME, s);
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.parms");
}
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.body");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = parseFunctionBody(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
// skip the last EOL so nested functions work...
// name might be null;
source = sourceToString(savedSourceTop);
}
finally {
sourceTop = savedSourceTop;
functionNumber = savedFunctionNumber;
}
Object pn = nf.createFunction(name, args, body,
ts.getSourceName(),
baseLineno, ts.getLineno(),
source,
isExpr || memberExprNode != null);
if (memberExprNode != null) {
pn = nf.createBinary(ts.ASSIGN, ts.NOP, memberExprNode, pn);
}
// Add EOL but only if function is not part of expression, in which
// case it gets SEMI + EOL from Statement.
if (!isExpr) {
if (memberExprNode != null) {
// Add ';' to make 'function x.f(){}' and 'x.f = function(){}'
// to print the same strings when decompiling
sourceAdd((char)ts.SEMI);
}
sourceAdd((char)ts.EOL);
wellTerminated(ts, ts.FUNCTION);
}
return pn;
}
private Object statements(TokenStream ts)
throws IOException
{
Object pn = nf.createBlock(ts.getLineno());
int tt;
while((tt = ts.peekToken()) > ts.EOF && tt != ts.RC) {
nf.addChildToBack(pn, statement(ts));
}
return pn;
}
private Object condition(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn;
mustMatchToken(ts, ts.LP, "msg.no.paren.cond");
sourceAdd((char)ts.LP);
pn = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.cond");
sourceAdd((char)ts.RP);
// there's a check here in jsparse.c that corrects = to ==
return pn;
}
private boolean wellTerminated(TokenStream ts, int lastExprType)
throws IOException, JavaScriptException
{
int tt = ts.peekTokenSameLine();
if (tt == ts.ERROR) {
return false;
}
if (tt != ts.EOF && tt != ts.EOL
&& tt != ts.SEMI && tt != ts.RC)
{
int version = Context.getContext().getLanguageVersion();
if ((tt == ts.FUNCTION || lastExprType == ts.FUNCTION) &&
(version < Context.VERSION_1_2)) {
/*
* Checking against version < 1.2 and version >= 1.0
* in the above line breaks old javascript, so we keep it
* this way for now... XXX warning needed?
*/
return true;
} else {
reportError(ts, "msg.no.semi.stmt");
}
}
return true;
}
// match a NAME; return null if no match.
private String matchLabel(TokenStream ts)
throws IOException, JavaScriptException
{
int lineno = ts.getLineno();
String label = null;
int tt;
tt = ts.peekTokenSameLine();
if (tt == ts.NAME) {
ts.getToken();
label = ts.getString();
}
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
return label;
}
private Object statement(TokenStream ts)
throws IOException
{
try {
return statementHelper(ts);
} catch (JavaScriptException e) {
// skip to end of statement
int lineno = ts.getLineno();
int t;
do {
t = ts.getToken();
} while (t != TokenStream.SEMI && t != TokenStream.EOL &&
t != TokenStream.EOF && t != TokenStream.ERROR);
return nf.createExprStatement(nf.createName("error"), lineno);
}
}
/**
* Whether the "catch (e: e instanceof Exception) { ... }" syntax
* is implemented.
*/
private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
- int lineno = 0;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
+ int lineno = ts.getLineno();
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
- lineno = ts.getLineno();
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
private Object variables(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = nf.createVariables(ts.getLineno());
boolean first = true;
sourceAdd((char)ts.VAR);
for (;;) {
Object name;
Object init;
mustMatchToken(ts, ts.NAME, "msg.bad.var");
String s = ts.getString();
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
sourceAddString(ts.NAME, s);
name = nf.createName(s);
// omitted check for argument hiding
if (ts.matchToken(ts.ASSIGN)) {
if (ts.getOp() != ts.NOP)
reportError(ts, "msg.bad.var.init");
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.NOP);
init = assignExpr(ts, inForInit);
nf.addChildToBack(name, init);
}
nf.addChildToBack(pn, name);
if (!ts.matchToken(ts.COMMA))
break;
}
return pn;
}
private Object expr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = assignExpr(ts, inForInit);
while (ts.matchToken(ts.COMMA)) {
sourceAdd((char)ts.COMMA);
pn = nf.createBinary(ts.COMMA, pn, assignExpr(ts, inForInit));
}
return pn;
}
private Object assignExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = condExpr(ts, inForInit);
if (ts.matchToken(ts.ASSIGN)) {
// omitted: "invalid assignment left-hand side" check.
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.ASSIGN, ts.getOp(), pn,
assignExpr(ts, inForInit));
}
return pn;
}
private Object condExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object ifTrue;
Object ifFalse;
Object pn = orExpr(ts, inForInit);
if (ts.matchToken(ts.HOOK)) {
sourceAdd((char)ts.HOOK);
ifTrue = assignExpr(ts, false);
mustMatchToken(ts, ts.COLON, "msg.no.colon.cond");
sourceAdd((char)ts.COLON);
ifFalse = assignExpr(ts, inForInit);
return nf.createTernary(pn, ifTrue, ifFalse);
}
return pn;
}
private Object orExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = andExpr(ts, inForInit);
if (ts.matchToken(ts.OR)) {
sourceAdd((char)ts.OR);
pn = nf.createBinary(ts.OR, pn, orExpr(ts, inForInit));
}
return pn;
}
private Object andExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitOrExpr(ts, inForInit);
if (ts.matchToken(ts.AND)) {
sourceAdd((char)ts.AND);
pn = nf.createBinary(ts.AND, pn, andExpr(ts, inForInit));
}
return pn;
}
private Object bitOrExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitXorExpr(ts, inForInit);
while (ts.matchToken(ts.BITOR)) {
sourceAdd((char)ts.BITOR);
pn = nf.createBinary(ts.BITOR, pn, bitXorExpr(ts, inForInit));
}
return pn;
}
private Object bitXorExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitAndExpr(ts, inForInit);
while (ts.matchToken(ts.BITXOR)) {
sourceAdd((char)ts.BITXOR);
pn = nf.createBinary(ts.BITXOR, pn, bitAndExpr(ts, inForInit));
}
return pn;
}
private Object bitAndExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = eqExpr(ts, inForInit);
while (ts.matchToken(ts.BITAND)) {
sourceAdd((char)ts.BITAND);
pn = nf.createBinary(ts.BITAND, pn, eqExpr(ts, inForInit));
}
return pn;
}
private Object eqExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = relExpr(ts, inForInit);
while (ts.matchToken(ts.EQOP)) {
sourceAdd((char)ts.EQOP);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.EQOP, ts.getOp(), pn,
relExpr(ts, inForInit));
}
return pn;
}
private Object relExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = shiftExpr(ts);
while (ts.matchToken(ts.RELOP)) {
int op = ts.getOp();
if (inForInit && op == ts.IN) {
ts.ungetToken(ts.RELOP);
break;
}
sourceAdd((char)ts.RELOP);
sourceAdd((char)op);
pn = nf.createBinary(ts.RELOP, op, pn, shiftExpr(ts));
}
return pn;
}
private Object shiftExpr(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = addExpr(ts);
while (ts.matchToken(ts.SHOP)) {
sourceAdd((char)ts.SHOP);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.getOp(), pn, addExpr(ts));
}
return pn;
}
private Object addExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn = mulExpr(ts);
while ((tt = ts.getToken()) == ts.ADD || tt == ts.SUB) {
sourceAdd((char)tt);
// flushNewLines
pn = nf.createBinary(tt, pn, mulExpr(ts));
}
ts.ungetToken(tt);
return pn;
}
private Object mulExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn = unaryExpr(ts);
while ((tt = ts.peekToken()) == ts.MUL ||
tt == ts.DIV ||
tt == ts.MOD) {
tt = ts.getToken();
sourceAdd((char)tt);
pn = nf.createBinary(tt, pn, unaryExpr(ts));
}
return pn;
}
private Object unaryExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
switch(tt) {
case TokenStream.UNARYOP:
sourceAdd((char)ts.UNARYOP);
sourceAdd((char)ts.getOp());
return nf.createUnary(ts.UNARYOP, ts.getOp(),
unaryExpr(ts));
case TokenStream.ADD:
case TokenStream.SUB:
sourceAdd((char)ts.UNARYOP);
sourceAdd((char)tt);
return nf.createUnary(ts.UNARYOP, tt, unaryExpr(ts));
case TokenStream.INC:
case TokenStream.DEC:
sourceAdd((char)tt);
return nf.createUnary(tt, ts.PRE, memberExpr(ts, true));
case TokenStream.DELPROP:
sourceAdd((char)ts.DELPROP);
return nf.createUnary(ts.DELPROP, unaryExpr(ts));
case TokenStream.ERROR:
break;
default:
ts.ungetToken(tt);
int lineno = ts.getLineno();
Object pn = memberExpr(ts, true);
/* don't look across a newline boundary for a postfix incop.
* the rhino scanner seems to work differently than the js
* scanner here; in js, it works to have the line number check
* precede the peekToken calls. It'd be better if they had
* similar behavior...
*/
int peeked;
if (((peeked = ts.peekToken()) == ts.INC ||
peeked == ts.DEC) &&
ts.getLineno() == lineno)
{
int pf = ts.getToken();
sourceAdd((char)pf);
return nf.createUnary(pf, ts.POST, pn);
}
return pn;
}
return nf.createName("err"); // Only reached on error. Try to continue.
}
private Object argumentList(TokenStream ts, Object listNode)
throws IOException, JavaScriptException
{
boolean matched;
ts.flags |= ts.TSF_REGEXP;
matched = ts.matchToken(ts.RP);
ts.flags &= ~ts.TSF_REGEXP;
if (!matched) {
boolean first = true;
do {
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
nf.addChildToBack(listNode, assignExpr(ts, false));
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RP, "msg.no.paren.arg");
}
sourceAdd((char)ts.RP);
return listNode;
}
private Object memberExpr(TokenStream ts, boolean allowCallSyntax)
throws IOException, JavaScriptException
{
int tt;
Object pn;
/* Check for new expressions. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekToken();
ts.flags &= ~ts.TSF_REGEXP;
if (tt == ts.NEW) {
/* Eat the NEW token. */
ts.getToken();
sourceAdd((char)ts.NEW);
/* Make a NEW node to append to. */
pn = nf.createLeaf(ts.NEW);
nf.addChildToBack(pn, memberExpr(ts, false));
if (ts.matchToken(ts.LP)) {
sourceAdd((char)ts.LP);
/* Add the arguments to pn, if any are supplied. */
pn = argumentList(ts, pn);
}
/* XXX there's a check in the C source against
* "too many constructor arguments" - how many
* do we claim to support?
*/
/* Experimental syntax: allow an object literal to follow a new expression,
* which will mean a kind of anonymous class built with the JavaAdapter.
* the object literal will be passed as an additional argument to the constructor.
*/
tt = ts.peekToken();
if (tt == ts.LC) {
nf.addChildToBack(pn, primaryExpr(ts));
}
} else {
pn = primaryExpr(ts);
}
return memberExprTail(ts, allowCallSyntax, pn);
}
private Object memberExprTail(TokenStream ts, boolean allowCallSyntax,
Object pn)
throws IOException, JavaScriptException
{
lastExprEndLine = ts.getLineno();
int tt;
while ((tt = ts.getToken()) > ts.EOF) {
if (tt == ts.DOT) {
sourceAdd((char)ts.DOT);
mustMatchToken(ts, ts.NAME, "msg.no.name.after.dot");
String s = ts.getString();
sourceAddString(ts.NAME, s);
pn = nf.createBinary(ts.DOT, pn,
nf.createName(ts.getString()));
/* pn = nf.createBinary(ts.DOT, pn, memberExpr(ts))
* is the version in Brendan's IR C version. Not in ECMA...
* does it reflect the 'new' operator syntax he mentioned?
*/
lastExprEndLine = ts.getLineno();
} else if (tt == ts.LB) {
sourceAdd((char)ts.LB);
pn = nf.createBinary(ts.LB, pn, expr(ts, false));
mustMatchToken(ts, ts.RB, "msg.no.bracket.index");
sourceAdd((char)ts.RB);
lastExprEndLine = ts.getLineno();
} else if (allowCallSyntax && tt == ts.LP) {
/* make a call node */
pn = nf.createUnary(ts.CALL, pn);
sourceAdd((char)ts.LP);
/* Add the arguments to pn, if any are supplied. */
pn = argumentList(ts, pn);
lastExprEndLine = ts.getLineno();
} else {
ts.ungetToken(tt);
break;
}
}
return pn;
}
private Object primaryExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn;
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
switch(tt) {
case TokenStream.FUNCTION:
return function(ts, true);
case TokenStream.LB:
{
sourceAdd((char)ts.LB);
pn = nf.createLeaf(ts.ARRAYLIT);
ts.flags |= ts.TSF_REGEXP;
boolean matched = ts.matchToken(ts.RB);
ts.flags &= ~ts.TSF_REGEXP;
if (!matched) {
boolean first = true;
do {
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekToken();
ts.flags &= ~ts.TSF_REGEXP;
if (!first)
sourceAdd((char)ts.COMMA);
else
first = false;
if (tt == ts.RB) { // to fix [,,,].length behavior...
break;
}
if (tt == ts.COMMA) {
nf.addChildToBack(pn, nf.createLeaf(ts.PRIMARY,
ts.UNDEFINED));
} else {
nf.addChildToBack(pn, assignExpr(ts, false));
}
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RB, "msg.no.bracket.arg");
}
sourceAdd((char)ts.RB);
return nf.createArrayLiteral(pn);
}
case TokenStream.LC: {
pn = nf.createLeaf(ts.OBJLIT);
sourceAdd((char)ts.LC);
if (!ts.matchToken(ts.RC)) {
boolean first = true;
commaloop:
do {
Object property;
if (!first)
sourceAdd((char)ts.COMMA);
else
first = false;
tt = ts.getToken();
switch(tt) {
// map NAMEs to STRINGs in object literal context.
case TokenStream.NAME:
case TokenStream.STRING:
String s = ts.getString();
sourceAddString(ts.NAME, s);
property = nf.createString(ts.getString());
break;
case TokenStream.NUMBER:
double n = ts.getNumber();
sourceAddNumber(n);
property = nf.createNumber(n);
break;
case TokenStream.RC:
// trailing comma is OK.
ts.ungetToken(tt);
break commaloop;
default:
reportError(ts, "msg.bad.prop");
break commaloop;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.prop");
// OBJLIT is used as ':' in object literal for
// decompilation to solve spacing ambiguity.
sourceAdd((char)ts.OBJLIT);
nf.addChildToBack(pn, property);
nf.addChildToBack(pn, assignExpr(ts, false));
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RC, "msg.no.brace.prop");
}
sourceAdd((char)ts.RC);
return nf.createObjectLiteral(pn);
}
case TokenStream.LP:
/* Brendan's IR-jsparse.c makes a new node tagged with
* TOK_LP here... I'm not sure I understand why. Isn't
* the grouping already implicit in the structure of the
* parse tree? also TOK_LP is already overloaded (I
* think) in the C IR as 'function call.' */
sourceAdd((char)ts.LP);
pn = expr(ts, false);
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.RP, "msg.no.paren");
return pn;
case TokenStream.NAME:
String name = ts.getString();
sourceAddString(ts.NAME, name);
return nf.createName(name);
case TokenStream.NUMBER:
double n = ts.getNumber();
sourceAddNumber(n);
return nf.createNumber(n);
case TokenStream.STRING:
String s = ts.getString();
sourceAddString(ts.STRING, s);
return nf.createString(s);
case TokenStream.OBJECT:
{
String flags = ts.regExpFlags;
ts.regExpFlags = null;
String re = ts.getString();
sourceAddString(ts.OBJECT, '/' + re + '/' + flags);
return nf.createRegExp(re, flags);
}
case TokenStream.PRIMARY:
sourceAdd((char)ts.PRIMARY);
sourceAdd((char)ts.getOp());
return nf.createLeaf(ts.PRIMARY, ts.getOp());
case TokenStream.RESERVED:
reportError(ts, "msg.reserved.id");
break;
case TokenStream.ERROR:
/* the scanner or one of its subroutines reported the error. */
break;
default:
reportError(ts, "msg.syntax");
break;
}
return null; // should never reach here
}
/**
* The following methods save decompilation information about the source.
* Source information is returned from the parser as a String
* associated with function nodes and with the toplevel script. When
* saved in the constant pool of a class, this string will be UTF-8
* encoded, and token values will occupy a single byte.
* Source is saved (mostly) as token numbers. The tokens saved pretty
* much correspond to the token stream of a 'canonical' representation
* of the input program, as directed by the parser. (There were a few
* cases where tokens could have been left out where decompiler could
* easily reconstruct them, but I left them in for clarity). (I also
* looked adding source collection to TokenStream instead, where I
* could have limited the changes to a few lines in getToken... but
* this wouldn't have saved any space in the resulting source
* representation, and would have meant that I'd have to duplicate
* parser logic in the decompiler to disambiguate situations where
* newlines are important.) NativeFunction.decompile expands the
* tokens back into their string representations, using simple
* lookahead to correct spacing and indentation.
* Token types with associated ops (ASSIGN, SHOP, PRIMARY, etc.) are
* saved as two-token pairs. Number tokens are stored inline, as a
* NUMBER token, a character representing the type, and either 1 or 4
* characters representing the bit-encoding of the number. String
* types NAME, STRING and OBJECT are currently stored as a token type,
* followed by a character giving the length of the string (assumed to
* be less than 2^16), followed by the characters of the string
* inlined into the source string. Changing this to some reference to
* to the string in the compiled class' constant pool would probably
* save a lot of space... but would require some method of deriving
* the final constant pool entry from information available at parse
* time.
* Nested functions need a similar mechanism... fortunately the nested
* functions for a given function are generated in source order.
* Nested functions are encoded as FUNCTION followed by a function
* number (encoded as a character), which is enough information to
* find the proper generated NativeFunction instance.
*/
private void sourceAdd(char c) {
if (sourceTop == sourceBuffer.length) {
increaseSourceCapacity(sourceTop + 1);
}
sourceBuffer[sourceTop] = c;
++sourceTop;
}
private void sourceAddString(int type, String str) {
int L = str.length();
// java string length < 2^16?
if (Context.check && L > Character.MAX_VALUE) Context.codeBug();
if (sourceTop + L + 2 > sourceBuffer.length) {
increaseSourceCapacity(sourceTop + L + 2);
}
sourceAdd((char)type);
sourceAdd((char)L);
str.getChars(0, L, sourceBuffer, sourceTop);
sourceTop += L;
}
private void sourceAddNumber(double n) {
sourceAdd((char)TokenStream.NUMBER);
/* encode the number in the source stream.
* Save as NUMBER type (char | char char char char)
* where type is
* 'D' - double, 'S' - short, 'J' - long.
* We need to retain float vs. integer type info to keep the
* behavior of liveconnect type-guessing the same after
* decompilation. (Liveconnect tries to present 1.0 to Java
* as a float/double)
* OPT: This is no longer true. We could compress the format.
* This may not be the most space-efficient encoding;
* the chars created below may take up to 3 bytes in
* constant pool UTF-8 encoding, so a Double could take
* up to 12 bytes.
*/
long lbits = (long)n;
if (lbits != n) {
// if it's floating point, save as a Double bit pattern.
// (12/15/97 our scanner only returns Double for f.p.)
lbits = Double.doubleToLongBits(n);
sourceAdd('D');
sourceAdd((char)(lbits >> 48));
sourceAdd((char)(lbits >> 32));
sourceAdd((char)(lbits >> 16));
sourceAdd((char)lbits);
}
else {
// we can ignore negative values, bc they're already prefixed
// by UNARYOP SUB
if (Context.check && lbits < 0) Context.codeBug();
// will it fit in a char?
// this gives a short encoding for integer values up to 2^16.
if (lbits <= Character.MAX_VALUE) {
sourceAdd('S');
sourceAdd((char)lbits);
}
else { // Integral, but won't fit in a char. Store as a long.
sourceAdd('J');
sourceAdd((char)(lbits >> 48));
sourceAdd((char)(lbits >> 32));
sourceAdd((char)(lbits >> 16));
sourceAdd((char)lbits);
}
}
}
private void increaseSourceCapacity(int minimalCapacity) {
// Call this only when capacity increase is must
if (Context.check && minimalCapacity <= sourceBuffer.length)
Context.codeBug();
int newCapacity = sourceBuffer.length * 2;
if (newCapacity < minimalCapacity) {
newCapacity = minimalCapacity;
}
char[] tmp = new char[newCapacity];
System.arraycopy(sourceBuffer, 0, tmp, 0, sourceTop);
sourceBuffer = tmp;
}
private String sourceToString(int offset) {
if (Context.check && (offset < 0 || sourceTop < offset))
Context.codeBug();
return new String(sourceBuffer, offset, sourceTop - offset);
}
private int lastExprEndLine; // Hack to handle function expr termination.
private IRFactory nf;
private ErrorReporter er;
private boolean ok; // Did the parse encounter an error?
private char[] sourceBuffer = new char[128];
private int sourceTop;
private int functionNumber;
}
| false | true | private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
int lineno = 0;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
lineno = ts.getLineno();
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
| private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
int lineno = ts.getLineno();
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
|
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/Annotation.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/Annotation.java
index af14321bc..d5215d5b5 100644
--- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/Annotation.java
+++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/Annotation.java
@@ -1,127 +1,130 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 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.source;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
/**
* Abstract annotation managed by an <code>IAnnotationModel</code>.
* Annotations are considered being located at layers and are considered being painted
* starting with layer 0 upwards. Thus an annotation of layer 5 will be drawn on top of
* all co-located annotations at the layers 4 - 0. Subclasses must provide the annotations
* paint method.
*
* @see IVerticalRuler
*/
public abstract class Annotation {
/** The layer of this annotation. */
private int fLayer;
/**
* Creates a new annotation.
*/
protected Annotation() {
}
/**
* Sets the layer of this annotation.
*
* @param layer the layer of this annotation
*/
protected void setLayer(int layer) {
fLayer= layer;
}
/**
* Convenience method for drawing an image aligned inside a rectangle.
*
* @param image the image to be drawn
* @param GC the drawing GC
* @param canvas the canvas on which to draw
* @param r the clipping rectangle
* @param halign the horizontal alignment of the image to be drawn
* @param valign the vertical alignment of the image to be drawn
*/
protected static void drawImage(Image image, GC gc, Canvas canvas, Rectangle r, int halign, int valign) {
if (image != null) {
Rectangle bounds= image.getBounds();
int x= 0;
switch(halign) {
case SWT.LEFT:
break;
case SWT.CENTER:
x= (r.width - bounds.width) / 2;
break;
case SWT.RIGHT:
x= r.width - bounds.width;
break;
}
int y= 0;
switch (valign) {
- case SWT.TOP:
+ case SWT.TOP: {
FontMetrics fontMetrics= gc.getFontMetrics();
y= (fontMetrics.getHeight() - bounds.height)/2;
break;
+ }
case SWT.CENTER:
y= (r.height - bounds.height) / 2;
break;
- case SWT.BOTTOM:
- y= r.height - bounds.height;
+ case SWT.BOTTOM: {
+ FontMetrics fontMetrics= gc.getFontMetrics();
+ y= r.height - (fontMetrics.getHeight() + bounds.height)/2;
break;
+ }
}
gc.drawImage(image, r.x+x, r.y+y);
}
}
/**
* Convenience method for drawing an image aligned inside a rectangle.
*
* @param image the image to be drawn
* @param GC the drawing GC
* @param canvas the canvas on which to draw
* @param r the clipping rectangle
* @param align the alignment of the image to be drawn
*/
protected static void drawImage(Image image, GC gc, Canvas canvas, Rectangle r, int align) {
drawImage(image, gc, canvas, r, align, SWT.CENTER);
}
/**
* Returns the annotations drawing layer.
*
* @return the annotations drawing layer
*/
public int getLayer() {
return fLayer;
}
/**
* Implement this method to draw a graphical representation
* of this annotation within the given bounds.
*
* @param GC the drawing GC
* @param canvas the canvas to draw on
* @param bounds the bounds inside the canvas to draw on
*/
public abstract void paint(GC gc, Canvas canvas, Rectangle bounds);
}
| false | true | protected static void drawImage(Image image, GC gc, Canvas canvas, Rectangle r, int halign, int valign) {
if (image != null) {
Rectangle bounds= image.getBounds();
int x= 0;
switch(halign) {
case SWT.LEFT:
break;
case SWT.CENTER:
x= (r.width - bounds.width) / 2;
break;
case SWT.RIGHT:
x= r.width - bounds.width;
break;
}
int y= 0;
switch (valign) {
case SWT.TOP:
FontMetrics fontMetrics= gc.getFontMetrics();
y= (fontMetrics.getHeight() - bounds.height)/2;
break;
case SWT.CENTER:
y= (r.height - bounds.height) / 2;
break;
case SWT.BOTTOM:
y= r.height - bounds.height;
break;
}
gc.drawImage(image, r.x+x, r.y+y);
}
}
| protected static void drawImage(Image image, GC gc, Canvas canvas, Rectangle r, int halign, int valign) {
if (image != null) {
Rectangle bounds= image.getBounds();
int x= 0;
switch(halign) {
case SWT.LEFT:
break;
case SWT.CENTER:
x= (r.width - bounds.width) / 2;
break;
case SWT.RIGHT:
x= r.width - bounds.width;
break;
}
int y= 0;
switch (valign) {
case SWT.TOP: {
FontMetrics fontMetrics= gc.getFontMetrics();
y= (fontMetrics.getHeight() - bounds.height)/2;
break;
}
case SWT.CENTER:
y= (r.height - bounds.height) / 2;
break;
case SWT.BOTTOM: {
FontMetrics fontMetrics= gc.getFontMetrics();
y= r.height - (fontMetrics.getHeight() + bounds.height)/2;
break;
}
}
gc.drawImage(image, r.x+x, r.y+y);
}
}
|
diff --git a/geotools2/geotools-src/shapefile/src/org/geotools/shapefile/ShapefileDataSource.java b/geotools2/geotools-src/shapefile/src/org/geotools/shapefile/ShapefileDataSource.java
index ebae3be7f..2c1f39a90 100644
--- a/geotools2/geotools-src/shapefile/src/org/geotools/shapefile/ShapefileDataSource.java
+++ b/geotools2/geotools-src/shapefile/src/org/geotools/shapefile/ShapefileDataSource.java
@@ -1,94 +1,94 @@
/*
* ShapefileDataSource.java
*
* Created on March 4, 2002, 1:48 PM
*/
package org.geotools.shapefile;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import org.geotools.datasource.*;
import org.geotools.datasource.extents.*;
import com.vividsolutions.jts.geom.*;
/**
*
* @author jamesm
*/
public class ShapefileDataSource implements org.geotools.datasource.DataSource {
Shapefile shapefile;
/** Creates a new instance of ShapefileDataSource */
public ShapefileDataSource(Shapefile shapefile) {
}
/** gets the Column names (used by FeatureTable) for this DataSource
*/
public String[] getColumnNames() {
return new String[]{"Geometry"};
}
/** Loads Feature rows for the given Extent from the datasource
*/
public List load(Extent ex) throws DataSourceException {
if(ex instanceof EnvelopeExtent){
List features = new ArrayList();
EnvelopeExtent ee = (EnvelopeExtent)ex;
Envelope bounds = ee.getBounds();
try{
GeometryCollection shapes = shapefile.read(new GeometryFactory());
int count = shapes.getNumGeometries();
for(int i=0;i<count;i++){
Feature feat = new Feature();
feat.columnNames = getColumnNames();
Object [] row = new Object[1];
feat.row = row;
feat.row[0] = shapes.getGeometryN(i);
if(ex.containsFeature(feat)){
features.add(feat);
}
}
}
catch(IOException ioe){
throw new DataSourceException("IO Exception loading data : "+ioe.getMessage());
}
catch(ShapefileException se){
throw new DataSourceException("Shapefile Exception loading data : "+se.getMessage());
}
catch(TopologyException te){
throw new DataSourceException("Topology Exception loading data : "+te.getMessage());
}
- return null;
+ return features;
}
else{
return null;
}
}
/** Saves the given features to the datasource
*/
public void save(List features) throws DataSourceException {
GeometryFactory fac = new GeometryFactory();
GeometryCollection gc = fac.createGeometryCollection((GeometryCollection[])features.toArray(new Geometry[0]));
try{
shapefile.write(gc);
}
catch(Exception e){
{
throw new DataSourceException(e.getMessage());
}
}
}
/** Stops this DataSource from loading
*/
public void stopLoading() {
//can't sorry
}
}
| true | true | public List load(Extent ex) throws DataSourceException {
if(ex instanceof EnvelopeExtent){
List features = new ArrayList();
EnvelopeExtent ee = (EnvelopeExtent)ex;
Envelope bounds = ee.getBounds();
try{
GeometryCollection shapes = shapefile.read(new GeometryFactory());
int count = shapes.getNumGeometries();
for(int i=0;i<count;i++){
Feature feat = new Feature();
feat.columnNames = getColumnNames();
Object [] row = new Object[1];
feat.row = row;
feat.row[0] = shapes.getGeometryN(i);
if(ex.containsFeature(feat)){
features.add(feat);
}
}
}
catch(IOException ioe){
throw new DataSourceException("IO Exception loading data : "+ioe.getMessage());
}
catch(ShapefileException se){
throw new DataSourceException("Shapefile Exception loading data : "+se.getMessage());
}
catch(TopologyException te){
throw new DataSourceException("Topology Exception loading data : "+te.getMessage());
}
return null;
}
else{
return null;
}
}
| public List load(Extent ex) throws DataSourceException {
if(ex instanceof EnvelopeExtent){
List features = new ArrayList();
EnvelopeExtent ee = (EnvelopeExtent)ex;
Envelope bounds = ee.getBounds();
try{
GeometryCollection shapes = shapefile.read(new GeometryFactory());
int count = shapes.getNumGeometries();
for(int i=0;i<count;i++){
Feature feat = new Feature();
feat.columnNames = getColumnNames();
Object [] row = new Object[1];
feat.row = row;
feat.row[0] = shapes.getGeometryN(i);
if(ex.containsFeature(feat)){
features.add(feat);
}
}
}
catch(IOException ioe){
throw new DataSourceException("IO Exception loading data : "+ioe.getMessage());
}
catch(ShapefileException se){
throw new DataSourceException("Shapefile Exception loading data : "+se.getMessage());
}
catch(TopologyException te){
throw new DataSourceException("Topology Exception loading data : "+te.getMessage());
}
return features;
}
else{
return null;
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementRegistry.java b/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementRegistry.java
index 4c922cf84..4be52f353 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementRegistry.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/requirements/RequirementRegistry.java
@@ -1,497 +1,497 @@
package net.aufdemrand.denizen.scripts.requirements;
import net.aufdemrand.denizen.Denizen;
import net.aufdemrand.denizen.interfaces.dRegistry;
import net.aufdemrand.denizen.interfaces.RegistrationableInstance;
import net.aufdemrand.denizen.scripts.requirements.core.*;
import net.aufdemrand.denizen.utilities.debugging.dB;
import java.util.HashMap;
import java.util.Map;
public class RequirementRegistry implements dRegistry {
public Denizen denizen;
private Map<String, AbstractRequirement> instances = new HashMap<String, AbstractRequirement>();
private Map<Class<? extends AbstractRequirement>, String> classes = new HashMap<Class<? extends AbstractRequirement>, String>();
public RequirementRegistry(Denizen denizen) {
this.denizen = denizen;
}
@Override
public void disableCoreMembers() {
for (RegistrationableInstance member : instances.values())
try {
member.onDisable();
} catch (Exception e) {
dB.echoError("Unable to disable '" + member.getClass().getName() + "'!");
if (dB.showStackTraces) e.printStackTrace();
}
}
@Override
public <T extends RegistrationableInstance> T get(Class<T> clazz) {
if (classes.containsKey(clazz)) return (T) clazz.cast(instances.get(classes.get(clazz)));
else return null;
}
@Override
public AbstractRequirement get(String requirementName) {
if (instances.containsKey(requirementName.toUpperCase())) return instances.get(requirementName.toUpperCase());
else return null;
}
@Override
public Map<String, AbstractRequirement> list() {
return instances;
}
@Override
public boolean register(String requirementName, RegistrationableInstance requirementClass) {
this.instances.put(requirementName.toUpperCase(), (AbstractRequirement) requirementClass);
this.classes.put(((AbstractRequirement) requirementClass).getClass(), requirementName.toUpperCase());
return true;
}
@Override
public void registerCoreMembers() {
// <--[requirement]
// @Name Enchanted
// @Usage enchanted [iteminhand]
// @Required 1
// @Stable Stable
// @Short Checks if an item has an enchantment or not.
//
// @Description
// Checks if the specified item has an enchantment. Currently, the only
// item available for this is the "iteminhand".
//
// @Usage
// Use to check if the item in the player's hand has an enchantment.
- // - enchantment iteminhand
+ // - enchanted iteminhand
//
// @Example
// TODO
//
// -->
registerCoreMember(EnchantedRequirement.class,
"ENCHANTED", "enchanted [iteminhand]", 1);
// <--[requirement]
// @Name Flagged
// @Usage (-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)
// @Required 1
// @Stable Stable
// @Short Checks if the specified flag exists.
//
// @Description
// Checks if the specified flag exists on the specified owner, which is "player"
// by default.
//
// @Usage
// Check if a flag exists.
// - flagged FlagName
//
// @Usage
// Check if a flag has a specified value.
// - flagged FlagName:Value
//
// @Usage
// Check if a flag does not exist.
// - -flagged FlagName
//
// @Example
// TODO
//
// -->
registerCoreMember(FlaggedRequirement.class,
"FLAGGED", "(-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)", 1);
// <--[requirement]
// @Name Holding
// @Usage holding [<item>] (qty:<#>) (exact)
// @Required 1
// @Stable Stable
// @Short Checks if the player is holding an item.
//
// @Description
// Checks if the player is holding a specified item. The item can be a dItem (i@itemName)
// or it can be a normal material name or ID (wood, 5, 5:1). If a quantity is given, it
// checks if the ItemStack in the player's hand hand has at least that many items. If
// "exact" is specified, it must be the exact quantity of items.
//
// @Usage
// Check if the player is holding at least 3 pieces of wood.
// - holding wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(HoldingRequirement.class,
"HOLDING", "holding [<item>] (qty:<#>) (exact)", 1);
// <--[requirement]
// @Name InGroup
// @Usage ingroup (global) [<group>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a group.
//
// @Description
// Checks if the player is in the specified group in the current world, or global group if specified.
//
// @Usage
// Check if the player is in a group.
// - ingroup Builder
//
// @Usage
// Check if the player is in a global group.
// - ingroup global Admin
//
// @Example
// TODO
//
// -->
registerCoreMember(InGroupRequirement.class,
"INGROUP", "ingroup (global) [<group>]", 1);
// <--[requirement]
// @Name Item
// @Usage item [<item>] (qty:<#>)
// @Required 1
// @Stable Stable
// @Short Checks if the player has an item.
//
// @Description
// Checks if the player has the specified item and the quantity of that item in their inventory.
//
// @Usage
// Check if the player has an item.
// - item wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(ItemRequirement.class,
"ITEM", "item [<item>] (qty:<#>)", 1);
// <--[requirement]
// @Name IsLiquid
// @Usage isliquid [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is a liquid.
//
// @Description
// Checks if the block at the specified location is a liquid. (Water or lava)
//
// @Usage
// Check if the block is a liquid.
// - isliquid location:103,70,413,world
//
// @Example TODO
//
// -->
registerCoreMember(LiquidRequirement.class,
"ISLIQUID", "isliquid [location:<location>]", 1);
// <--[requirement]
// @Name Money
// @Usage money [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has an amount of money.
//
// @Description
// Checks if the player has a specified amount of money in their account.
//
// @Usage
// Check if the player has an amount of money.
// - money qty:100
//
// @Example TODO
//
// -->
registerCoreMember(MoneyRequirement.class,
"MONEY", "money [qty:<#>]", 1);
// <--[requirement]
// @Name Op
// @Usage op
// @Required 0
// @Stable Stable
// @Short Checks if the player is an op.
//
// @Description
// Checks if the player has Minecraft Op status.
//
// @Usage
// Check if the player is opped.
// - op
//
// @Example TODO
//
// -->
registerCoreMember(OpRequirement.class,
"OP", "op", 0);
// <--[requirement]
// @Name Owner
// @Usage owner
// @Required 0
// @Stable Stable
// @Short Checks if the player is the owner of the current NPC.
//
// @Description
// Checks if the player is the owner of the NPC attached to the current script.
//
// @Usage
// Check if the player is the owner of the NPC.
// - owner
//
// @Example TODO
//
// -->
registerCoreMember(OwnerRequirement.class,
"OWNER", "owner", 0);
// <--[requirement]
// @Name Permission
// @Usage permission (global) [<permission>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has a permission node.
//
// @Description Check if the player has a specified permission node.
// (Requires Vault)
//
// @Usage
// Check if the player has a permission.
// - permission denizen.basic
//
// @Example TODO
//
// -->
registerCoreMember(PermissionRequirement.class,
"PERMISSION", "permission (global) [<permission>]", 1);
// <--[requirement]
// @Name IsPowered
// @Usage ispowered [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is powered.
//
// @Description Checks if the block at a specified location is powered
// by a redstone current.
//
// @Usage
// Check if the block is powered.
// - ispowered location:919,78,298
//
// @Example TODO
//
// -->
registerCoreMember(PoweredRequirement.class,
"ISPOWERED", "ispowered [location:<location>]", 1);
// <--[requirement]
// @Name Oxygen
// @Usage oxygen (range:below/equals/above) [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks the player's oxygen level.
//
// @Description Checks if the specified oxygen level is above, below, or
// equal to the oxygen level of the player.
//
// @Usage Check if the player has above an amount of oxygen.
// - oxygen range:above qty:3
//
// @Example TODO
//
// -->
registerCoreMember(OxygenRequirement.class,
"OXYGEN", "oxygen (range:below/equals/above) [qty:<#>]", 1);
// <--[requirement]
// @Name Procedure
// @Usage procedure [<script>]
// @Required 1
// @Stable Stable
// @Short Checks the value of the procedure script.
//
// @Description Checks the value of a specified procedure script.
//
// @Usage
// Check if the procedure script determines true
// - procedure procScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ProcedureRequirement.class,
"PROCEDURE", "procedure [<script>]", 1);
// <--[requirement]
// @Name Script
// @Usage script [finished/failed] [script:<name>]
// @Required 2
// @Stable Stable
// @Short Checks if a script is finished or failed.
//
// @Description
// Checks if the specified script was finished or failed by the player.
//
// @Usage
// Check if the script was finished
// - script finished script:ScriptName
//
// @Usage
// Check if the script was failed
// - script failed script:ScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ScriptRequirement.class,
"SCRIPT", "script [finished/failed] [script:<name>]", 2);
// <--[requirement]
// @Name Sneaking
// @Usage sneaking
// @Required 0
// @Stable Stable
// @Short Checks if the player is sneaking.
//
// @Description
// Checks if the player is currently sneaking.
//
// @Usage
// Check if the player is sneaking
// - sneaking
//
// @Example TODO
//
// -->
registerCoreMember(SneakingRequirement.class,
"SNEAKING", "sneaking", 0);
// <--[requirement]
// @Name Storming
// @Usage storming
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is storming.
//
// @Description
// Checks if the world the player is currently in has stormy weather.
//
// @Usage
// Check if the world is storming
// - storming
//
// @Example TODO
//
// -->
registerCoreMember(StormRequirement.class,
"STORMING", "storming", 0);
// <--[requirement]
// @Name Sunny
// @Usage sunny
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is sunny.
//
// @Description
// Checks if the world the player is currently in has sunny weather.
//
// @Usage
// Check if the world is sunny
// - sunny
//
// @Example TODO
//
// -->
registerCoreMember(SunnyRequirement.class,
"SUNNY", "sunny", 0);
// <--[requirement]
// @Name Rainy
// @Usage rainy
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is rainy.
//
// @Description
// Checks if the world the player is currently in has rainy weather.
//
// @Usage
// Check if the world is rainy
// - rainy
//
// @Example TODO
//
// -->
registerCoreMember(RainyRequirement.class,
"RAINY", "rainy", 0);
// <--[requirement]
// @Name Time
// @Usage time [dawn/day/dusk/night]
// @Required 1
// @Stable Stable
// @Short Checks the time of the player's world.
//
// @Description
// Checks if the time of the player's world is currently dawn, day, dusk, or night.
//
// @Usage
// Check the time of day
// - time dusk
//
// @Example TODO
//
// -->
registerCoreMember(TimeRequirement.class,
"TIME", "time [dawn/day/dusk/night]", 1);
// <--[requirement]
// @Name InRegion
// @Usage inregion [name:<region>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a region.
//
// @Description
// Checks if the player is in a WorldGuard region. (Requires WorldGuard!)
//
// @Usage
// Check if the player is in a region
// - inregion name:MyRegion
//
// @Example TODO
//
// -->
registerCoreMember(WorldGuardRegionRequirement.class,
"INREGION", "inregion [name:<region>]", 1);
dB.echoApproval("Loaded core requirements: " + instances.keySet().toString());
}
private <T extends AbstractRequirement> void registerCoreMember(Class<T> requirement, String name, String hint, int args) {
try {
requirement.newInstance().activate().as(name).withOptions("(-)" + hint, args);
} catch(Exception e) {
dB.echoError("Could not register requirement " + name + ": " + e.getMessage());
if (dB.showStackTraces) e.printStackTrace();
}
}
}
| true | true | public void registerCoreMembers() {
// <--[requirement]
// @Name Enchanted
// @Usage enchanted [iteminhand]
// @Required 1
// @Stable Stable
// @Short Checks if an item has an enchantment or not.
//
// @Description
// Checks if the specified item has an enchantment. Currently, the only
// item available for this is the "iteminhand".
//
// @Usage
// Use to check if the item in the player's hand has an enchantment.
// - enchantment iteminhand
//
// @Example
// TODO
//
// -->
registerCoreMember(EnchantedRequirement.class,
"ENCHANTED", "enchanted [iteminhand]", 1);
// <--[requirement]
// @Name Flagged
// @Usage (-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)
// @Required 1
// @Stable Stable
// @Short Checks if the specified flag exists.
//
// @Description
// Checks if the specified flag exists on the specified owner, which is "player"
// by default.
//
// @Usage
// Check if a flag exists.
// - flagged FlagName
//
// @Usage
// Check if a flag has a specified value.
// - flagged FlagName:Value
//
// @Usage
// Check if a flag does not exist.
// - -flagged FlagName
//
// @Example
// TODO
//
// -->
registerCoreMember(FlaggedRequirement.class,
"FLAGGED", "(-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)", 1);
// <--[requirement]
// @Name Holding
// @Usage holding [<item>] (qty:<#>) (exact)
// @Required 1
// @Stable Stable
// @Short Checks if the player is holding an item.
//
// @Description
// Checks if the player is holding a specified item. The item can be a dItem (i@itemName)
// or it can be a normal material name or ID (wood, 5, 5:1). If a quantity is given, it
// checks if the ItemStack in the player's hand hand has at least that many items. If
// "exact" is specified, it must be the exact quantity of items.
//
// @Usage
// Check if the player is holding at least 3 pieces of wood.
// - holding wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(HoldingRequirement.class,
"HOLDING", "holding [<item>] (qty:<#>) (exact)", 1);
// <--[requirement]
// @Name InGroup
// @Usage ingroup (global) [<group>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a group.
//
// @Description
// Checks if the player is in the specified group in the current world, or global group if specified.
//
// @Usage
// Check if the player is in a group.
// - ingroup Builder
//
// @Usage
// Check if the player is in a global group.
// - ingroup global Admin
//
// @Example
// TODO
//
// -->
registerCoreMember(InGroupRequirement.class,
"INGROUP", "ingroup (global) [<group>]", 1);
// <--[requirement]
// @Name Item
// @Usage item [<item>] (qty:<#>)
// @Required 1
// @Stable Stable
// @Short Checks if the player has an item.
//
// @Description
// Checks if the player has the specified item and the quantity of that item in their inventory.
//
// @Usage
// Check if the player has an item.
// - item wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(ItemRequirement.class,
"ITEM", "item [<item>] (qty:<#>)", 1);
// <--[requirement]
// @Name IsLiquid
// @Usage isliquid [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is a liquid.
//
// @Description
// Checks if the block at the specified location is a liquid. (Water or lava)
//
// @Usage
// Check if the block is a liquid.
// - isliquid location:103,70,413,world
//
// @Example TODO
//
// -->
registerCoreMember(LiquidRequirement.class,
"ISLIQUID", "isliquid [location:<location>]", 1);
// <--[requirement]
// @Name Money
// @Usage money [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has an amount of money.
//
// @Description
// Checks if the player has a specified amount of money in their account.
//
// @Usage
// Check if the player has an amount of money.
// - money qty:100
//
// @Example TODO
//
// -->
registerCoreMember(MoneyRequirement.class,
"MONEY", "money [qty:<#>]", 1);
// <--[requirement]
// @Name Op
// @Usage op
// @Required 0
// @Stable Stable
// @Short Checks if the player is an op.
//
// @Description
// Checks if the player has Minecraft Op status.
//
// @Usage
// Check if the player is opped.
// - op
//
// @Example TODO
//
// -->
registerCoreMember(OpRequirement.class,
"OP", "op", 0);
// <--[requirement]
// @Name Owner
// @Usage owner
// @Required 0
// @Stable Stable
// @Short Checks if the player is the owner of the current NPC.
//
// @Description
// Checks if the player is the owner of the NPC attached to the current script.
//
// @Usage
// Check if the player is the owner of the NPC.
// - owner
//
// @Example TODO
//
// -->
registerCoreMember(OwnerRequirement.class,
"OWNER", "owner", 0);
// <--[requirement]
// @Name Permission
// @Usage permission (global) [<permission>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has a permission node.
//
// @Description Check if the player has a specified permission node.
// (Requires Vault)
//
// @Usage
// Check if the player has a permission.
// - permission denizen.basic
//
// @Example TODO
//
// -->
registerCoreMember(PermissionRequirement.class,
"PERMISSION", "permission (global) [<permission>]", 1);
// <--[requirement]
// @Name IsPowered
// @Usage ispowered [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is powered.
//
// @Description Checks if the block at a specified location is powered
// by a redstone current.
//
// @Usage
// Check if the block is powered.
// - ispowered location:919,78,298
//
// @Example TODO
//
// -->
registerCoreMember(PoweredRequirement.class,
"ISPOWERED", "ispowered [location:<location>]", 1);
// <--[requirement]
// @Name Oxygen
// @Usage oxygen (range:below/equals/above) [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks the player's oxygen level.
//
// @Description Checks if the specified oxygen level is above, below, or
// equal to the oxygen level of the player.
//
// @Usage Check if the player has above an amount of oxygen.
// - oxygen range:above qty:3
//
// @Example TODO
//
// -->
registerCoreMember(OxygenRequirement.class,
"OXYGEN", "oxygen (range:below/equals/above) [qty:<#>]", 1);
// <--[requirement]
// @Name Procedure
// @Usage procedure [<script>]
// @Required 1
// @Stable Stable
// @Short Checks the value of the procedure script.
//
// @Description Checks the value of a specified procedure script.
//
// @Usage
// Check if the procedure script determines true
// - procedure procScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ProcedureRequirement.class,
"PROCEDURE", "procedure [<script>]", 1);
// <--[requirement]
// @Name Script
// @Usage script [finished/failed] [script:<name>]
// @Required 2
// @Stable Stable
// @Short Checks if a script is finished or failed.
//
// @Description
// Checks if the specified script was finished or failed by the player.
//
// @Usage
// Check if the script was finished
// - script finished script:ScriptName
//
// @Usage
// Check if the script was failed
// - script failed script:ScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ScriptRequirement.class,
"SCRIPT", "script [finished/failed] [script:<name>]", 2);
// <--[requirement]
// @Name Sneaking
// @Usage sneaking
// @Required 0
// @Stable Stable
// @Short Checks if the player is sneaking.
//
// @Description
// Checks if the player is currently sneaking.
//
// @Usage
// Check if the player is sneaking
// - sneaking
//
// @Example TODO
//
// -->
registerCoreMember(SneakingRequirement.class,
"SNEAKING", "sneaking", 0);
// <--[requirement]
// @Name Storming
// @Usage storming
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is storming.
//
// @Description
// Checks if the world the player is currently in has stormy weather.
//
// @Usage
// Check if the world is storming
// - storming
//
// @Example TODO
//
// -->
registerCoreMember(StormRequirement.class,
"STORMING", "storming", 0);
// <--[requirement]
// @Name Sunny
// @Usage sunny
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is sunny.
//
// @Description
// Checks if the world the player is currently in has sunny weather.
//
// @Usage
// Check if the world is sunny
// - sunny
//
// @Example TODO
//
// -->
registerCoreMember(SunnyRequirement.class,
"SUNNY", "sunny", 0);
// <--[requirement]
// @Name Rainy
// @Usage rainy
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is rainy.
//
// @Description
// Checks if the world the player is currently in has rainy weather.
//
// @Usage
// Check if the world is rainy
// - rainy
//
// @Example TODO
//
// -->
registerCoreMember(RainyRequirement.class,
"RAINY", "rainy", 0);
// <--[requirement]
// @Name Time
// @Usage time [dawn/day/dusk/night]
// @Required 1
// @Stable Stable
// @Short Checks the time of the player's world.
//
// @Description
// Checks if the time of the player's world is currently dawn, day, dusk, or night.
//
// @Usage
// Check the time of day
// - time dusk
//
// @Example TODO
//
// -->
registerCoreMember(TimeRequirement.class,
"TIME", "time [dawn/day/dusk/night]", 1);
// <--[requirement]
// @Name InRegion
// @Usage inregion [name:<region>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a region.
//
// @Description
// Checks if the player is in a WorldGuard region. (Requires WorldGuard!)
//
// @Usage
// Check if the player is in a region
// - inregion name:MyRegion
//
// @Example TODO
//
// -->
registerCoreMember(WorldGuardRegionRequirement.class,
"INREGION", "inregion [name:<region>]", 1);
dB.echoApproval("Loaded core requirements: " + instances.keySet().toString());
}
| public void registerCoreMembers() {
// <--[requirement]
// @Name Enchanted
// @Usage enchanted [iteminhand]
// @Required 1
// @Stable Stable
// @Short Checks if an item has an enchantment or not.
//
// @Description
// Checks if the specified item has an enchantment. Currently, the only
// item available for this is the "iteminhand".
//
// @Usage
// Use to check if the item in the player's hand has an enchantment.
// - enchanted iteminhand
//
// @Example
// TODO
//
// -->
registerCoreMember(EnchantedRequirement.class,
"ENCHANTED", "enchanted [iteminhand]", 1);
// <--[requirement]
// @Name Flagged
// @Usage (-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)
// @Required 1
// @Stable Stable
// @Short Checks if the specified flag exists.
//
// @Description
// Checks if the specified flag exists on the specified owner, which is "player"
// by default.
//
// @Usage
// Check if a flag exists.
// - flagged FlagName
//
// @Usage
// Check if a flag has a specified value.
// - flagged FlagName:Value
//
// @Usage
// Check if a flag does not exist.
// - -flagged FlagName
//
// @Example
// TODO
//
// -->
registerCoreMember(FlaggedRequirement.class,
"FLAGGED", "(-)flagged ({player}/npc/global) [<name>([<#>])](:<value>)", 1);
// <--[requirement]
// @Name Holding
// @Usage holding [<item>] (qty:<#>) (exact)
// @Required 1
// @Stable Stable
// @Short Checks if the player is holding an item.
//
// @Description
// Checks if the player is holding a specified item. The item can be a dItem (i@itemName)
// or it can be a normal material name or ID (wood, 5, 5:1). If a quantity is given, it
// checks if the ItemStack in the player's hand hand has at least that many items. If
// "exact" is specified, it must be the exact quantity of items.
//
// @Usage
// Check if the player is holding at least 3 pieces of wood.
// - holding wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(HoldingRequirement.class,
"HOLDING", "holding [<item>] (qty:<#>) (exact)", 1);
// <--[requirement]
// @Name InGroup
// @Usage ingroup (global) [<group>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a group.
//
// @Description
// Checks if the player is in the specified group in the current world, or global group if specified.
//
// @Usage
// Check if the player is in a group.
// - ingroup Builder
//
// @Usage
// Check if the player is in a global group.
// - ingroup global Admin
//
// @Example
// TODO
//
// -->
registerCoreMember(InGroupRequirement.class,
"INGROUP", "ingroup (global) [<group>]", 1);
// <--[requirement]
// @Name Item
// @Usage item [<item>] (qty:<#>)
// @Required 1
// @Stable Stable
// @Short Checks if the player has an item.
//
// @Description
// Checks if the player has the specified item and the quantity of that item in their inventory.
//
// @Usage
// Check if the player has an item.
// - item wood qty:3
//
// @Example
// TODO
//
// -->
registerCoreMember(ItemRequirement.class,
"ITEM", "item [<item>] (qty:<#>)", 1);
// <--[requirement]
// @Name IsLiquid
// @Usage isliquid [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is a liquid.
//
// @Description
// Checks if the block at the specified location is a liquid. (Water or lava)
//
// @Usage
// Check if the block is a liquid.
// - isliquid location:103,70,413,world
//
// @Example TODO
//
// -->
registerCoreMember(LiquidRequirement.class,
"ISLIQUID", "isliquid [location:<location>]", 1);
// <--[requirement]
// @Name Money
// @Usage money [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has an amount of money.
//
// @Description
// Checks if the player has a specified amount of money in their account.
//
// @Usage
// Check if the player has an amount of money.
// - money qty:100
//
// @Example TODO
//
// -->
registerCoreMember(MoneyRequirement.class,
"MONEY", "money [qty:<#>]", 1);
// <--[requirement]
// @Name Op
// @Usage op
// @Required 0
// @Stable Stable
// @Short Checks if the player is an op.
//
// @Description
// Checks if the player has Minecraft Op status.
//
// @Usage
// Check if the player is opped.
// - op
//
// @Example TODO
//
// -->
registerCoreMember(OpRequirement.class,
"OP", "op", 0);
// <--[requirement]
// @Name Owner
// @Usage owner
// @Required 0
// @Stable Stable
// @Short Checks if the player is the owner of the current NPC.
//
// @Description
// Checks if the player is the owner of the NPC attached to the current script.
//
// @Usage
// Check if the player is the owner of the NPC.
// - owner
//
// @Example TODO
//
// -->
registerCoreMember(OwnerRequirement.class,
"OWNER", "owner", 0);
// <--[requirement]
// @Name Permission
// @Usage permission (global) [<permission>]
// @Required 1
// @Stable Stable
// @Short Checks if the player has a permission node.
//
// @Description Check if the player has a specified permission node.
// (Requires Vault)
//
// @Usage
// Check if the player has a permission.
// - permission denizen.basic
//
// @Example TODO
//
// -->
registerCoreMember(PermissionRequirement.class,
"PERMISSION", "permission (global) [<permission>]", 1);
// <--[requirement]
// @Name IsPowered
// @Usage ispowered [location:<location>]
// @Required 1
// @Stable Stable
// @Short Checks if a block is powered.
//
// @Description Checks if the block at a specified location is powered
// by a redstone current.
//
// @Usage
// Check if the block is powered.
// - ispowered location:919,78,298
//
// @Example TODO
//
// -->
registerCoreMember(PoweredRequirement.class,
"ISPOWERED", "ispowered [location:<location>]", 1);
// <--[requirement]
// @Name Oxygen
// @Usage oxygen (range:below/equals/above) [qty:<#>]
// @Required 1
// @Stable Stable
// @Short Checks the player's oxygen level.
//
// @Description Checks if the specified oxygen level is above, below, or
// equal to the oxygen level of the player.
//
// @Usage Check if the player has above an amount of oxygen.
// - oxygen range:above qty:3
//
// @Example TODO
//
// -->
registerCoreMember(OxygenRequirement.class,
"OXYGEN", "oxygen (range:below/equals/above) [qty:<#>]", 1);
// <--[requirement]
// @Name Procedure
// @Usage procedure [<script>]
// @Required 1
// @Stable Stable
// @Short Checks the value of the procedure script.
//
// @Description Checks the value of a specified procedure script.
//
// @Usage
// Check if the procedure script determines true
// - procedure procScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ProcedureRequirement.class,
"PROCEDURE", "procedure [<script>]", 1);
// <--[requirement]
// @Name Script
// @Usage script [finished/failed] [script:<name>]
// @Required 2
// @Stable Stable
// @Short Checks if a script is finished or failed.
//
// @Description
// Checks if the specified script was finished or failed by the player.
//
// @Usage
// Check if the script was finished
// - script finished script:ScriptName
//
// @Usage
// Check if the script was failed
// - script failed script:ScriptName
//
// @Example TODO
//
// -->
registerCoreMember(ScriptRequirement.class,
"SCRIPT", "script [finished/failed] [script:<name>]", 2);
// <--[requirement]
// @Name Sneaking
// @Usage sneaking
// @Required 0
// @Stable Stable
// @Short Checks if the player is sneaking.
//
// @Description
// Checks if the player is currently sneaking.
//
// @Usage
// Check if the player is sneaking
// - sneaking
//
// @Example TODO
//
// -->
registerCoreMember(SneakingRequirement.class,
"SNEAKING", "sneaking", 0);
// <--[requirement]
// @Name Storming
// @Usage storming
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is storming.
//
// @Description
// Checks if the world the player is currently in has stormy weather.
//
// @Usage
// Check if the world is storming
// - storming
//
// @Example TODO
//
// -->
registerCoreMember(StormRequirement.class,
"STORMING", "storming", 0);
// <--[requirement]
// @Name Sunny
// @Usage sunny
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is sunny.
//
// @Description
// Checks if the world the player is currently in has sunny weather.
//
// @Usage
// Check if the world is sunny
// - sunny
//
// @Example TODO
//
// -->
registerCoreMember(SunnyRequirement.class,
"SUNNY", "sunny", 0);
// <--[requirement]
// @Name Rainy
// @Usage rainy
// @Required 0
// @Stable Stable
// @Short Checks if the player's world is rainy.
//
// @Description
// Checks if the world the player is currently in has rainy weather.
//
// @Usage
// Check if the world is rainy
// - rainy
//
// @Example TODO
//
// -->
registerCoreMember(RainyRequirement.class,
"RAINY", "rainy", 0);
// <--[requirement]
// @Name Time
// @Usage time [dawn/day/dusk/night]
// @Required 1
// @Stable Stable
// @Short Checks the time of the player's world.
//
// @Description
// Checks if the time of the player's world is currently dawn, day, dusk, or night.
//
// @Usage
// Check the time of day
// - time dusk
//
// @Example TODO
//
// -->
registerCoreMember(TimeRequirement.class,
"TIME", "time [dawn/day/dusk/night]", 1);
// <--[requirement]
// @Name InRegion
// @Usage inregion [name:<region>]
// @Required 1
// @Stable Stable
// @Short Checks if the player is in a region.
//
// @Description
// Checks if the player is in a WorldGuard region. (Requires WorldGuard!)
//
// @Usage
// Check if the player is in a region
// - inregion name:MyRegion
//
// @Example TODO
//
// -->
registerCoreMember(WorldGuardRegionRequirement.class,
"INREGION", "inregion [name:<region>]", 1);
dB.echoApproval("Loaded core requirements: " + instances.keySet().toString());
}
|
diff --git a/src/main/java/com/solidstategroup/radar/web/pages/admin/AdminUserPage.java b/src/main/java/com/solidstategroup/radar/web/pages/admin/AdminUserPage.java
index 5ba2c61e..6bad1d92 100644
--- a/src/main/java/com/solidstategroup/radar/web/pages/admin/AdminUserPage.java
+++ b/src/main/java/com/solidstategroup/radar/web/pages/admin/AdminUserPage.java
@@ -1,232 +1,234 @@
package com.solidstategroup.radar.web.pages.admin;
import com.solidstategroup.radar.model.user.ProfessionalUser;
import com.solidstategroup.radar.service.UserManager;
import com.solidstategroup.radar.web.behaviours.RadarBehaviourFactory;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;
import java.util.Date;
public class AdminUserPage extends AdminsBasePage {
@SpringBean
private UserManager userManager;
private static final String PARAM_ID = "ID";
private boolean editMode = false;
private boolean newUser = false;
public AdminUserPage() {
this(new PageParameters());
}
public AdminUserPage(PageParameters parameters) {
super();
final ProfessionalUser user;
// if id is empty or -1 then its a new user else try pull back record
StringValue idValue = parameters.get(PARAM_ID);
if (idValue.isEmpty() || idValue.toLong() == -1) {
user = new ProfessionalUser();
// if its new user just show edit mode straight away
editMode = true;
newUser = true;
} else {
user = userManager.getProfessionalUser(idValue.toLongObject());
}
CompoundPropertyModel<ProfessionalUser> professionalUserModel =
new CompoundPropertyModel<ProfessionalUser>(user);
final FeedbackPanel feedback = new FeedbackPanel("feedback");
feedback.setOutputMarkupId(true);
feedback.setOutputMarkupPlaceholderTag(true);
add(feedback);
final Form<ProfessionalUser> userForm = new Form<ProfessionalUser>("userForm", professionalUserModel) {
protected void onSubmit() {
try {
userManager.saveProfessionalUser(getModelObject());
if (newUser) {
setResponsePage(AdminUsersPage.class);
}
} catch (Exception e) {
- error("Could not save user: " + e.toString());
+ error("Could not save user");
}
}
};
add(userForm);
UserLabel idLabel = new UserLabel("idLabel", new PropertyModel<Long>(user, "id"));
idLabel.setHideable(false);
userForm.add(idLabel);
userForm.add(new UserLabel("surnameLabel", new PropertyModel<String>(user, "surname")));
userForm.add(new UserTextField("surname"));
userForm.add(new UserLabel("forenameLabel", new PropertyModel<String>(user, "forename")));
userForm.add(new UserTextField("forename"));
userForm.add(new UserLabel("titleLabel", new PropertyModel<String>(user, "title")));
userForm.add(new UserTextField("title"));
userForm.add(new UserLabel("roleLabel", new PropertyModel<String>(user, "role")));
userForm.add(new UserTextField("role"));
userForm.add(new UserLabel("emailLabel", new PropertyModel<String>(user, "email")));
userForm.add(new UserTextField("email"));
userForm.add(new UserLabel("phoneLabel", new PropertyModel<String>(user, "phone")));
userForm.add(new UserTextField("phone"));
userForm.add(new UserLabel("centreLabel", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserTextField("centre", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserLabel("dateRegisteredLabel", new PropertyModel<Date>(user, "dateRegistered")));
userForm.add(new UserTextField("dateRegistered"));
UserLabel usernameLabel = new UserLabel("usernameLabel", user.getUsername());
// hide this field if new user as username will be set to email
usernameLabel.setVisible(!newUser);
usernameLabel.setHideable(false);
userForm.add(usernameLabel);
/**
* Add a container to hold links for Edit and Delete options
* This will show when not in editMode
*/
WebMarkupContainer userOptions = new WebMarkupContainer("userOptions") {
public boolean isVisible() {
return !editMode;
}
};
userForm.add(userOptions);
userOptions.add(new AjaxLink("edit") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = true;
ajaxRequestTarget.add(userForm);
}
});
AjaxLink deleteLink = new AjaxLink("delete") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
try {
userManager.deleteProfessionalUser(user);
setResponsePage(AdminUsersPage.class);
} catch (Exception e) {
ajaxRequestTarget.add(feedback);
error("Could not delete user: " + e.toString());
}
}
};
userOptions.add(deleteLink);
deleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
/**
* Add a container to hold the options for when the page is in edit mode
*/
WebMarkupContainer editOptions = new WebMarkupContainer("editOptions") {
public boolean isVisible() {
return editMode;
}
};
editOptions.add(new AjaxSubmitLink("update") {
protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
editMode = false;
ajaxRequestTarget.add(feedback);
ajaxRequestTarget.add(userForm);
}
protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
+ editMode = true;
ajaxRequestTarget.add(feedback);
+ ajaxRequestTarget.add(userForm);
}
});
editOptions.add(new AjaxLink("cancel") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = false;
// if its a new user then cancel back to list
if (newUser) {
setResponsePage(AdminUsersPage.class);
} else {
ajaxRequestTarget.add(userForm);
}
}
});
userForm.add(editOptions);
add(new BookmarkablePageLink<AdminUsersPage>("back",
AdminUsersPage.class));
}
/**
* Helper class to add a label to the page that will show and hide when the form is reloading
* depending on the mode of the page - Edit will be hidden, Normal will be shown
*/
private class UserLabel extends Label {
private boolean isHideable = true;
private UserLabel(String s, String s1) {
super(s, s1);
}
private UserLabel(String s, IModel<?> iModel) {
super(s, iModel);
}
public boolean isVisible() {
return !isHideable || !editMode;
}
public boolean isHideable() {
return isHideable;
}
public void setHideable(boolean hideable) {
isHideable = hideable;
}
}
/**
* Helper class to add a text field to the form that will show and hide when the form is reloaded and depending
* on page mode - Edit will be shown, Normal will be hidden
*/
private class UserTextField extends RequiredTextField {
private UserTextField(String s) {
super(s);
}
private UserTextField(String s, IModel iModel) {
super(s, iModel);
}
public boolean isVisible() {
return editMode;
}
}
public static PageParameters getPageParameters(ProfessionalUser user) {
return new PageParameters().set(PARAM_ID, user.getId());
}
}
| false | true | public AdminUserPage(PageParameters parameters) {
super();
final ProfessionalUser user;
// if id is empty or -1 then its a new user else try pull back record
StringValue idValue = parameters.get(PARAM_ID);
if (idValue.isEmpty() || idValue.toLong() == -1) {
user = new ProfessionalUser();
// if its new user just show edit mode straight away
editMode = true;
newUser = true;
} else {
user = userManager.getProfessionalUser(idValue.toLongObject());
}
CompoundPropertyModel<ProfessionalUser> professionalUserModel =
new CompoundPropertyModel<ProfessionalUser>(user);
final FeedbackPanel feedback = new FeedbackPanel("feedback");
feedback.setOutputMarkupId(true);
feedback.setOutputMarkupPlaceholderTag(true);
add(feedback);
final Form<ProfessionalUser> userForm = new Form<ProfessionalUser>("userForm", professionalUserModel) {
protected void onSubmit() {
try {
userManager.saveProfessionalUser(getModelObject());
if (newUser) {
setResponsePage(AdminUsersPage.class);
}
} catch (Exception e) {
error("Could not save user: " + e.toString());
}
}
};
add(userForm);
UserLabel idLabel = new UserLabel("idLabel", new PropertyModel<Long>(user, "id"));
idLabel.setHideable(false);
userForm.add(idLabel);
userForm.add(new UserLabel("surnameLabel", new PropertyModel<String>(user, "surname")));
userForm.add(new UserTextField("surname"));
userForm.add(new UserLabel("forenameLabel", new PropertyModel<String>(user, "forename")));
userForm.add(new UserTextField("forename"));
userForm.add(new UserLabel("titleLabel", new PropertyModel<String>(user, "title")));
userForm.add(new UserTextField("title"));
userForm.add(new UserLabel("roleLabel", new PropertyModel<String>(user, "role")));
userForm.add(new UserTextField("role"));
userForm.add(new UserLabel("emailLabel", new PropertyModel<String>(user, "email")));
userForm.add(new UserTextField("email"));
userForm.add(new UserLabel("phoneLabel", new PropertyModel<String>(user, "phone")));
userForm.add(new UserTextField("phone"));
userForm.add(new UserLabel("centreLabel", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserTextField("centre", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserLabel("dateRegisteredLabel", new PropertyModel<Date>(user, "dateRegistered")));
userForm.add(new UserTextField("dateRegistered"));
UserLabel usernameLabel = new UserLabel("usernameLabel", user.getUsername());
// hide this field if new user as username will be set to email
usernameLabel.setVisible(!newUser);
usernameLabel.setHideable(false);
userForm.add(usernameLabel);
/**
* Add a container to hold links for Edit and Delete options
* This will show when not in editMode
*/
WebMarkupContainer userOptions = new WebMarkupContainer("userOptions") {
public boolean isVisible() {
return !editMode;
}
};
userForm.add(userOptions);
userOptions.add(new AjaxLink("edit") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = true;
ajaxRequestTarget.add(userForm);
}
});
AjaxLink deleteLink = new AjaxLink("delete") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
try {
userManager.deleteProfessionalUser(user);
setResponsePage(AdminUsersPage.class);
} catch (Exception e) {
ajaxRequestTarget.add(feedback);
error("Could not delete user: " + e.toString());
}
}
};
userOptions.add(deleteLink);
deleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
/**
* Add a container to hold the options for when the page is in edit mode
*/
WebMarkupContainer editOptions = new WebMarkupContainer("editOptions") {
public boolean isVisible() {
return editMode;
}
};
editOptions.add(new AjaxSubmitLink("update") {
protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
editMode = false;
ajaxRequestTarget.add(feedback);
ajaxRequestTarget.add(userForm);
}
protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
ajaxRequestTarget.add(feedback);
}
});
editOptions.add(new AjaxLink("cancel") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = false;
// if its a new user then cancel back to list
if (newUser) {
setResponsePage(AdminUsersPage.class);
} else {
ajaxRequestTarget.add(userForm);
}
}
});
userForm.add(editOptions);
add(new BookmarkablePageLink<AdminUsersPage>("back",
AdminUsersPage.class));
}
| public AdminUserPage(PageParameters parameters) {
super();
final ProfessionalUser user;
// if id is empty or -1 then its a new user else try pull back record
StringValue idValue = parameters.get(PARAM_ID);
if (idValue.isEmpty() || idValue.toLong() == -1) {
user = new ProfessionalUser();
// if its new user just show edit mode straight away
editMode = true;
newUser = true;
} else {
user = userManager.getProfessionalUser(idValue.toLongObject());
}
CompoundPropertyModel<ProfessionalUser> professionalUserModel =
new CompoundPropertyModel<ProfessionalUser>(user);
final FeedbackPanel feedback = new FeedbackPanel("feedback");
feedback.setOutputMarkupId(true);
feedback.setOutputMarkupPlaceholderTag(true);
add(feedback);
final Form<ProfessionalUser> userForm = new Form<ProfessionalUser>("userForm", professionalUserModel) {
protected void onSubmit() {
try {
userManager.saveProfessionalUser(getModelObject());
if (newUser) {
setResponsePage(AdminUsersPage.class);
}
} catch (Exception e) {
error("Could not save user");
}
}
};
add(userForm);
UserLabel idLabel = new UserLabel("idLabel", new PropertyModel<Long>(user, "id"));
idLabel.setHideable(false);
userForm.add(idLabel);
userForm.add(new UserLabel("surnameLabel", new PropertyModel<String>(user, "surname")));
userForm.add(new UserTextField("surname"));
userForm.add(new UserLabel("forenameLabel", new PropertyModel<String>(user, "forename")));
userForm.add(new UserTextField("forename"));
userForm.add(new UserLabel("titleLabel", new PropertyModel<String>(user, "title")));
userForm.add(new UserTextField("title"));
userForm.add(new UserLabel("roleLabel", new PropertyModel<String>(user, "role")));
userForm.add(new UserTextField("role"));
userForm.add(new UserLabel("emailLabel", new PropertyModel<String>(user, "email")));
userForm.add(new UserTextField("email"));
userForm.add(new UserLabel("phoneLabel", new PropertyModel<String>(user, "phone")));
userForm.add(new UserTextField("phone"));
userForm.add(new UserLabel("centreLabel", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserTextField("centre", new PropertyModel<Long>(user.getCentre(), "id")));
userForm.add(new UserLabel("dateRegisteredLabel", new PropertyModel<Date>(user, "dateRegistered")));
userForm.add(new UserTextField("dateRegistered"));
UserLabel usernameLabel = new UserLabel("usernameLabel", user.getUsername());
// hide this field if new user as username will be set to email
usernameLabel.setVisible(!newUser);
usernameLabel.setHideable(false);
userForm.add(usernameLabel);
/**
* Add a container to hold links for Edit and Delete options
* This will show when not in editMode
*/
WebMarkupContainer userOptions = new WebMarkupContainer("userOptions") {
public boolean isVisible() {
return !editMode;
}
};
userForm.add(userOptions);
userOptions.add(new AjaxLink("edit") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = true;
ajaxRequestTarget.add(userForm);
}
});
AjaxLink deleteLink = new AjaxLink("delete") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
try {
userManager.deleteProfessionalUser(user);
setResponsePage(AdminUsersPage.class);
} catch (Exception e) {
ajaxRequestTarget.add(feedback);
error("Could not delete user: " + e.toString());
}
}
};
userOptions.add(deleteLink);
deleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
/**
* Add a container to hold the options for when the page is in edit mode
*/
WebMarkupContainer editOptions = new WebMarkupContainer("editOptions") {
public boolean isVisible() {
return editMode;
}
};
editOptions.add(new AjaxSubmitLink("update") {
protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
editMode = false;
ajaxRequestTarget.add(feedback);
ajaxRequestTarget.add(userForm);
}
protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
editMode = true;
ajaxRequestTarget.add(feedback);
ajaxRequestTarget.add(userForm);
}
});
editOptions.add(new AjaxLink("cancel") {
public void onClick(AjaxRequestTarget ajaxRequestTarget) {
editMode = false;
// if its a new user then cancel back to list
if (newUser) {
setResponsePage(AdminUsersPage.class);
} else {
ajaxRequestTarget.add(userForm);
}
}
});
userForm.add(editOptions);
add(new BookmarkablePageLink<AdminUsersPage>("back",
AdminUsersPage.class));
}
|
diff --git a/src/com/hotcats/textreminder/TextReceiver.java b/src/com/hotcats/textreminder/TextReceiver.java
index bd60a0b..d61ed30 100644
--- a/src/com/hotcats/textreminder/TextReceiver.java
+++ b/src/com/hotcats/textreminder/TextReceiver.java
@@ -1,97 +1,97 @@
package com.hotcats.textreminder;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Receives text messages and alarm rings to alert the user if there are unread
* texts.
*/
public class TextReceiver extends BroadcastReceiver {
public static final String ALARM_RING = "com.hotcats.textreminder.TextReceiver.ALARM_RING";
public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
public static final long[] VIBRATE_PATTERN = { 0, 250, 250, 250 };
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = Utilities.constructAlarmPendingIntent(context);
if (ALARM_RING.equals(intent.getAction())) {
handleAlarm(context, am, pi);
} else if (SMS_RECEIVED.equals(intent.getAction())) {
handleText(context, am, pi);
} else {
Log.w("all", "invalid intent received: " + intent.getAction());
}
}
/**
* Handle an alarm ring: if there are unread texts alert the user, otherwise
* cancel the alarm.
*/
private void handleAlarm(Context context, AlarmManager am, PendingIntent pi) {
Log.i("alarm", "alarm ring received");
Cursor c = context.getContentResolver().query(SMS_INBOX, null,
"read = 0", null, null);
int unread = c.getCount();
c.close();
Log.i("alarm", "found " + unread + " unread texts");
if (unread == 0) {
Utilities.cancelAlarm(am, pi);
Log.i("alarm", "cancelled alarm");
} else {
Vibrator v = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(VIBRATE_PATTERN, -1);
}
}
/**
* Handle receiving a text: set an alarm to alert the user.
*/
private void handleText(Context context, AlarmManager am, PendingIntent pi) {
Log.i("text", "text message recieved!");
- // TODO: How can look this and repeatDelay up only once instead of every
- // time this method is called?
+ // TODO: How can I look this and repeatDelay up only once instead of
+ // every time this method is called?
boolean enabledDefault = context.getResources().getBoolean(
R.bool.pref_enabled_default);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean enabled = prefs.getBoolean(Preferences.PREF_ENABLED,
enabledDefault);
if (enabled) {
String repeatDelayDefault = context.getResources().getString(
R.string.pref_repeatDelay_default);
int repeatDelay = 1000 * Integer.parseInt(prefs.getString(
Preferences.PREF_REPEAT_DELAY, repeatDelayDefault));
Log.i("text", "setting alarm to repeat every " + repeatDelay
+ " ms");
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ repeatDelay, repeatDelay, pi);
} else {
Log.i("text", "disabled, not setting alarm");
}
}
}
| true | true | private void handleText(Context context, AlarmManager am, PendingIntent pi) {
Log.i("text", "text message recieved!");
// TODO: How can look this and repeatDelay up only once instead of every
// time this method is called?
boolean enabledDefault = context.getResources().getBoolean(
R.bool.pref_enabled_default);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean enabled = prefs.getBoolean(Preferences.PREF_ENABLED,
enabledDefault);
if (enabled) {
String repeatDelayDefault = context.getResources().getString(
R.string.pref_repeatDelay_default);
int repeatDelay = 1000 * Integer.parseInt(prefs.getString(
Preferences.PREF_REPEAT_DELAY, repeatDelayDefault));
Log.i("text", "setting alarm to repeat every " + repeatDelay
+ " ms");
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ repeatDelay, repeatDelay, pi);
} else {
Log.i("text", "disabled, not setting alarm");
}
}
| private void handleText(Context context, AlarmManager am, PendingIntent pi) {
Log.i("text", "text message recieved!");
// TODO: How can I look this and repeatDelay up only once instead of
// every time this method is called?
boolean enabledDefault = context.getResources().getBoolean(
R.bool.pref_enabled_default);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean enabled = prefs.getBoolean(Preferences.PREF_ENABLED,
enabledDefault);
if (enabled) {
String repeatDelayDefault = context.getResources().getString(
R.string.pref_repeatDelay_default);
int repeatDelay = 1000 * Integer.parseInt(prefs.getString(
Preferences.PREF_REPEAT_DELAY, repeatDelayDefault));
Log.i("text", "setting alarm to repeat every " + repeatDelay
+ " ms");
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ repeatDelay, repeatDelay, pi);
} else {
Log.i("text", "disabled, not setting alarm");
}
}
|
diff --git a/ForRealRobot/src/onRobot/BTCommRobot.java b/ForRealRobot/src/onRobot/BTCommRobot.java
index 14f55cc..85fd802 100644
--- a/ForRealRobot/src/onRobot/BTCommRobot.java
+++ b/ForRealRobot/src/onRobot/BTCommRobot.java
@@ -1,1170 +1,1176 @@
package onRobot;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import lejos.nxt.Battery;
import lejos.nxt.Button;
import lejos.nxt.LCD;
import lejos.nxt.LightSensor;
import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
import lejos.nxt.SensorPort;
import lejos.nxt.Sound;
import lejos.nxt.TouchSensor;
import lejos.nxt.UltrasonicSensor;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
public class BTCommRobot implements CMD {
private final float wheelsDiameter = 5.43F;
// private static final float wheelDiameterLeft = 5.43F;
// private static final float wheelDiameterRight = 5.43F;
private final float trackWidth = 16.40F;
private int pcSendLength=2;
private int robotReplyLength=0;
int[] _command = new int[2];
int[] _reply;
boolean _keepItRunning = true;
String _connected = "Connected";
String _waiting = "Waiting...";
String _closing = "Closing...";
DataInputStream _dis = null;
DataOutputStream _dos = null;
BTConnection _btc = null;
final TouchSensor touchSensor;
final LightSensor lightSensor;
final UltrasonicSensor ultrasonicSensor;
final NXTRegulatedMotor sensorMotor ;
final DifferentialPilot pilot;
private SecondThread secondThread;
private Queue<int[]> replyAdditionList;
private boolean calibratedLightHigh=false;
private boolean calibratedLightLow=false;
private int typeBeforLastWood=LightType.WOOD;
private int lastLightType=LightType.WOOD;
private List<Position> barCodePositionList;
private boolean fromSecondThread=false;
public BTCommRobot() {
barCodePositionList= new ArrayList<Position>();
replyAdditionList= new Queue<int[]>();
touchSensor = new TouchSensor(SensorPort.S1);
lightSensor= new LightSensor(SensorPort.S3);
ultrasonicSensor = new UltrasonicSensor(SensorPort.S2);
pilot = new DifferentialPilot(wheelsDiameter, trackWidth);
sensorMotor = Motor.A;
sensorMotor.removeListener();
sensorMotor.resetTachoCount();
sensorMotor.setSpeed(100*Battery.getVoltage());
LCD.drawString(_waiting,0,0);
LCD.refresh();
// Slave waits for Master to connect
_btc = Bluetooth.waitForConnection();
Sound.twoBeeps();
LCD.clear();
LCD.drawString(_connected,0,0);
LCD.refresh();
// Set up the data input and output streams
_dis = _btc.openDataInputStream();
_dos = _btc.openDataOutputStream();
Sound.beepSequenceUp();
secondThread= new SecondThread();
secondThread.addAction(new PoseUpdateAction(pilot));
secondThread.start();
Writer.forcedWrite("na secondThread start");
secondThread.addAction(new CheckForBarCodeAction(this));
Writer.forcedWrite("We will now startCommunication");
startCommunication();
}
public static void main(String [] args) throws Exception
{
try{
Writer.write("We will now make a BtCommRobot");
new BTCommRobot();
Writer.write("The program has ended normally");
Writer.close();
}catch(Exception e){
Sound.buzz();
Writer.forcedWrite("There was an exception: " + e.getCause()+", "+e.getClass()+", "+ e.getMessage());
Writer.close();
LCD.clear();
e.printStackTrace(System.out);
LCD.refresh();
Button.waitForAnyPress();
}
}
private void startCommunication() {
try {
startWhileLoop();
} catch (IOException e1) {
Writer.write("we were trying to do the while loop, but IOException");
}
// Slave begins disconnect cycle
//try{Thread.sleep(5000);}
//catch(InterruptedException e){
// System.exit(0);
//}
// Close the data input and output streams
try {
_dis.close();
_dos.close();
Thread.sleep(100); // wait for data to drain
LCD.clear();
LCD.drawString(_closing,0,0);
LCD.refresh();
// Close the bluetooth connection from the Slave's point-of-view
_btc.close();
LCD.clear();
} catch (IOException e) {
//this schould not happen
Writer.write("we were trying to close the connection");
}
catch(InterruptedException e){
Writer.write("The thread was interrupted before we could close the connection");
}
}
//TODO checken of dit nog bruikbaar is of weg moet
// private void startBarcodePolling(){
// while(true){
// if(detectBlackLine()){
// int[] barcode = scanBarcode();
// robotReplyLength = 8;
// for(int i = 0; i<4; i++){
// _reply[4+i] = barcode[i];
// }
// }
//
// }
// }
private void startWhileLoop() throws IOException {
while (_keepItRunning)
{
handleOneCommand();
}// End of while loop
}
private void handleOneCommand() throws IOException {
// Fetch the Master's command and argument
int command=_dis.readByte();
// Writer.write("we read command " + command);
double argument= (_dis.readInt())/100.0;
// Writer.write("we read argument " + argument);
// We set the robotReplyLength to 0 because this is the case for
// most of the commands.
robotReplyLength = 0;
_reply=new int[4];
// Respond to the Master's command which is stored in command[0]
// Writer.write("command received" + command);
switch (command) {
// Get the battery voltage
case STOP:
stop();
break;
case GETPOSE:
_reply = getPose();
robotReplyLength=4;
break;
case BATTERY:
_reply[0]=getBattery();
robotReplyLength=1;
break;
// Manual Ping
case CALIBRATELSHIGH:
calibrateLightSensorHigh();
break;
case CALIBRATELSLOW:
calibrateLightSensorLow();
break;
case TURNSENSOR:
turnSensor((int)argument);
break;
case TURNSENSORTO:
turnSensorTo((int)argument);
break;
// Manual Ping
case GETSENSORVALUES:
_reply=getSensorValues();
robotReplyLength=4;
break;
// Travel forward requested distance and return sonic sensor distance
case TRAVEL:
travel(argument);
break;
// Rotate requested angle and return sonic sensor distance
case TURN:
turn(argument);
break;
// Master warns of a bluetooth disconnect; set while loop so it stops
case KEEPTRAVELLING:
keepTraveling(argument>0);
break;
case KEEPTURNING:
keepTurning(argument>0);
break;
case DISCONNECT:
disconnect();
break;
case SCANBARCODE:
_reply=scanBarcode();
if(_reply!=null){
robotReplyLength=4;}
break;
case DRIVESLOW:
driveSlow();
break;
case DRIVEFAST:
driveFast();
break;
case PLAYTUNE:
playTune();
break;
case WAIT5:
wait5();
break;
case STRAIGHTEN:
straighten();
break;
case SETTODEFAULTTRAVELSPEED:
setToDefaultTravelSpeed();
break;
case SETTODEFAULTTURNSPEED:
setToDefaultTurnSpeed();
break;
case SETSLOWTRAVELSPEED:
setSlowTravelSpeed(argument);
break;
case SETHIGHTRAVELSPEED:
setHighTravelSpeed(argument);
break;
case SETWHEELDIAMETER:
setWheelDiameter(argument);
break;
case SETTRACKWIDTH:
setTrackWidth(argument);
break;
case SETROTATION:
setRotation(argument);
break;
case SETX:
setX(argument);
break;
case SETY:
setY(argument);
break;
case SETDEFAULTTRAVELSPEED:
setDefaultTravelSpeed(argument);
break;
case SETDEFAULTTURNSPEED:
setDefaultTurnSpeed(argument);
break;
case SETTURNSPEED:
setTurnSpeed(argument);
break;
case SETTRAVELSPEED:
setTravelSpeed(argument);
break;
case AUTOCALIBRATELS:
autoCalibrateLightSensor((int)argument);
break;
+ case FETCHBALL:
+ fetchBall();
+ break;
+ case DONOTHING:
+ doNothing();
+ break;
default:
throw new RuntimeException("A case was not implemented or did not break");
} // End case structure
int numberOfSpecialReplies=replyAdditionList.size();
if (numberOfSpecialReplies == 0 && robotReplyLength == 0) {
//if there is nothing to send, then we just send 0
_dos.writeByte(0);
_dos.flush();
} else {
// we will first write how many replies there will be
_dos.writeByte(numberOfSpecialReplies + 1);
//now we write how long the normal reply will be.
_dos.writeByte(robotReplyLength);
_dos.flush();
//now we write the normal reply
for (int k = 0; k < robotReplyLength; k++) {
_dos.writeInt(_reply[k]);
_dos.flush();
}
//now we write the special replies
for (int i = 0; i < numberOfSpecialReplies; i++) {
Writer.write("start of write specialReply: "+i);
int[] specialReply=(int[]) replyAdditionList.pop();
//We first write the specialReplyCode
_dos.writeByte(specialReply[0]);
_dos.flush();
for(int j=1;j<specialReply.length;j++){
Writer.write("wrote specialReply argument: " +j+": "+ specialReply[j]);
_dos.writeInt(specialReply[j]);
_dos.flush();
}
Writer.write("wrote specialReply: "+i);
}
// Writer.write("command replied " + command);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.exit(0);
}
}
// LCD.refresh();
}
@Override
public void travel(double distance) {
pilot.travelNonBlocking(distance);
}
// private boolean justChecked = false;
// private boolean checkingBarcode = false;
// private void travelWithCheck(double distance) {
// Position startpos = pilot.getPosition();
// double startX = startpos.getX();
// double startY = startpos.getY();
// boolean mayMove = true;
// keepTraveling(true);
// while(!detectBlackLine() && mayMove){
// Position newpos = pilot.getPosition();
// if(distance <= Math.sqrt(Math.pow(newpos.getX() - startX, 2) + Math.pow(newpos.getY() - startY, 2)))
// mayMove = false;
// }
// stop();
// stop();
// if(detectBlackLine()){
// checkingBarcode = true;
// justChecked = true;
// int[] barcode = scanBarcode();
// robotReplyLength = 8;
// _reply = new int[8];
// for(int i = 0; i<4; i++){
// _reply[4+i] = barcode[i];
// }
// checkingBarcode = false;
// }
// mayMove = true;
// }
/**
*
* @param SpecialReplyCode
* @param specialReply
* @pre the first int in the array should be the specialReplyCode and thus negative
*/
public void addSomethingToReply(byte specialReplyCode, int[] specialReply){
if(specialReplyCode>=0){
Writer.write("the format of the specialReply was incorrect");
}
int[] completeSpecialReply=new int[specialReply.length+1];
completeSpecialReply[0]=specialReplyCode;
int i=1;
for(int replyPart: specialReply){
completeSpecialReply[i++]=replyPart;
}
replyAdditionList.push(completeSpecialReply);
}
@Override
public void turn(double angle) {
pilot.rotateNonBlocking(angle);
}
@Override
public void turnSensor(int angle) {
sensorMotor.rotate(angle);
}
@Override
public void turnSensorTo(int angle) {
//the if is for correction of the pulling cable
if(angle<-45)angle-=5;
sensorMotor.rotateTo(angle);
}
@Override
public void stop() {
pilot.stop();
return;
}
@Override
public int[] getPose() {
Position position= pilot.getPosition();
return new int[]{(int)position.getX(), (int)position.getY(), (int)pilot.getRotation(), pilot.isMoving()?1:0};
}
@Override
public int[] getSensorValues() {
int[] result = new int[4];
result[0] = readLightValue();
result[1] =ultrasonicSensor.getDistance();
if(touchSensor.isPressed() == true)
result[2] =1;
else
result[2] =-1;
result[3] = sensorMotor.getTachoCount();
return result;
}
public int readLightValue(){
return readLight(false);
}
public int readLightType(){
return readLight(true);
}
private int readLight(boolean justType) {
int readValue=lightSensor.readValue();
int thisLightType=LightType.getLightType(readValue);
if(thisLightType==LightType.WOOD){
typeBeforLastWood=lastLightType;
}
lastLightType=thisLightType;
return justType?thisLightType:readValue;
}
public boolean isTouching(){
return touchSensor.isPressed();
}
public int readUltraSonicSensor(){
int firstRead=ultrasonicSensor.getDistance();
int lastRead=ultrasonicSensor.getDistance();
while(firstRead-lastRead>1||firstRead-lastRead<-1){
firstRead=lastRead;
lastRead=ultrasonicSensor.getDistance();
}
return Math.round(lastRead);
}
public boolean detectBlackValue() {
return readLightType()==LightType.BLACK;
}
// public boolean detectWoodToBlack() {
// readLightValue();
// readLightValue();
// int numberOfReadValues=lastLightValues.size();
// if(numberOfReadValues<4){
// return false;}
// boolean detected=true;
// int index = numberOfReadValues;
// //We first read the two last values
// for (index = numberOfReadValues; index >numberOfReadValues-2; index--) {
// if(!LightType.isBlack(lastLightValues.get(index))){
// detected=false;
// }
// }
//
//
// if(detected){
// //if the two last values were black, then we read the following black values
// while (LightType.isBlack(lastLightValues.get(index))) {
// index--;
// }
// //Now we take the first 2 non-black values and check whether they ar both wood
// for (int i = index; i > index - 2; i--) {
// if (!LightType.isWood(lastLightValues.get(i))) {
// detected = false;
// }
// }
// }
// lastLightValues.clear();
// return detected;
//
// }
public boolean detectWhiteValue() {
return readLightType()==LightType.WHITE;
}
public boolean detect2TimesWhite() {
return detectWhiteValue()&&detectWhiteValue();
}
public boolean detect2TimesBlack() {
return detectBlackValue()
&&detectBlackValue();
}
// public boolean detectWoodToWhite() {
// readLightValue();
// readLightValue();
// int numberOfReadValues=lastLightValues.size();
// if(numberOfReadValues<4){
// return false;}
// boolean detected=true;
// int index = numberOfReadValues;
// //We first read the two last values
// for (index = numberOfReadValues; index >numberOfReadValues-2; index--) {
// if(!LightType.isWhite(lastLightValues.get(index))){
// detected=false;
// }
// }
//
//
// if(detected){
// //if the two last values were white, then we read the following black values
// while (LightType.isWhite(lastLightValues.get(index))) {
// index--;
// }
// //Now we take the first 2 non-white values and check whether they ar both wood
// for (int i = index; i > index - 2; i--) {
// if (!LightType.isWood(lastLightValues.get(i))) {
// detected = false;
// }
// }
// }
// lastLightValues.clear();
// return detected;
// }
@Override
public int getBattery() {
return Battery.getVoltageMilliVolt();
}
@Override
public void calibrateLightSensorHigh() {
lightSensor.calibrateHigh();
calibratedLightHigh=true;
}
@Override
public void calibrateLightSensorLow() {
lightSensor.calibrateLow();
calibratedLightLow=true;
}
@Override
public void keepTurning(boolean left) {
pilot.keepTurning(left);
}
@Override
public void keepTraveling(boolean forward) {
if(forward)
pilot.forward();
else pilot.backward();
}
@Override
public void disconnect() {
_keepItRunning = false;
for(int k = 0; k < 4; k++){
_reply[k] = 255;
}
}
private void findBlackLine(){
Writer.write("findBlackLine is called");
pilot.forward();
while (!detect2TimesBlack());
pilot.stop();
Writer.write("findBlackLine returned");
}
@Override
public int[] scanBarcode() {
//return scanBarcodeV1();
return scanBarcodeV2();
}
public int[] scanBarcodeV2() {
initiateBarcodeReading();
boolean[] allBits=new boolean[10000];
final int noWantedWoods=(int) (200*(5.0/pilot.getTravelSpeed()));
int numberOfBits=0;
int dismissed=0;
int noWoods=0;
final int sampleDivider=4;
pilot.forward();
while(!detect2TimesBlack()){
}
while(noWoods<noWantedWoods){
// we throw away some of the read values
int lightType = readLightType();
if (lightType== LightType.WOOD) {
noWoods++;
} else {
noWoods = 0;
}
if (dismissed++ >= sampleDivider) {
// This is to lower the sample-rate without slowing down wood
// Detection
dismissed = 0;
} else {
allBits[numberOfBits++] = lightType!=LightType.BLACK;
}
}
pilot.stop();
numberOfBits-=(noWoods/sampleDivider);
Writer.write(""+numberOfBits);
int[] realBits= new int[]{0,0,0,0,0,0};
for(int j=1;j<7;j++){
int numberOf1s=0;
for(int k= (int) Math.round((numberOfBits*(j+0.25))/8.0);k<Math.round(numberOfBits*(j+0.75)/8.0); k++ ){
if(allBits[k]){
numberOf1s++;
}
}
Writer.write("NumberOf1s is: "+numberOf1s);
if(numberOf1s>numberOfBits/8/8){
realBits[j-1]=1;
}
else{
realBits[j-1]=0;
}
}
if(!fromSecondThread){
endBarcodeReading();
}
return makeBarcodeInfo(realBits);
}
public int[] scanBarcodeV1() {
initiateBarcodeReading();
int[] bits = new int[32];
int timesTheSame=1;
for(int i = 0; i<32; i++){
pilot.travelBlocking(0.5);
int lightValue=readLightValue();
if(lightValue<0){
bits[i] = 0;
}
else{
bits[i] = 1;
}
if(i!=0&&bits[i]==bits[i-1]){
timesTheSame++;
}
else{
timesTheSame=1;
}
Writer.write(timesTheSame+"th: "+ bits[i]+": "+lightValue);
}
int[] realBits = new int[6];
for(int i = 1; i<7; i++){
int count1 =0;
for(int j= 0; j<4; j++){
if(bits[4*i+j] ==1) count1++;
}
if(count1 == 2) return null;
else if(count1>2) realBits[i-1] = 1;
else realBits[i-1] = 0;
Writer.write("realBit "+ (i-1) +": "+realBits[i-1]);
}
//We now make the robot go forward until there is no barcode anymore
pilot.forward();
while(detectBlackValue());
pilot.stop();
pilot.travelBlocking(0.5);
endBarcodeReading();
return makeBarcodeInfo(realBits);
}
private int[] makeBarcodeInfo(int[] realBits) {
int decimal = calculateDecimal(realBits);
Writer.write("We are now going to return the barcode: "+ decimal);
Position pos = pilot.getPosition();
final int MAZECONSTANT = 40;
int lowx = (int) (Math.floor((pos.getX())/MAZECONSTANT))*MAZECONSTANT;
int lowy = (int) (Math.floor((pos.getY())/MAZECONSTANT))*MAZECONSTANT;
return new int[]{lowx + 20,lowy+20,decimal,(int) pilot.getRotation()};
}
private int calculateDecimal(int[] realBits) {
String bitString=new String();
for(int bit:realBits){
bitString=new String(bitString+bit);
}
Writer.write(bitString);
int decimal = 0;
for(int i = 0; i< 6; i++){
Writer.write("i: "+i+" d: "+decimal+" b: "+realBits[5-i]+" pw: "+power(2,i)+" pr: "+realBits[5-i]*power(2,i));
decimal = (decimal + realBits[5-i]*power(2, i));
}
return decimal;
}
private int power(int number, int power){
return power(number,number, power);
}
private int power(int number,int groundNumber, int power) {
if(power==0){
if(number==0)
return 0;
else return 1;
}
else if(power==1){
return number;}
else return power(number*groundNumber, groundNumber, power-1);
}
private void endBarcodeReading() {
// System.out.println(lowx + 20 +" " +lowy+20+" "+decimal+" "+getPose()[2]);
setToDefaultTravelSpeed();
pilot.setReadingBarcode(false);
pilot.enablePoseUpdate();
}
private void initiateBarcodeReading() {
pilot.setReadingBarcode(true);
Writer.write("We want to find a barcode");
pilot.setToSlowTravelSpeed();
// if(!woodToBlackAlreadyDetected&&!detectBlackValue()) {
//// Writer.write("We do not detect the black line yet");
// findBlackLine();
// }
if (fromSecondThread) {
final int noWantedWoods = (int) (200 * (pilot.getTravelSpeed() / 5));
int noWoods = 0;
pilot.backward();
while (noWoods < noWantedWoods) {
if (readLightType() == LightType.WOOD) {
noWoods++;
} else {
noWoods = 0;
}
}
pilot.stop();
}
pilot.disablePoseUpdate();
Sound.beepSequenceUp();
}
private boolean lightIsCalibrated() {
return calibratedLightHigh&&calibratedLightLow;
}
@Override
public void setDefaultTravelSpeed(double speed){
pilot.setDefaultTravelSpeed(speed);
}
@Override
public void setDefaultTurnSpeed(double speed){
pilot.setDefaultRotateSpeed(speed);
}
@Override
public void driveSlow() {
pilot.setToSlowTravelSpeed();
}
@Override
public void driveFast() {
pilot.setToFastTravelSpeed();
}
public void driveDefault(){
pilot.setToDefaultTravelSpeed();
}
@Override
public void playTune() {
Sound.twoBeeps();
try{
Sound.playSample(new File("tune.wav"));
}
catch(Exception e){
final short [] note = {
2349,115, 0,5, 1760,165, 0,35, 1760,28, 0,13, 1976,23,
0,18, 1760,18, 0,23, 1568,15, 0,25, 1480,103, 0,18, 1175,180, 0,20, 1760,18,
0,23, 1976,20, 0,20, 1760,15, 0,25, 1568,15, 0,25, 2217,98, 0,23, 1760,88,
0,33, 1760,75, 0,5, 1760,20, 0,20, 1760,20, 0,20, 1976,18, 0,23, 1760,18,
0,23, 2217,225, 0,15, 2217,218};
for(int i=0;i<note.length; i+=2) {
final short w = note[i+1];
final int n = note[i];
if (n != 0) Sound.playTone(n, w*10);
try { Thread.sleep(w*10); } catch (InterruptedException e1) {}
}
}
}
@Override
public void wait5() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Writer.write("Lauren zegt: ziejewel!");
}
}
@Override
public void setSlowTravelSpeed(double speed) {
pilot.setSlowTravelSpeed(speed);
}
@Override
public void setHighTravelSpeed(double speed) {
pilot.setHighTravelSpeed(speed);
}
@Override
public void setWheelDiameter(double diameter) {
pilot.setWheelDiameter(diameter);
}
@Override
public void setTrackWidth(double trackWidth) {
pilot.setTrackWidth(trackWidth);
}
@Override
public void setX(double xCo) {
pilot.setXCo(xCo);
}
@Override
public void setY(double yCo) {
pilot.setYCo(yCo);
}
@Override
public void setRotation(double rotation) {
pilot.setRotation(rotation);
}
@Override
public void setToDefaultTravelSpeed() {
pilot.setToDefaultTravelSpeed();
}
@Override
public void setToDefaultTurnSpeed() {
pilot.setToDefaultRotateSpeed();
}
@Override
public void setTravelSpeed(double speed) {
pilot.setTravelSpeed(speed);
}
@Override
public void setTurnSpeed(double speed) {
pilot.setRotateSpeed(speed);
}
@Override
public void straighten() {
int middleDifference=17;
if(pilot.poseUpdateIsDisabled()){
//in this case we are either scanning a barcode or straightening already
return;
}
int calcDistance = 0;
Writer.write(" straighten" );
pilot.forward();
stopAtWoodToWhite();
pilot.travelBlocking(5);
pilot.setRotateSpeed(50);
pilot.keepTurning(true);
stopAtWoodToWhite(); //TODO checken of gecommentarieerd beter is
calcDistance = fixDistance(readUltraSonicSensor())%40;
calcDistance = calcDistance - middleDifference;
if(calcDistance < -4 || calcDistance > 4){
calcDistance = (calcDistance / Math.abs(calcDistance)) * 4;
}
pilot.travelBlocking(calcDistance);
pilot.setToDefaultRotateSpeed();
pilot.rotateBlocking(85);
snapPoseAfterStraighten();
}
private void stopAtWoodToWhite() {
//TODO TODO test
int noWantedWoods;
if(readLightType()!=LightType.WOOD&& readLightType()!=LightType.WOOD){
noWantedWoods=(int) (200 * 5.0/(pilot.getTravelSpeed()));
}
else{
noWantedWoods = (int) (100 * 5.0/(pilot.getTravelSpeed() ));
}
int noWantedWhites=(int) (50 * 5.0/(pilot.getTravelSpeed() ));
int noWhites=0;
int noWoods = 0;
while (noWoods < noWantedWoods) {
if (readLightType() == LightType.WOOD) {
noWoods++;
} else {
if(readLightType() != LightType.WOOD){
noWoods = 0;}
}
}
while(noWhites<noWantedWhites){
if(readLightType()==LightType.WHITE){
noWhites++;
}
else{
if(readLightType() != LightType.WHITE){
noWhites=0;}
}
};
pilot.stop();
//TODO TODO test
}
private int fixDistance(int distanceAfterTurn) {
if(distanceAfterTurn<25){
return distanceAfterTurn-=2;
}
return distanceAfterTurn;
}
private int minInAbs(int i, int j) {
if(Math.abs(i)<Math.abs(j)){
return i;
}
else {
return j;
}
}
//Makes the
private void snapPoseAfterStraighten() {
pilot.disablePoseUpdate();
int newRotation= snapTo(90,pilot.getRotation());
if(newRotation%180==0){
pilot.setXCo(snapTo(40,pilot.getPosition().getX()));
pilot.setYCo(snapTo(40,20,pilot.getPosition().getY()));
}
else{
pilot.setXCo(snapTo(40,20,pilot.getPosition().getX()));
pilot.setYCo(snapTo(40,pilot.getPosition().getY()));
}
pilot.setRotation(newRotation);
// pilot.setPosition(pilot.getPosition().getX());
pilot.enablePoseUpdate();
}
private int snapTo(int mod, double notSnapped) {
return snapTo(mod, 0, notSnapped);
}
private int snapTo(int mod, int offset, double notSnapped) {
boolean positive=notSnapped>=0;
notSnapped*=(positive?1:-1);
int intNotSnapped=(int) notSnapped-offset;
int snappedNumber=(intNotSnapped/mod)*mod;
if(intNotSnapped-snappedNumber> mod/2){
snappedNumber+=mod;
}
return (positive?1:-1)*(snappedNumber+offset);
}
public void checkAndReadBarcode() {
if (!lightIsCalibrated() || pilot.poseUpdateIsDisabled()
|| pilot.getCurrentMoveType() != MoveType.ENDINGTRAVEL
|| !detect2TimesBlack()) {
if(lightSensor.readValue()<-150){
// Writer.write("CF "+ ((!lightIsCalibrated())?1:0) + "" + (pilot.poseUpdateIsDisabled()?1:0) +"" + ((pilot.getCurrentMoveType() != MoveType.ENDINGTRAVEL)?1:0)+" "+lastLightType+ " "+ detectWoodToBlack() );
}
// If this is the case, then we are either checking for a barcode,
// or straightening, or stopped, or turning\
// Writer.write("CF "+ ((!lightIsCalibrated())?1:0) + "" + (pilot.poseUpdateIsDisabled()?1:0) +"" + ((pilot.getCurrentMoveType() != MoveType.ENDINGTRAVEL)?1:0));
return;
}
Writer.write("found barcode in check");
Position newBarcodePosition = new Position(snapTo(40, 20, pilot
.getPosition().getX()), snapTo(40, 20, pilot.getPosition()
.getY()));
for (Position otherPosition : barCodePositionList) {
if (otherPosition.equals(newBarcodePosition)) {
Writer.write("returned because already read");
return;
}
}
fromSecondThread=true;
pilot.setReadingBarcode(true);
pilot.disablePoseUpdate();
pilot.stop();
int[] barcode = scanBarcode();
barCodePositionList.add(newBarcodePosition);
// if (barcode == null) {
// travel(-40);
// straighten();
// findBlackLine();
// checkAndReadBarcode();
// } else {
addSomethingToReply(SpecialReplyCode.ADDBARCODE, barcode);
//We wait until the the special reply is sent
while(!replyAdditionList.isEmpty());
endBarcodeReading();
// }
fromSecondThread=false;
}
@Override
public void autoCalibrateLightSensor(int difference) {
autoCalibrateLightSensor(difference, 0, 0);
}
public void autoCalibrateLightSensor(int difference, int numberOfTry, int extraTravelBackDistance) {
if (numberOfTry < 3) {
lightSensor.calibrateLow();
Position firstPosition = pilot.getPosition();
pilot.forward();
while (readLightValue() < difference) {
}
pilot.stop();
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lightSensor.calibrateHigh();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Writer.write("autoCalibrate was interrupted");
}
pilot.travelNonBlocking(-(firstPosition.getDistance(pilot
.getPosition()) + extraTravelBackDistance));
boolean shouldCalibrateAgain = false;
while (pilot.isMoving()) {
if (detectBlackValue() && detectBlackValue()) {
shouldCalibrateAgain = true;
stop();
break;
}
}
int dismissedDistance = (int) firstPosition.getDistance(pilot
.getPosition());
if (shouldCalibrateAgain) {
autoCalibrateLightSensor(difference, ++numberOfTry,
dismissedDistance);
}
calibratedLightLow=true;
calibratedLightHigh=true;
}
}
public void checkTouching() {
}
@Override
public void fetchBall() {
pilot.travelBlocking(50);
pilot.rotateBlocking(180);
pilot.travelBlocking(50);
}
@Override
public void doNothing() {
pilot.rotateBlocking(180);
}
// private static class blackLinePoller extends Thread {
// private BTCommRobot robot;
//
// public blackLinePoller(BTCommRobot robot) {
// this.robot = robot;
// }
// /**
// * Infinite loop that runs while the thread is active.
// */
// public void run(){
// try{
// while(true){
// if(robot.detectBlackLine()){
// robot.pilot.setReadingBarcode(true);
// robot.stop();
// int[] barcode = robot.scanBarcode();
// robot.robotReplyLength = 8;
// robot._reply = new int[robot.robotReplyLength];
// for(int i = 0; i<4; i++){
// robot._reply[4+i] = barcode[i];
// }
// robot.pilot.setReadingBarcode(false);
// }
// sleep(100);
// }
// } catch(InterruptedException e){
// //Do absolutely nothing
// }
// }
// }
}
| true | true | private void handleOneCommand() throws IOException {
// Fetch the Master's command and argument
int command=_dis.readByte();
// Writer.write("we read command " + command);
double argument= (_dis.readInt())/100.0;
// Writer.write("we read argument " + argument);
// We set the robotReplyLength to 0 because this is the case for
// most of the commands.
robotReplyLength = 0;
_reply=new int[4];
// Respond to the Master's command which is stored in command[0]
// Writer.write("command received" + command);
switch (command) {
// Get the battery voltage
case STOP:
stop();
break;
case GETPOSE:
_reply = getPose();
robotReplyLength=4;
break;
case BATTERY:
_reply[0]=getBattery();
robotReplyLength=1;
break;
// Manual Ping
case CALIBRATELSHIGH:
calibrateLightSensorHigh();
break;
case CALIBRATELSLOW:
calibrateLightSensorLow();
break;
case TURNSENSOR:
turnSensor((int)argument);
break;
case TURNSENSORTO:
turnSensorTo((int)argument);
break;
// Manual Ping
case GETSENSORVALUES:
_reply=getSensorValues();
robotReplyLength=4;
break;
// Travel forward requested distance and return sonic sensor distance
case TRAVEL:
travel(argument);
break;
// Rotate requested angle and return sonic sensor distance
case TURN:
turn(argument);
break;
// Master warns of a bluetooth disconnect; set while loop so it stops
case KEEPTRAVELLING:
keepTraveling(argument>0);
break;
case KEEPTURNING:
keepTurning(argument>0);
break;
case DISCONNECT:
disconnect();
break;
case SCANBARCODE:
_reply=scanBarcode();
if(_reply!=null){
robotReplyLength=4;}
break;
case DRIVESLOW:
driveSlow();
break;
case DRIVEFAST:
driveFast();
break;
case PLAYTUNE:
playTune();
break;
case WAIT5:
wait5();
break;
case STRAIGHTEN:
straighten();
break;
case SETTODEFAULTTRAVELSPEED:
setToDefaultTravelSpeed();
break;
case SETTODEFAULTTURNSPEED:
setToDefaultTurnSpeed();
break;
case SETSLOWTRAVELSPEED:
setSlowTravelSpeed(argument);
break;
case SETHIGHTRAVELSPEED:
setHighTravelSpeed(argument);
break;
case SETWHEELDIAMETER:
setWheelDiameter(argument);
break;
case SETTRACKWIDTH:
setTrackWidth(argument);
break;
case SETROTATION:
setRotation(argument);
break;
case SETX:
setX(argument);
break;
case SETY:
setY(argument);
break;
case SETDEFAULTTRAVELSPEED:
setDefaultTravelSpeed(argument);
break;
case SETDEFAULTTURNSPEED:
setDefaultTurnSpeed(argument);
break;
case SETTURNSPEED:
setTurnSpeed(argument);
break;
case SETTRAVELSPEED:
setTravelSpeed(argument);
break;
case AUTOCALIBRATELS:
autoCalibrateLightSensor((int)argument);
break;
default:
throw new RuntimeException("A case was not implemented or did not break");
} // End case structure
int numberOfSpecialReplies=replyAdditionList.size();
if (numberOfSpecialReplies == 0 && robotReplyLength == 0) {
//if there is nothing to send, then we just send 0
_dos.writeByte(0);
_dos.flush();
} else {
// we will first write how many replies there will be
_dos.writeByte(numberOfSpecialReplies + 1);
//now we write how long the normal reply will be.
_dos.writeByte(robotReplyLength);
_dos.flush();
//now we write the normal reply
for (int k = 0; k < robotReplyLength; k++) {
_dos.writeInt(_reply[k]);
_dos.flush();
}
//now we write the special replies
for (int i = 0; i < numberOfSpecialReplies; i++) {
Writer.write("start of write specialReply: "+i);
int[] specialReply=(int[]) replyAdditionList.pop();
//We first write the specialReplyCode
_dos.writeByte(specialReply[0]);
_dos.flush();
for(int j=1;j<specialReply.length;j++){
Writer.write("wrote specialReply argument: " +j+": "+ specialReply[j]);
_dos.writeInt(specialReply[j]);
_dos.flush();
}
Writer.write("wrote specialReply: "+i);
}
// Writer.write("command replied " + command);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.exit(0);
}
}
// LCD.refresh();
}
| private void handleOneCommand() throws IOException {
// Fetch the Master's command and argument
int command=_dis.readByte();
// Writer.write("we read command " + command);
double argument= (_dis.readInt())/100.0;
// Writer.write("we read argument " + argument);
// We set the robotReplyLength to 0 because this is the case for
// most of the commands.
robotReplyLength = 0;
_reply=new int[4];
// Respond to the Master's command which is stored in command[0]
// Writer.write("command received" + command);
switch (command) {
// Get the battery voltage
case STOP:
stop();
break;
case GETPOSE:
_reply = getPose();
robotReplyLength=4;
break;
case BATTERY:
_reply[0]=getBattery();
robotReplyLength=1;
break;
// Manual Ping
case CALIBRATELSHIGH:
calibrateLightSensorHigh();
break;
case CALIBRATELSLOW:
calibrateLightSensorLow();
break;
case TURNSENSOR:
turnSensor((int)argument);
break;
case TURNSENSORTO:
turnSensorTo((int)argument);
break;
// Manual Ping
case GETSENSORVALUES:
_reply=getSensorValues();
robotReplyLength=4;
break;
// Travel forward requested distance and return sonic sensor distance
case TRAVEL:
travel(argument);
break;
// Rotate requested angle and return sonic sensor distance
case TURN:
turn(argument);
break;
// Master warns of a bluetooth disconnect; set while loop so it stops
case KEEPTRAVELLING:
keepTraveling(argument>0);
break;
case KEEPTURNING:
keepTurning(argument>0);
break;
case DISCONNECT:
disconnect();
break;
case SCANBARCODE:
_reply=scanBarcode();
if(_reply!=null){
robotReplyLength=4;}
break;
case DRIVESLOW:
driveSlow();
break;
case DRIVEFAST:
driveFast();
break;
case PLAYTUNE:
playTune();
break;
case WAIT5:
wait5();
break;
case STRAIGHTEN:
straighten();
break;
case SETTODEFAULTTRAVELSPEED:
setToDefaultTravelSpeed();
break;
case SETTODEFAULTTURNSPEED:
setToDefaultTurnSpeed();
break;
case SETSLOWTRAVELSPEED:
setSlowTravelSpeed(argument);
break;
case SETHIGHTRAVELSPEED:
setHighTravelSpeed(argument);
break;
case SETWHEELDIAMETER:
setWheelDiameter(argument);
break;
case SETTRACKWIDTH:
setTrackWidth(argument);
break;
case SETROTATION:
setRotation(argument);
break;
case SETX:
setX(argument);
break;
case SETY:
setY(argument);
break;
case SETDEFAULTTRAVELSPEED:
setDefaultTravelSpeed(argument);
break;
case SETDEFAULTTURNSPEED:
setDefaultTurnSpeed(argument);
break;
case SETTURNSPEED:
setTurnSpeed(argument);
break;
case SETTRAVELSPEED:
setTravelSpeed(argument);
break;
case AUTOCALIBRATELS:
autoCalibrateLightSensor((int)argument);
break;
case FETCHBALL:
fetchBall();
break;
case DONOTHING:
doNothing();
break;
default:
throw new RuntimeException("A case was not implemented or did not break");
} // End case structure
int numberOfSpecialReplies=replyAdditionList.size();
if (numberOfSpecialReplies == 0 && robotReplyLength == 0) {
//if there is nothing to send, then we just send 0
_dos.writeByte(0);
_dos.flush();
} else {
// we will first write how many replies there will be
_dos.writeByte(numberOfSpecialReplies + 1);
//now we write how long the normal reply will be.
_dos.writeByte(robotReplyLength);
_dos.flush();
//now we write the normal reply
for (int k = 0; k < robotReplyLength; k++) {
_dos.writeInt(_reply[k]);
_dos.flush();
}
//now we write the special replies
for (int i = 0; i < numberOfSpecialReplies; i++) {
Writer.write("start of write specialReply: "+i);
int[] specialReply=(int[]) replyAdditionList.pop();
//We first write the specialReplyCode
_dos.writeByte(specialReply[0]);
_dos.flush();
for(int j=1;j<specialReply.length;j++){
Writer.write("wrote specialReply argument: " +j+": "+ specialReply[j]);
_dos.writeInt(specialReply[j]);
_dos.flush();
}
Writer.write("wrote specialReply: "+i);
}
// Writer.write("command replied " + command);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.exit(0);
}
}
// LCD.refresh();
}
|
diff --git a/src/bt/Model/PeerListener.java b/src/bt/Model/PeerListener.java
index f3c0309..c1c89ce 100644
--- a/src/bt/Model/PeerListener.java
+++ b/src/bt/Model/PeerListener.java
@@ -1,138 +1,136 @@
package bt.Model;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import bt.Utils.Utilities;
/**
*
* The main listener thread for each peer this client is connected to.
* @author Ike, Robert and Fernando
*
*/
class PeerListener implements Runnable{
private InputStream in = null;
private Peer parent = null;
private boolean running = true;
PeerListener (Peer parent, InputStream inStream) {
this.in = inStream;
this.parent = parent;
}
@Override
public void run() {
while(running) {
if(!parent.peerAccepted) {
receiveHandshake();
} else {
try {
readLine();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
void receiveHandshake() {
byte[] tcpArray = new byte[68];
try {
in.read(tcpArray);
System.out.println("<<< Data received, processing...");
System.out.println(">>> Listening from Peer : "+this.parent+"...");
parent.validateInfoHash(tcpArray);
System.out.println("-- HANDSHAKE VALIDATED !!! w/ peer "+parent+" -");
parent.showInterested();
parent.sendBitfield();
parent.unChoke();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// This just means we are off slightly on our timing.
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
private void readLine() throws Exception {
byte[] lengthArray = new byte [4];
in.read(lengthArray, 0, 4);
ByteBuffer lengthBuffer = ByteBuffer.wrap(lengthArray);
- byte[] tcpArray = new byte[lengthBuffer.getInt()];
- in.read(tcpArray, 0, lengthBuffer.getInt());
+ int length = lengthBuffer.getInt();
+ byte[] tcpArray = new byte[length];
+ in.read(tcpArray, 0, length);
ByteBuffer tcpInput = ByteBuffer.wrap(tcpArray);
- int length = tcpInput.getInt(0);
if (length == 0) {
parent.updateTimout(); // This is a keep alive
} else {
- tcpInput.position(5); // sets the iterator in the data index after reading length. and
- // message id.
switch (tcpArray[4]) {
case 0: // choke
parent.setChoke(true);
break;
case 1: // remote-peer is unchoked, start requesting
parent.setChoke(false);
System.out.println(">>> Peer "+parent+" just unchoked me, start requesting pieces");
Bittorrent.getInstance().simpleDownloadAlgorithm();
break; // message was received and processed.
case 2: // interested
parent.setInterested(true);
break;
case 3: // not interested
parent.setInterested(false);
break;
case 4: // have
parent.haveReceived(tcpInput.getInt());
break;
case 5: // bitfield
byte[] bitfield = new byte[length - 1];
tcpInput.get(bitfield, 5, length - 1);
parent.receiveBitfield(bitfield);
break;
case 6: // request
parent.requestReceived(tcpInput.getInt(),
tcpInput.getInt(),
tcpInput.getInt());
break;
case 7: // piece
System.out.println("-- Piece received, analyzing...");
byte[] payload = new byte[length - 9];
tcpInput.position(13);
for(int i = 0; i < payload.length; ++i) {
payload[i] = tcpInput.get();
}
tcpInput.rewind();
// lineWrapper.get(payload, 9, length - 9); // this mothertrucker is giving problems.
parent.getPiece(tcpInput.getInt(5), tcpInput.getInt(9), payload);
break;
case 8: // cancel
parent.cancelIndex(tcpInput.getInt(5),
tcpInput.getInt(9),
tcpInput.getInt(13));
default:
System.err.println("Invalid message was received: " + tcpInput);
break;
}
}
}
/**
* This method is called by the parent of this object as the first action of its own dispose method to
* remove references to itself which might prevent garbage collection.
*/
void dispose () {
running = false;
in = null;
parent = null;
}
}
| false | true | private void readLine() throws Exception {
byte[] lengthArray = new byte [4];
in.read(lengthArray, 0, 4);
ByteBuffer lengthBuffer = ByteBuffer.wrap(lengthArray);
byte[] tcpArray = new byte[lengthBuffer.getInt()];
in.read(tcpArray, 0, lengthBuffer.getInt());
ByteBuffer tcpInput = ByteBuffer.wrap(tcpArray);
int length = tcpInput.getInt(0);
if (length == 0) {
parent.updateTimout(); // This is a keep alive
} else {
tcpInput.position(5); // sets the iterator in the data index after reading length. and
// message id.
switch (tcpArray[4]) {
case 0: // choke
parent.setChoke(true);
break;
case 1: // remote-peer is unchoked, start requesting
parent.setChoke(false);
System.out.println(">>> Peer "+parent+" just unchoked me, start requesting pieces");
Bittorrent.getInstance().simpleDownloadAlgorithm();
break; // message was received and processed.
case 2: // interested
parent.setInterested(true);
break;
case 3: // not interested
parent.setInterested(false);
break;
case 4: // have
parent.haveReceived(tcpInput.getInt());
break;
case 5: // bitfield
byte[] bitfield = new byte[length - 1];
tcpInput.get(bitfield, 5, length - 1);
parent.receiveBitfield(bitfield);
break;
case 6: // request
parent.requestReceived(tcpInput.getInt(),
tcpInput.getInt(),
tcpInput.getInt());
break;
case 7: // piece
System.out.println("-- Piece received, analyzing...");
byte[] payload = new byte[length - 9];
tcpInput.position(13);
for(int i = 0; i < payload.length; ++i) {
payload[i] = tcpInput.get();
}
tcpInput.rewind();
// lineWrapper.get(payload, 9, length - 9); // this mothertrucker is giving problems.
parent.getPiece(tcpInput.getInt(5), tcpInput.getInt(9), payload);
break;
case 8: // cancel
parent.cancelIndex(tcpInput.getInt(5),
tcpInput.getInt(9),
tcpInput.getInt(13));
default:
System.err.println("Invalid message was received: " + tcpInput);
break;
}
}
}
| private void readLine() throws Exception {
byte[] lengthArray = new byte [4];
in.read(lengthArray, 0, 4);
ByteBuffer lengthBuffer = ByteBuffer.wrap(lengthArray);
int length = lengthBuffer.getInt();
byte[] tcpArray = new byte[length];
in.read(tcpArray, 0, length);
ByteBuffer tcpInput = ByteBuffer.wrap(tcpArray);
if (length == 0) {
parent.updateTimout(); // This is a keep alive
} else {
switch (tcpArray[4]) {
case 0: // choke
parent.setChoke(true);
break;
case 1: // remote-peer is unchoked, start requesting
parent.setChoke(false);
System.out.println(">>> Peer "+parent+" just unchoked me, start requesting pieces");
Bittorrent.getInstance().simpleDownloadAlgorithm();
break; // message was received and processed.
case 2: // interested
parent.setInterested(true);
break;
case 3: // not interested
parent.setInterested(false);
break;
case 4: // have
parent.haveReceived(tcpInput.getInt());
break;
case 5: // bitfield
byte[] bitfield = new byte[length - 1];
tcpInput.get(bitfield, 5, length - 1);
parent.receiveBitfield(bitfield);
break;
case 6: // request
parent.requestReceived(tcpInput.getInt(),
tcpInput.getInt(),
tcpInput.getInt());
break;
case 7: // piece
System.out.println("-- Piece received, analyzing...");
byte[] payload = new byte[length - 9];
tcpInput.position(13);
for(int i = 0; i < payload.length; ++i) {
payload[i] = tcpInput.get();
}
tcpInput.rewind();
// lineWrapper.get(payload, 9, length - 9); // this mothertrucker is giving problems.
parent.getPiece(tcpInput.getInt(5), tcpInput.getInt(9), payload);
break;
case 8: // cancel
parent.cancelIndex(tcpInput.getInt(5),
tcpInput.getInt(9),
tcpInput.getInt(13));
default:
System.err.println("Invalid message was received: " + tcpInput);
break;
}
}
}
|
diff --git a/src/main/java/gui/MainWindow.java b/src/main/java/gui/MainWindow.java
index a0338aa..cb6852d 100644
--- a/src/main/java/gui/MainWindow.java
+++ b/src/main/java/gui/MainWindow.java
@@ -1,210 +1,211 @@
package gui;
import icarus.operatingsoftware.FailableOperatingSoftware;
import icarus.operatingsoftware.OperatingSoftware;
import icarus.operatingsoftware.PowerPlant;
import icarus.util.GameFileFilter;
import java.awt.event.*;
import java.io.File;
import java.net.URI;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileFilter;
/**
*
* @author drm511
*/
public class MainWindow extends JFrame implements ActionListener, ChangeListener {
private JFileChooser fc;
private JMenu fileMenu;
private JMenu helpMenu;
private JMenuBar menuBar;
private JPanel controlPanel;
private JPanel viewPanel;
private JSlider rodSlider;
private OperatingSoftware os;
/**
* Creates new form MainWindow
*/
public MainWindow() {
os = new FailableOperatingSoftware(new PowerPlant());
viewPanel = new JPanel();
controlPanel = new ControlPanel(os);
menuBar = new JMenuBar();
fileMenu = new JMenu();
helpMenu = new JMenu();
fc = new JFileChooser();
GameFileFilter ff = new GameFileFilter();
fc.addChoosableFileFilter(ff);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GroupLayout viewPanelLayout = new GroupLayout(viewPanel);
viewPanel.setLayout(viewPanelLayout);
viewPanelLayout.setHorizontalGroup(
viewPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE));
viewPanelLayout.setVerticalGroup(
viewPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGap(0, 399, Short.MAX_VALUE));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(viewPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(controlPanel, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(viewPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(controlPanel, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)));
pack();
createMenus();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
// Ignore all exceptions here :(
} catch (Exception e) {
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainWindow().setVisible(true);
}
});
}
/*
public void stateChanged(ChangeEvent e){
repaint();
}
*/
@Override
public void actionPerformed(ActionEvent e) {
try
{
if(e.getActionCommand().equals("New Game"))
{
os.resetPlant();
}
else if(e.getActionCommand().equals("Save Game"))
{
int retval = fc.showSaveDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
os.saveToFile(file.getAbsolutePath());
}
}
else if(e.getActionCommand().equals("Load Game"))
{
int retval = fc.showOpenDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(!os.loadFromFile(file.getAbsolutePath()))
{
+ JOptionPane.showMessageDialog(null,"Unable to load this file");
System.err.println("Error Loading File");
}
}
}
else if(e.getActionCommand().equals("Quit"))
{
quit();
}
else if(e.getActionCommand().equals("Online Help"))
{
java.awt.Desktop.getDesktop().browse( new URI("http://www.teameel.com/help"));
}
else if(e.getActionCommand().equals("About"))
{
AboutDialog aboutDialog = new AboutDialog(this,true);
aboutDialog.pack();
aboutDialog.setVisible(true);
}
}
catch(Exception ex)
{
}
repaint();
}
@Override
public void stateChanged(ChangeEvent e) {
repaint();
}
private void createMenus() {
JMenuItem tmpMenuItem;
fileMenu.setText("File");
tmpMenuItem = new JMenuItem("New Game");
tmpMenuItem.addActionListener(this);
fileMenu.add(tmpMenuItem);
tmpMenuItem = new JMenuItem("Load Game");
tmpMenuItem.addActionListener(this);
fileMenu.add(tmpMenuItem);
tmpMenuItem = new JMenuItem("Save Game");
tmpMenuItem.addActionListener(this);
fileMenu.add(tmpMenuItem);
tmpMenuItem = new JMenuItem("Quit");
tmpMenuItem.addActionListener(this);
fileMenu.add(tmpMenuItem);
menuBar.add(fileMenu);
helpMenu.setText("Help");
tmpMenuItem = new JMenuItem("Online Help");
tmpMenuItem.addActionListener(this);
helpMenu.add(tmpMenuItem);
tmpMenuItem = new JMenuItem("About");
tmpMenuItem.addActionListener(this);
helpMenu.add(tmpMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
private void quit() {
this.dispatchEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING));
}
}
| true | true | public void actionPerformed(ActionEvent e) {
try
{
if(e.getActionCommand().equals("New Game"))
{
os.resetPlant();
}
else if(e.getActionCommand().equals("Save Game"))
{
int retval = fc.showSaveDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
os.saveToFile(file.getAbsolutePath());
}
}
else if(e.getActionCommand().equals("Load Game"))
{
int retval = fc.showOpenDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(!os.loadFromFile(file.getAbsolutePath()))
{
System.err.println("Error Loading File");
}
}
}
else if(e.getActionCommand().equals("Quit"))
{
quit();
}
else if(e.getActionCommand().equals("Online Help"))
{
java.awt.Desktop.getDesktop().browse( new URI("http://www.teameel.com/help"));
}
else if(e.getActionCommand().equals("About"))
{
AboutDialog aboutDialog = new AboutDialog(this,true);
aboutDialog.pack();
aboutDialog.setVisible(true);
}
}
catch(Exception ex)
{
}
repaint();
}
| public void actionPerformed(ActionEvent e) {
try
{
if(e.getActionCommand().equals("New Game"))
{
os.resetPlant();
}
else if(e.getActionCommand().equals("Save Game"))
{
int retval = fc.showSaveDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
os.saveToFile(file.getAbsolutePath());
}
}
else if(e.getActionCommand().equals("Load Game"))
{
int retval = fc.showOpenDialog(this);
if(retval == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(!os.loadFromFile(file.getAbsolutePath()))
{
JOptionPane.showMessageDialog(null,"Unable to load this file");
System.err.println("Error Loading File");
}
}
}
else if(e.getActionCommand().equals("Quit"))
{
quit();
}
else if(e.getActionCommand().equals("Online Help"))
{
java.awt.Desktop.getDesktop().browse( new URI("http://www.teameel.com/help"));
}
else if(e.getActionCommand().equals("About"))
{
AboutDialog aboutDialog = new AboutDialog(this,true);
aboutDialog.pack();
aboutDialog.setVisible(true);
}
}
catch(Exception ex)
{
}
repaint();
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/document/stream/WrapperedRAInputStream.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/document/stream/WrapperedRAInputStream.java
index 19a8d4cd7..31ebcb4b1 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/document/stream/WrapperedRAInputStream.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/document/stream/WrapperedRAInputStream.java
@@ -1,95 +1,95 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl.document.stream;
import java.io.IOException;
import org.eclipse.birt.core.archive.RAInputStream;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
class WrapperedRAInputStream extends RAInputStream
{
private RAInputStream raIn;
private long startOffset;
private int size;
WrapperedRAInputStream( RAInputStream input, long startOffset, int size ) throws DataException
{
this.raIn = input;
this.startOffset = startOffset;
this.size = size;
try
{
- this.skip( this.startOffset );
+ this.raIn.seek( this.startOffset );
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ));
}
}
public int available( ) throws IOException
{
return this.raIn.available( );
}
public long getOffset( ) throws IOException
{
return this.raIn.getOffset( ) - this.startOffset;
}
public long length( ) throws IOException
{
return this.size;
}
public void readFully( byte[] b, int off, int len ) throws IOException
{
this.raIn.readFully( b, off, len );
}
public int readInt( ) throws IOException
{
return this.raIn.readInt( );
}
public long readLong( ) throws IOException
{
return this.raIn.readLong( );
}
public void refresh( ) throws IOException
{
this.raIn.refresh( );
this.raIn.seek( this.startOffset );
}
public void seek( long localPos ) throws IOException
{
this.raIn.seek( this.startOffset + localPos );
}
public int read( ) throws IOException
{
return this.raIn.read( );
}
public void close() throws IOException
{
this.raIn.close( );
}
}
| true | true | WrapperedRAInputStream( RAInputStream input, long startOffset, int size ) throws DataException
{
this.raIn = input;
this.startOffset = startOffset;
this.size = size;
try
{
this.skip( this.startOffset );
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ));
}
}
| WrapperedRAInputStream( RAInputStream input, long startOffset, int size ) throws DataException
{
this.raIn = input;
this.startOffset = startOffset;
this.size = size;
try
{
this.raIn.seek( this.startOffset );
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ));
}
}
|
diff --git a/ChanServ/LogCleaner.java b/ChanServ/LogCleaner.java
index 4998710..c6ee02c 100644
--- a/ChanServ/LogCleaner.java
+++ b/ChanServ/LogCleaner.java
@@ -1,159 +1,160 @@
/*
* Created on 25.12.2007
*
* This class is involved in moving logs from files on disk to a database,
* where they can be more easily accessed by TASServer web interface.
*
* This is the procedure it follows:
* 1) Check if temp_logs folder exists. If not, create it.
* 2) Check if there are any files in temp_logs folder.
* If there are, skip to 4), or else continue with 4).
* 3) Lock access to logs globally in ChanServ, then move
* all log files to temp_logs folder.
* 4) Transfer all logs from temp_logs folder to a database
* and remove them from disk.
*
*/
/**
* @author Betalord
*
*/
import java.sql.SQLException;
import java.util.*;
import java.io.*;
import java.sql.*;
public class LogCleaner extends TimerTask {
final static String TEMP_LOGS_FOLDER = "./temp_logs";
public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
String name = file.getName().substring(0, file.getName().length() - 4); // remove ".log" from the end of the file name
try {
if (!ChanServ.database.doesTableExist(name)) {
- boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + name + "' (" + Misc.EOL +
+ boolean result= ChanServ.database.execUpdate("CREATE TABLE `" + name + "` (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
- "line TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
+ "line TEXT NOT NULL, " + Misc.EOL +
+ "primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
Log.error("Unable to create table '" + name + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
- update += "INSERT INTO '" + name + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
+ update += "INSERT INTO `" + name + "` (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
}
| false | true | public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
String name = file.getName().substring(0, file.getName().length() - 4); // remove ".log" from the end of the file name
try {
if (!ChanServ.database.doesTableExist(name)) {
boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + name + "' (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
"line TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
Log.error("Unable to create table '" + name + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
update += "INSERT INTO '" + name + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
| public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
String name = file.getName().substring(0, file.getName().length() - 4); // remove ".log" from the end of the file name
try {
if (!ChanServ.database.doesTableExist(name)) {
boolean result= ChanServ.database.execUpdate("CREATE TABLE `" + name + "` (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
"line TEXT NOT NULL, " + Misc.EOL +
"primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
Log.error("Unable to create table '" + name + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
update += "INSERT INTO `" + name + "` (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
|
diff --git a/src/episode_15/ThreeDeeDemo.java b/src/episode_15/ThreeDeeDemo.java
index 153d112..dca7a50 100644
--- a/src/episode_15/ThreeDeeDemo.java
+++ b/src/episode_15/ThreeDeeDemo.java
@@ -1,127 +1,127 @@
package episode_15;
import java.util.Random;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;
/**
* Shows a space-like particle simulation.
*
* @author Oskar
*/
public class ThreeDeeDemo {
public ThreeDeeDemo() {
// Initialization code Display
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("Three Dee Demo");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
//
// Initialization code OpenGL
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Create a new perspective with 30 degree angle (field of view), 640 / 480 aspect ratio, 0.001f zNear, 100 zFar
// Note: +x is to the right
// +y is to the top
// +z is to the camera
gluPerspective((float) 30, 640f / 480f, 0.001f, 100);
glMatrixMode(GL_MODELVIEW);
//
glEnable(GL_DEPTH_TEST);
// Initialization code random points
- Point[] points = new Point[10000000];
+ Point[] points = new Point[1000];
Random random = new Random();
// Iterate of every array index
for (int i = 0; i < points.length; i++) {
// Set the point at the array index to
// x = random between -50 and +50
// y = random between -50 and +50
// z = random between 0 and -200
points[i] = new Point((random.nextFloat() - 0.5f) * 100f, (random.nextFloat() - 0.5f) * 100f, random.nextInt(200) - 200);
}
// The speed in which the "camera" travels
float speed = 0.0f;
//
while (!Display.isCloseRequested()) {
// Render
// Clear the screen of its filthy contents
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Push the screen inwards at the amount of speed
glTranslatef(0, 0, speed);
// Begin drawing points
glBegin(GL_POINTS);
// Iterate of every point
for (Point p : points) {
// Draw the point at its coordinates
glVertex3f(p.x, p.y, p.z);
}
// Stop drawing points
glEnd();
// If we're pressing the "up" key increase our speed
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
speed += 0.01f;
}
// If we're pressing the "down" key decrease our speed
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
speed -= 0.01f;
}
// Iterate over keyboard input events
while (Keyboard.next()) {
// If we're pressing the "space-bar" key reset our speed to zero
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
speed = 0f;
}
// If we're pressing the "c" key reset our speed to zero and reset our position
if (Keyboard.isKeyDown(Keyboard.KEY_C)) {
speed = 0;
glLoadIdentity();
}
}
// Update the display
Display.update();
// Wait until the frame-rate is 60fps
Display.sync(60);
}
// Dispose of the display
Display.destroy();
// Exit the JVM (for some reason this lingers on Macintosh)
System.exit(0);
}
private static class Point {
float x, y, z;
public Point(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
}
/**
* @param args
*/
public static void main(String[] args) {
new ThreeDeeDemo();
}
}
| true | true | public ThreeDeeDemo() {
// Initialization code Display
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("Three Dee Demo");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
//
// Initialization code OpenGL
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Create a new perspective with 30 degree angle (field of view), 640 / 480 aspect ratio, 0.001f zNear, 100 zFar
// Note: +x is to the right
// +y is to the top
// +z is to the camera
gluPerspective((float) 30, 640f / 480f, 0.001f, 100);
glMatrixMode(GL_MODELVIEW);
//
glEnable(GL_DEPTH_TEST);
// Initialization code random points
Point[] points = new Point[10000000];
Random random = new Random();
// Iterate of every array index
for (int i = 0; i < points.length; i++) {
// Set the point at the array index to
// x = random between -50 and +50
// y = random between -50 and +50
// z = random between 0 and -200
points[i] = new Point((random.nextFloat() - 0.5f) * 100f, (random.nextFloat() - 0.5f) * 100f, random.nextInt(200) - 200);
}
// The speed in which the "camera" travels
float speed = 0.0f;
//
while (!Display.isCloseRequested()) {
// Render
// Clear the screen of its filthy contents
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Push the screen inwards at the amount of speed
glTranslatef(0, 0, speed);
// Begin drawing points
glBegin(GL_POINTS);
// Iterate of every point
for (Point p : points) {
// Draw the point at its coordinates
glVertex3f(p.x, p.y, p.z);
}
// Stop drawing points
glEnd();
// If we're pressing the "up" key increase our speed
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
speed += 0.01f;
}
// If we're pressing the "down" key decrease our speed
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
speed -= 0.01f;
}
// Iterate over keyboard input events
while (Keyboard.next()) {
// If we're pressing the "space-bar" key reset our speed to zero
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
speed = 0f;
}
// If we're pressing the "c" key reset our speed to zero and reset our position
if (Keyboard.isKeyDown(Keyboard.KEY_C)) {
speed = 0;
glLoadIdentity();
}
}
// Update the display
Display.update();
// Wait until the frame-rate is 60fps
Display.sync(60);
}
// Dispose of the display
Display.destroy();
// Exit the JVM (for some reason this lingers on Macintosh)
System.exit(0);
}
| public ThreeDeeDemo() {
// Initialization code Display
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("Three Dee Demo");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
//
// Initialization code OpenGL
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Create a new perspective with 30 degree angle (field of view), 640 / 480 aspect ratio, 0.001f zNear, 100 zFar
// Note: +x is to the right
// +y is to the top
// +z is to the camera
gluPerspective((float) 30, 640f / 480f, 0.001f, 100);
glMatrixMode(GL_MODELVIEW);
//
glEnable(GL_DEPTH_TEST);
// Initialization code random points
Point[] points = new Point[1000];
Random random = new Random();
// Iterate of every array index
for (int i = 0; i < points.length; i++) {
// Set the point at the array index to
// x = random between -50 and +50
// y = random between -50 and +50
// z = random between 0 and -200
points[i] = new Point((random.nextFloat() - 0.5f) * 100f, (random.nextFloat() - 0.5f) * 100f, random.nextInt(200) - 200);
}
// The speed in which the "camera" travels
float speed = 0.0f;
//
while (!Display.isCloseRequested()) {
// Render
// Clear the screen of its filthy contents
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Push the screen inwards at the amount of speed
glTranslatef(0, 0, speed);
// Begin drawing points
glBegin(GL_POINTS);
// Iterate of every point
for (Point p : points) {
// Draw the point at its coordinates
glVertex3f(p.x, p.y, p.z);
}
// Stop drawing points
glEnd();
// If we're pressing the "up" key increase our speed
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
speed += 0.01f;
}
// If we're pressing the "down" key decrease our speed
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
speed -= 0.01f;
}
// Iterate over keyboard input events
while (Keyboard.next()) {
// If we're pressing the "space-bar" key reset our speed to zero
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
speed = 0f;
}
// If we're pressing the "c" key reset our speed to zero and reset our position
if (Keyboard.isKeyDown(Keyboard.KEY_C)) {
speed = 0;
glLoadIdentity();
}
}
// Update the display
Display.update();
// Wait until the frame-rate is 60fps
Display.sync(60);
}
// Dispose of the display
Display.destroy();
// Exit the JVM (for some reason this lingers on Macintosh)
System.exit(0);
}
|
diff --git a/test/net/java/sip/communicator/slick/protocol/icq/TestProtocolProviderServiceIcqImpl.java b/test/net/java/sip/communicator/slick/protocol/icq/TestProtocolProviderServiceIcqImpl.java
index f37088c95..a7806e31a 100644
--- a/test/net/java/sip/communicator/slick/protocol/icq/TestProtocolProviderServiceIcqImpl.java
+++ b/test/net/java/sip/communicator/slick/protocol/icq/TestProtocolProviderServiceIcqImpl.java
@@ -1,313 +1,313 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.protocol.icq;
import junit.framework.*;
import net.java.sip.communicator.service.protocol.*;
import java.util.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.service.protocol.icqconstants.*;
/**
* Test icq/aim specific behaviour for OSCAR (AIM/ICQ) implementations of the
* protocol provider service. The class would basically test that registration
* succeeds, that the provider registration state is updated accordingly and
* that the corrsponding registration change events are generated and dispatched.
*
* In the case of a registration failure we try to remain consistent and do
* assertions accordingly.
*
* It is important to note that it is critical to execute tests in this class
* in a particular order because of protocol limitations (we cannot login and
* logoff to most of the existing protocol services as often as we'd like to).
* This is why we have overridden the suite() method which kind of solves the
* problem but adds the limitation of making extending developers manually add
* the tests they write to the suite method.
*
* @author Emil Ivov
*/
public class TestProtocolProviderServiceIcqImpl extends TestCase
{
private static final Logger logger =
Logger.getLogger(TestProtocolProviderServiceIcqImpl.class);
private IcqSlickFixture fixture = new IcqSlickFixture();
/**
* The lock that we wait on until registration is finalized.
*/
private Object registrationLock = new Object();
/**
* An event adapter that would collec registation state change events
*/
public RegistrationEventCollector regEvtCollector
= new RegistrationEventCollector();
public TestProtocolProviderServiceIcqImpl(String name)
{
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
fixture.setUp();
}
protected void tearDown() throws Exception
{
fixture.tearDown();
super.tearDown();
}
// -------------------------- IMPORTANT ----------------------
/**
* Since we cannot afford to log on and off to the icq service as many
* times as we want we're obliged to do our testing in a predfined order.
* That's why we explicitely difine a suite with the order that suits us ;).
* @return a TestSuite with the tests of this class ordered for execution
* the way we want them to be.
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(
new TestProtocolProviderServiceIcqImpl("testRegister"));
suite.addTest(
new TestProtocolProviderServiceIcqImpl("testIsRegistered"));
suite.addTest(
new TestProtocolProviderServiceIcqImpl("testGetRegistrationState"));
suite.addTest(
new TestProtocolProviderServiceIcqImpl("testOperationSetTypes"));
return suite;
}
/**
* Makes sure that the instance of the ICQ protocol provider that we're
* going to use for testing is properly initialized and signed on ICQ. This
* method only makes sense if called before any other icq testing.
*
* The method also verifies that a registration event is fired upond
* succesful registration and collected by our event collector.
*/
public void testRegister()
{
//add an event collector that will collect all events during the
//registration and allows us to later inspect them and make sure
//they were properly dispatched.
fixture.provider.addRegistrationStateChangeListener(regEvtCollector);
- fixture.provider.register(null);
+ fixture.provider.register(new SecurityAuthorityImpl());
//give it enough time to register. We won't really have to wait all this
//time since the registration event collector would notify us the moment
//we get signed on.
try{
synchronized(registrationLock){
logger.debug("Waiting for registration to complete ...");
registrationLock.wait(40000);
logger.debug("Registration was completed or we lost patience.");
}
}
catch (InterruptedException ex){
logger.debug("Interrupted while waiting for registration", ex);
}
catch(Throwable t)
{
logger.debug("We got thrown out while waiting for registration", t);
}
// Here is registered the listener which will receive the first message
// This message is supposed to be offline message and as one is tested
// in TestOperationSetBasicInstantMessaging.testReceiveOfflineMessages()
Map supportedOperationSets =
fixture.provider.getSupportedOperationSets();
OperationSetBasicInstantMessaging opSetBasicIM =
(OperationSetBasicInstantMessaging)supportedOperationSets.get(
OperationSetBasicInstantMessaging.class.getName());
fixture.offlineMsgCollector.register(opSetBasicIM);
//give time for the AIM server to notify everyone of our arrival
//simply waitinf is really not a reliable way of doing things but I
//can't think of anything better
Object lock = new Object();
synchronized(lock)
{
try
{
logger.debug("Giving the aim server time to notify for our arrival!");
lock.wait(5000);
}
catch (Exception ex)
{}
}
//make sure the provider is on-line
assertTrue(
"The tested ICQ implementation on-line status was OFFLINE",
!IcqStatusEnum.OFFLINE.equals(
fixture.testerAgent.getBuddyStatus(fixture.ourUserID))
);
//make sure that the registration process trigerred the corresponding
//events.
assertTrue(
"No events were dispatched during the registration process."
,regEvtCollector.collectedNewStates.size() > 0);
assertTrue(
"No registration event notifying of registration was dispatched. "
+"All events were: " + regEvtCollector.collectedNewStates
,regEvtCollector.collectedNewStates
.contains(RegistrationState.REGISTERED));
fixture.provider.removeRegistrationStateChangeListener(regEvtCollector);
}
/**
* Verifies whether the isRegistered method returns whatever it has to.
*/
public void testIsRegistered()
{
if (!IcqStatusEnum.OFFLINE.equals(
fixture.testerAgent.getBuddyStatus(fixture.ourUserID)))
assertTrue(
"provider.isRegistered() returned false while registered"
,fixture.provider.isRegistered());
else
//in case registration failed - the provider needs to know that.:
assertFalse(
"provider.isRegistered() returned true while unregistered"
,fixture.provider.isRegistered());
}
/**
* Tests that getRegistrationState returns properly after registration
* has completed (or failed)
*/
public void testGetRegistrationState()
{
if (!IcqStatusEnum.OFFLINE.equals(
fixture.testerAgent.getBuddyStatus(fixture.ourUserID)))
assertEquals(
"a provider was not in a REGISTERED state while registered."
,RegistrationState.REGISTERED
,fixture.provider.getRegistrationState());
else
assertFalse(
"a provider had a REGISTERED reg state while unregistered."
,fixture
.provider.getRegistrationState()
.equals(RegistrationState.REGISTERED));
}
/**
* Verifies that all operation sets have the type they are declarded to
* have.
*
* @throws java.lang.Exception if a class indicated in one of the keys
* could not be forName()ed.
*/
public void testOperationSetTypes() throws Exception
{
Map supportedOperationSets
= fixture.provider.getSupportedOperationSets();
//make sure that keys (which are supposed to be class names) correspond
//what the class of the values recorded against them.
Iterator setNames = supportedOperationSets.keySet().iterator();
while (setNames.hasNext())
{
String setName = (String) setNames.next();
Object opSet = supportedOperationSets.get(setName);
assertTrue(opSet + " was not an instance of "
+ setName + " as declared"
, Class.forName(setName).isInstance(opSet));
}
}
/**
* A class that would plugin as a registration listener to a protocol
* provider and simply record all events that it sees and notify the
* registrationLock if it sees an event that notifies us of a completed
* registration.
* @author Emil Ivov
*/
public class RegistrationEventCollector implements RegistrationStateChangeListener
{
public List collectedNewStates = new LinkedList();
/**
* The method would simply register all received events so that they
* could be available for later inspection by the unit tests. In the
* case where a registraiton event notifying us of a completed
* registration is seen, the method would call notifyAll() on the
* registrationLock.
*
* @param evt ProviderStatusChangeEvent the event describing the status
* change.
*/
public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
logger.debug("Received a RegistrationStateChangeEvent: " + evt);
collectedNewStates.add(evt.getNewState());
if(evt.getNewState().equals( RegistrationState.REGISTERED))
{
logger.debug("We're registered and will notify those who wait");
synchronized(registrationLock){
logger.debug(".");
registrationLock.notifyAll();
logger.debug(".");
}
}
}
}
/**
* A very simple straightforward implementation of a security authority
* that would authentify our tested implementation if necessary, by
* retrieving its password through the system properties.
*/
public class SecurityAuthorityImpl implements SecurityAuthority
{
/**
* Creates an instance of this class that would would authentify our
* tested implementation if necessary, by retrieving its password
* through the system properties.
*/
public SecurityAuthorityImpl()
{}
/**
* Returns a Credentials object containing the password for our
* tested implementation.
* <p>
* @param realm The realm that the credentials are needed for.
* @param defaultValues the values to propose the user by default
* @return The credentials associated with the specified realm or null if
* none could be obtained.
*/
public UserCredentials obtainCredentials(String realm,
UserCredentials defaultValues)
{
String passwd = System.getProperty( IcqProtocolProviderSlick
.TESTED_IMPL_PWD_PROP_NAME, null );
defaultValues.setPassword(passwd.toCharArray());
return defaultValues;
}
}
}
| true | true | public void testRegister()
{
//add an event collector that will collect all events during the
//registration and allows us to later inspect them and make sure
//they were properly dispatched.
fixture.provider.addRegistrationStateChangeListener(regEvtCollector);
fixture.provider.register(null);
//give it enough time to register. We won't really have to wait all this
//time since the registration event collector would notify us the moment
//we get signed on.
try{
synchronized(registrationLock){
logger.debug("Waiting for registration to complete ...");
registrationLock.wait(40000);
logger.debug("Registration was completed or we lost patience.");
}
}
catch (InterruptedException ex){
logger.debug("Interrupted while waiting for registration", ex);
}
catch(Throwable t)
{
logger.debug("We got thrown out while waiting for registration", t);
}
// Here is registered the listener which will receive the first message
// This message is supposed to be offline message and as one is tested
// in TestOperationSetBasicInstantMessaging.testReceiveOfflineMessages()
Map supportedOperationSets =
fixture.provider.getSupportedOperationSets();
OperationSetBasicInstantMessaging opSetBasicIM =
(OperationSetBasicInstantMessaging)supportedOperationSets.get(
OperationSetBasicInstantMessaging.class.getName());
fixture.offlineMsgCollector.register(opSetBasicIM);
//give time for the AIM server to notify everyone of our arrival
//simply waitinf is really not a reliable way of doing things but I
//can't think of anything better
Object lock = new Object();
synchronized(lock)
{
try
{
logger.debug("Giving the aim server time to notify for our arrival!");
lock.wait(5000);
}
catch (Exception ex)
{}
}
//make sure the provider is on-line
assertTrue(
"The tested ICQ implementation on-line status was OFFLINE",
!IcqStatusEnum.OFFLINE.equals(
fixture.testerAgent.getBuddyStatus(fixture.ourUserID))
);
//make sure that the registration process trigerred the corresponding
//events.
assertTrue(
"No events were dispatched during the registration process."
,regEvtCollector.collectedNewStates.size() > 0);
assertTrue(
"No registration event notifying of registration was dispatched. "
+"All events were: " + regEvtCollector.collectedNewStates
,regEvtCollector.collectedNewStates
.contains(RegistrationState.REGISTERED));
fixture.provider.removeRegistrationStateChangeListener(regEvtCollector);
}
| public void testRegister()
{
//add an event collector that will collect all events during the
//registration and allows us to later inspect them and make sure
//they were properly dispatched.
fixture.provider.addRegistrationStateChangeListener(regEvtCollector);
fixture.provider.register(new SecurityAuthorityImpl());
//give it enough time to register. We won't really have to wait all this
//time since the registration event collector would notify us the moment
//we get signed on.
try{
synchronized(registrationLock){
logger.debug("Waiting for registration to complete ...");
registrationLock.wait(40000);
logger.debug("Registration was completed or we lost patience.");
}
}
catch (InterruptedException ex){
logger.debug("Interrupted while waiting for registration", ex);
}
catch(Throwable t)
{
logger.debug("We got thrown out while waiting for registration", t);
}
// Here is registered the listener which will receive the first message
// This message is supposed to be offline message and as one is tested
// in TestOperationSetBasicInstantMessaging.testReceiveOfflineMessages()
Map supportedOperationSets =
fixture.provider.getSupportedOperationSets();
OperationSetBasicInstantMessaging opSetBasicIM =
(OperationSetBasicInstantMessaging)supportedOperationSets.get(
OperationSetBasicInstantMessaging.class.getName());
fixture.offlineMsgCollector.register(opSetBasicIM);
//give time for the AIM server to notify everyone of our arrival
//simply waitinf is really not a reliable way of doing things but I
//can't think of anything better
Object lock = new Object();
synchronized(lock)
{
try
{
logger.debug("Giving the aim server time to notify for our arrival!");
lock.wait(5000);
}
catch (Exception ex)
{}
}
//make sure the provider is on-line
assertTrue(
"The tested ICQ implementation on-line status was OFFLINE",
!IcqStatusEnum.OFFLINE.equals(
fixture.testerAgent.getBuddyStatus(fixture.ourUserID))
);
//make sure that the registration process trigerred the corresponding
//events.
assertTrue(
"No events were dispatched during the registration process."
,regEvtCollector.collectedNewStates.size() > 0);
assertTrue(
"No registration event notifying of registration was dispatched. "
+"All events were: " + regEvtCollector.collectedNewStates
,regEvtCollector.collectedNewStates
.contains(RegistrationState.REGISTERED));
fixture.provider.removeRegistrationStateChangeListener(regEvtCollector);
}
|
diff --git a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/MythicDropsPlugin.java b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/MythicDropsPlugin.java
index 21eb152d..10ca0b73 100644
--- a/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/MythicDropsPlugin.java
+++ b/MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/MythicDropsPlugin.java
@@ -1,1375 +1,1375 @@
package net.nunnerycode.bukkit.mythicdrops;
import com.conventnunnery.libraries.config.CommentedConventYamlConfiguration;
import com.conventnunnery.libraries.config.ConventYamlConfiguration;
import com.modcrafting.diablodrops.name.NamesLoader;
import net.nunnerycode.bukkit.mythicdrops.anvil.AnvilListener;
import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops;
import net.nunnerycode.bukkit.mythicdrops.api.armorsets.ArmorSet;
import net.nunnerycode.bukkit.mythicdrops.api.enchantments.MythicEnchantment;
import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem;
import net.nunnerycode.bukkit.mythicdrops.api.names.NameType;
import net.nunnerycode.bukkit.mythicdrops.api.settings.ArmorSetsSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.ConfigSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.CreatureSpawningSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.IdentifyingSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.RepairingSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.RuinsSettings;
import net.nunnerycode.bukkit.mythicdrops.api.settings.SockettingSettings;
import net.nunnerycode.bukkit.mythicdrops.api.socketting.EffectTarget;
import net.nunnerycode.bukkit.mythicdrops.api.socketting.GemType;
import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketEffect;
import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier;
import net.nunnerycode.bukkit.mythicdrops.armorsets.ArmorSetListener;
import net.nunnerycode.bukkit.mythicdrops.armorsets.MythicArmorSet;
import net.nunnerycode.bukkit.mythicdrops.commands.MythicDropsCommand;
import net.nunnerycode.bukkit.mythicdrops.identification.IdentifyingListener;
import net.nunnerycode.bukkit.mythicdrops.items.CustomItemBuilder;
import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap;
import net.nunnerycode.bukkit.mythicdrops.names.NameMap;
import net.nunnerycode.bukkit.mythicdrops.repair.MythicRepairCost;
import net.nunnerycode.bukkit.mythicdrops.repair.MythicRepairItem;
import net.nunnerycode.bukkit.mythicdrops.repair.RepairingListener;
import net.nunnerycode.bukkit.mythicdrops.ruins.RuinsWrapper;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicArmorSetsSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicConfigSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicCreatureSpawningSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicIdentifyingSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicRepairingSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicRuinsSettings;
import net.nunnerycode.bukkit.mythicdrops.settings.MythicSockettingSettings;
import net.nunnerycode.bukkit.mythicdrops.socketting.SocketCommand;
import net.nunnerycode.bukkit.mythicdrops.socketting.SocketGem;
import net.nunnerycode.bukkit.mythicdrops.socketting.SocketParticleEffect;
import net.nunnerycode.bukkit.mythicdrops.socketting.SocketPotionEffect;
import net.nunnerycode.bukkit.mythicdrops.socketting.SockettingListener;
import net.nunnerycode.bukkit.mythicdrops.spawning.ItemSpawningListener;
import net.nunnerycode.bukkit.mythicdrops.splatter.SplatterWrapper;
import net.nunnerycode.bukkit.mythicdrops.tiers.MythicTierBuilder;
import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap;
import net.nunnerycode.bukkit.mythicdrops.utils.ChatColorUtil;
import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil;
import net.nunnerycode.java.libraries.cannonball.DebugPrinter;
import org.apache.commons.lang3.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.event.HandlerList;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
import org.mcstats.Metrics;
import se.ranzdo.bukkit.methodcommand.CommandHandler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
public final class MythicDropsPlugin extends JavaPlugin implements MythicDrops {
private static MythicDropsPlugin _INSTANCE;
private ConfigSettings configSettings;
private CreatureSpawningSettings creatureSpawningSettings;
private RepairingSettings repairingSettings;
private SockettingSettings sockettingSettings;
private IdentifyingSettings identifyingSettings;
private ArmorSetsSettings armorSetsSettings;
private RuinsSettings ruinsSettings;
private DebugPrinter debugPrinter;
private CommentedConventYamlConfiguration configYAML;
private CommentedConventYamlConfiguration customItemYAML;
private CommentedConventYamlConfiguration itemGroupYAML;
private CommentedConventYamlConfiguration languageYAML;
private CommentedConventYamlConfiguration tierYAML;
private CommentedConventYamlConfiguration creatureSpawningYAML;
private CommentedConventYamlConfiguration repairingYAML;
private CommentedConventYamlConfiguration socketGemsYAML;
private CommentedConventYamlConfiguration sockettingYAML;
private CommentedConventYamlConfiguration identifyingYAML;
private CommentedConventYamlConfiguration ruinsYAML;
private CommentedConventYamlConfiguration armorSetsYAML;
private NamesLoader namesLoader;
private CommandHandler commandHandler;
private SplatterWrapper splatterWrapper;
public static MythicDropsPlugin getInstance() {
return _INSTANCE;
}
@Override
public ArmorSetsSettings getArmorSetsSettings() {
return armorSetsSettings;
}
@Override
public CommentedConventYamlConfiguration getArmorSetsYAML() {
return armorSetsYAML;
}
@Override
public CommentedConventYamlConfiguration getCreatureSpawningYAML() {
return creatureSpawningYAML;
}
@Override
public void debug(Level level, String... messages) {
if (getConfigSettings() != null && !getConfigSettings().isDebugMode()) {
return;
}
debugPrinter.debug(level, messages);
}
@Override
public ConfigSettings getConfigSettings() {
return configSettings;
}
@Override
public CreatureSpawningSettings getCreatureSpawningSettings() {
return creatureSpawningSettings;
}
@Override
public RepairingSettings getRepairingSettings() {
return repairingSettings;
}
@Override
public SockettingSettings getSockettingSettings() {
return sockettingSettings;
}
@Override
public IdentifyingSettings getIdentifyingSettings() {
return identifyingSettings;
}
@Override
public DebugPrinter getDebugPrinter() {
return debugPrinter;
}
@Override
public ConventYamlConfiguration getConfigYAML() {
return configYAML;
}
@Override
public ConventYamlConfiguration getCustomItemYAML() {
return customItemYAML;
}
@Override
public ConventYamlConfiguration getItemGroupYAML() {
return itemGroupYAML;
}
@Override
public ConventYamlConfiguration getLanguageYAML() {
return languageYAML;
}
@Override
public ConventYamlConfiguration getTierYAML() {
return tierYAML;
}
public CommentedConventYamlConfiguration getSocketGemsYAML() {
return socketGemsYAML;
}
@Override
public CommentedConventYamlConfiguration getSockettingYAML() {
return sockettingYAML;
}
public CommentedConventYamlConfiguration getRepairingYAML() {
return repairingYAML;
}
@Override
public CommentedConventYamlConfiguration getIdentifyingYAML() {
return identifyingYAML;
}
@Override
public void reloadSettings() {
loadCoreSettings();
loadCreatureSpawningSettings();
loadRepairSettings();
loadSockettingSettings();
loadSocketGems();
loadIdentifyingSettings();
loadRuinsSettings();
loadArmorSetsSettings();
loadArmorSets();
}
@Override
public void reloadTiers() {
TierMap.getInstance().clear();
CommentedConventYamlConfiguration c = tierYAML;
if (c == null) {
return;
}
List<String> loadedTierNames = new ArrayList<>();
for (String key : c.getKeys(false)) {
// Check if the key has other fields under it and if not, move on to the next
if (!c.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = c.getConfigurationSection(key);
MythicTierBuilder builder = new MythicTierBuilder(key.toLowerCase());
builder.withDisplayName(cs.getString("displayName", key));
builder.withDisplayColor(ChatColorUtil.getChatColorOrFallback(cs.getString("displayColor"),
ChatColorUtil.getRandomChatColor()));
builder.withIdentificationColor(ChatColorUtil.getChatColorOrFallback(cs.getString("identifierColor")
, ChatColorUtil.getRandomChatColor()));
ConfigurationSection enchCS = cs.getConfigurationSection("enchantments");
if (enchCS != null) {
builder.withSafeBaseEnchantments(enchCS.getBoolean("safeBaseEnchantments", true));
builder.withSafeBonusEnchantments(enchCS.getBoolean("safeBonusEnchantments", true));
builder.withHighBaseEnchantments(enchCS.getBoolean("allowHighBaseEnchantments", true));
builder.withHighBonusEnchantments(enchCS.getBoolean("allowHighBonusEnchantments", true));
builder.withMinimumBonusEnchantments(enchCS.getInt("minimumBonusEnchantments", 0));
builder.withMaximumBonusEnchantments(enchCS.getInt("maximumBonusEnchantments", 0));
Set<MythicEnchantment> baseEnchantments = new HashSet<>();
List<String> baseEnchantStrings = enchCS.getStringList("baseEnchantments");
for (String s : baseEnchantStrings) {
MythicEnchantment me = MythicEnchantment.fromString(s);
if (me != null) {
baseEnchantments.add(me);
}
}
builder.withBaseEnchantments(baseEnchantments);
Set<MythicEnchantment> bonusEnchantments = new HashSet<>();
List<String> bonusEnchantStrings = enchCS.getStringList("bonusEnchantments");
for (String s : bonusEnchantStrings) {
MythicEnchantment me = MythicEnchantment.fromString(s);
if (me != null) {
bonusEnchantments.add(me);
}
}
builder.withBonusEnchantments(bonusEnchantments);
}
ConfigurationSection loreCS = cs.getConfigurationSection("lore");
if (loreCS != null) {
builder.withMinimumBonusLore(loreCS.getInt("minimumBonusLore", 0));
builder.withMaximumBonusLore(loreCS.getInt("maximumBonusLore", 0));
builder.withBaseLore(loreCS.getStringList("baseLore"));
builder.withBonusLore(loreCS.getStringList("bonusLore"));
}
builder.withMinimumDurabilityPercentage(cs.getDouble("minimumDurability", 1.0));
builder.withMaximumDurabilityPercentage(cs.getDouble("maximumDurability", 1.0));
builder.withMinimumSockets(cs.getInt("minimumSockets", 0));
builder.withMaximumSockets(cs.getInt("maximumSockets", 0));
builder.withAllowedItemGroups(cs.getStringList("itemTypes.allowedGroups"));
builder.withDisallowedItemGroups(cs.getStringList("itemTypes.disallowedGroups"));
builder.withAllowedItemIds(cs.getStringList("itemTypes.allowedItemIds"));
builder.withDisallowedItemIds(cs.getStringList("itemTypes.disallowedItemIds"));
if (cs.isConfigurationSection("chanceToSpawnOnAMonster")) {
Map<String, Double> chanceToSpawnMap = new HashMap<>();
for (String k : cs.getConfigurationSection("chanceToSpawnOnAMonster").getKeys(false)) {
chanceToSpawnMap.put(k, cs.getDouble("chanceToSpawnOnAMonster." + k, 0));
chanceToSpawnMap.put("default", cs.getDouble("chanceToSpawnOnAMonster"));
}
builder.withWorldSpawnChanceMap(chanceToSpawnMap);
} else if (cs.isSet("chanceToSpawnOnAMonster")) {
Map<String, Double> chanceToSpawnMap = new HashMap<>();
chanceToSpawnMap.put("default", cs.getDouble("chanceToSpawnOnAMonster"));
builder.withWorldSpawnChanceMap(chanceToSpawnMap);
}
if (cs.isConfigurationSection("chanceToDropOnMonsterDeath")) {
Map<String, Double> chanceToSpawnMap = new HashMap<>();
for (String k : cs.getConfigurationSection("chanceToDropOnMonsterDeath").getKeys(false)) {
chanceToSpawnMap.put(k, cs.getDouble("chanceToDropOnMonsterDeath." + k, 1.0));
chanceToSpawnMap.put("default", cs.getDouble("chanceToDropOnMonsterDeath", 1.0));
}
builder.withWorldDropChanceMap(chanceToSpawnMap);
} else if (cs.isSet("chanceToDropOnMonsterDeath")) {
Map<String, Double> chanceToSpawnMap = new HashMap<>();
chanceToSpawnMap.put("default", cs.getDouble("chanceToDropOnMonsterDeath", 1.0));
builder.withWorldDropChanceMap(chanceToSpawnMap);
}
if (cs.isConfigurationSection("chanceToDropBeIdentified")) {
Map<String, Double> chanceToBeIdentified = new HashMap<>();
for (String k : cs.getConfigurationSection("chanceToBeIdentified").getKeys(false)) {
chanceToBeIdentified.put(k, cs.getDouble("chanceToBeIdentified." + k, 1.0));
chanceToBeIdentified.put("default", cs.getDouble("chanceToBeIdentified", 1.0));
}
builder.withWorldIdentifyChanceMap(chanceToBeIdentified);
} else if (cs.isSet("chanceToBeIdentified")) {
Map<String, Double> chanceToSpawnMap = new HashMap<>();
chanceToSpawnMap.put("default", cs.getDouble("chanceToBeIdentified", 1.0));
builder.withWorldIdentifyChanceMap(chanceToSpawnMap);
}
builder.withChanceToHaveSockets(cs.getDouble("chanceToHaveSockets", 1D));
builder.withBroadcastOnFind(cs.getBoolean("broadcastOnFind", false));
Tier t = builder.build();
if (t.getDisplayColor() == t.getIdentificationColor()) {
debug(Level.INFO, "Cannot load " + t.getName() + " due to displayColor and " +
"identificationColor being the same");
continue;
}
TierMap.getInstance().put(key.toLowerCase(), t);
loadedTierNames.add(key.toLowerCase());
}
debug(Level.INFO, "Loaded tiers: " + loadedTierNames.toString());
}
@Override
public void reloadCustomItems() {
CustomItemMap.getInstance().clear();
CommentedConventYamlConfiguration c = customItemYAML;
if (c == null) {
return;
}
List<String> loadedCustomItemsNames = new ArrayList<>();
for (String key : c.getKeys(false)) {
if (!c.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = c.getConfigurationSection(key);
CustomItemBuilder builder = new CustomItemBuilder(key);
MaterialData materialData = new MaterialData(cs.getInt("materialID", 0), (byte) cs.getInt("materialData",
0));
if (materialData.getItemTypeId() == 0) {
continue;
}
builder.withMaterialData(materialData);
builder.withDisplayName(cs.getString("displayName", key));
builder.withLore(cs.getStringList("lore"));
builder.withChanceToBeGivenToMonster(cs.getDouble("chanceToBeGivenToAMonster", 0));
builder.withChanceToDropOnDeath(cs.getDouble("chanceToDropOnDeath", 0));
Map<Enchantment, Integer> enchantments = new HashMap<>();
if (cs.isConfigurationSection("enchantments")) {
for (String ench : cs.getConfigurationSection("enchantments").getKeys(false)) {
Enchantment enchantment = Enchantment.getByName(ench);
if (enchantment == null) {
continue;
}
enchantments.put(enchantment, cs.getInt("enchantments." + ench));
}
}
builder.withEnchantments(enchantments);
builder.withBroadcastOnFind(cs.getBoolean("broadcastOnFind", false));
CustomItem ci = builder.build();
CustomItemMap.getInstance().put(key, ci);
loadedCustomItemsNames.add(key);
}
debug(Level.INFO, "Loaded custom items: " + loadedCustomItemsNames.toString());
}
@Override
public void reloadNames() {
NameMap.getInstance().clear();
loadPrefixes();
loadSuffixes();
loadLore();
loadMobNames();
}
@Override
public CommandHandler getCommandHandler() {
return commandHandler;
}
@Override
public SplatterWrapper getSplatterWrapper() {
return splatterWrapper;
}
@Override
public RuinsSettings getRuinsSettings() {
return ruinsSettings;
}
@Override
public CommentedConventYamlConfiguration getRuinsYAML() {
return ruinsYAML;
}
private void loadArmorSetsSettings() {
CommentedConventYamlConfiguration c = armorSetsYAML;
if (c == null) {
return;
}
MythicArmorSetsSettings mass = new MythicArmorSetsSettings();
mass.setEnabled(c.getBoolean("enabled", true));
this.armorSetsSettings = mass;
}
private void loadRuinsSettings() {
CommentedConventYamlConfiguration c = ruinsYAML;
MythicRuinsSettings mrs = new MythicRuinsSettings();
mrs.setEnabled(c.getBoolean("enabled"));
if (!c.isConfigurationSection("chance-to-spawn")) {
ruinsSettings = mrs;
return;
}
for (String key : c.getConfigurationSection("chance-to-spawn").getKeys(false)) {
if (c.isConfigurationSection("chance-to-spawn." + key)) {
continue;
}
mrs.setChanceToSpawn(key, c.getDouble("chance-to-spawn." + key, 0.0));
}
ruinsSettings = mrs;
}
@Override
public void onDisable() {
HandlerList.unregisterAll(this);
}
@Override
public void onEnable() {
_INSTANCE = this;
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
namesLoader = new NamesLoader(this);
unpackConfigurationFiles(new String[]{"config.yml", "customItems.yml", "itemGroups.yml", "language.yml",
"tier.yml", "creatureSpawning.yml", "repairing.yml", "socketGems.yml", "socketting.yml",
- "identifying.yml"}, false);
+ "identifying.yml", "ruins.yml", "armorSets.yml"}, false);
configYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().backupOnUpdate(true);
configYAML.options().updateOnLoad(true);
configYAML.load();
customItemYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "customItems.yml"),
YamlConfiguration.loadConfiguration(getResource("customItems.yml")).getString("version"));
customItemYAML.options().backupOnUpdate(true);
customItemYAML.options().updateOnLoad(true);
customItemYAML.load();
itemGroupYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "itemGroups.yml"),
YamlConfiguration.loadConfiguration(getResource("itemGroups.yml")).getString("version"));
itemGroupYAML.options().backupOnUpdate(true);
itemGroupYAML.options().updateOnLoad(true);
itemGroupYAML.load();
languageYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "language.yml"),
YamlConfiguration.loadConfiguration(getResource("language.yml")).getString("version"));
languageYAML.options().backupOnUpdate(true);
languageYAML.options().updateOnLoad(true);
languageYAML.load();
tierYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "tier.yml"),
YamlConfiguration.loadConfiguration(getResource("tier.yml")).getString("version"));
tierYAML.options().backupOnUpdate(true);
tierYAML.options().updateOnLoad(true);
tierYAML.load();
creatureSpawningYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "creatureSpawning.yml"),
YamlConfiguration.loadConfiguration(getResource("creatureSpawning.yml")).getString("version"));
creatureSpawningYAML.options().pathSeparator('/');
creatureSpawningYAML.options().backupOnUpdate(true);
creatureSpawningYAML.options().updateOnLoad(true);
creatureSpawningYAML.load();
repairingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "repairing.yml"),
YamlConfiguration.loadConfiguration(getResource("repairing.yml")).getString("version"));
repairingYAML.options().backupOnUpdate(true);
repairingYAML.options().updateOnLoad(true);
repairingYAML.load();
socketGemsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketGems.yml"),
YamlConfiguration.loadConfiguration(getResource("socketGems.yml")).getString("version"));
socketGemsYAML.options().backupOnUpdate(true);
socketGemsYAML.options().updateOnLoad(true);
socketGemsYAML.load();
sockettingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketting.yml"),
YamlConfiguration.loadConfiguration(getResource("socketting.yml")).getString("version"));
sockettingYAML.options().backupOnUpdate(true);
sockettingYAML.options().updateOnLoad(true);
sockettingYAML.load();
identifyingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "identifying.yml"),
YamlConfiguration.loadConfiguration(getResource("identifying.yml")).getString("version"));
identifyingYAML.options().backupOnUpdate(true);
identifyingYAML.options().updateOnLoad(true);
identifyingYAML.load();
ruinsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "ruins.yml"),
YamlConfiguration.loadConfiguration(getResource("ruins.yml")).getString("version"));
ruinsYAML.options().backupOnUpdate(true);
ruinsYAML.options().updateOnLoad(true);
ruinsYAML.load();
armorSetsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "armorSets.yml"),
YamlConfiguration.loadConfiguration(getResource("armorSets.yml")).getString("version"));
armorSetsYAML.options().backupOnUpdate(true);
armorSetsYAML.options().updateOnLoad(true);
armorSetsYAML.load();
writeResourceFiles();
reloadTiers();
reloadNames();
reloadCustomItems();
reloadSettings();
Bukkit.getPluginManager().registerEvents(new AnvilListener(), this);
commandHandler = new CommandHandler(this);
commandHandler.registerCommands(new MythicDropsCommand(this));
if (getCreatureSpawningSettings().isEnabled()) {
getLogger().info("Mobs spawning with equipment enabled");
debug(Level.INFO, "Mobs spawning with equipment enabled");
Bukkit.getPluginManager().registerEvents(new ItemSpawningListener(this), this);
}
if (getRepairingSettings().isEnabled()) {
getLogger().info("Repairing enabled");
debug(Level.INFO, "Repairing enabled");
Bukkit.getPluginManager().registerEvents(new RepairingListener(this), this);
}
if (getSockettingSettings().isEnabled()) {
getLogger().info("Socketting enabled");
debug(Level.INFO, "Socketting enabled");
Bukkit.getPluginManager().registerEvents(new SockettingListener(this), this);
}
if (getIdentifyingSettings().isEnabled()) {
getLogger().info("Identifying enabled");
debug(Level.INFO, "Identifying enabled");
Bukkit.getPluginManager().registerEvents(new IdentifyingListener(this), this);
}
if (getArmorSetsSettings().isEnabled()) {
getLogger().info("Armor Sets enabled");
debug(Level.INFO, "Armor Sets enabled");
Bukkit.getPluginManager().registerEvents(new ArmorSetListener(), this);
}
if (getConfigSettings().isReportingEnabled() && Bukkit.getPluginManager().getPlugin("Splatter") != null) {
String username = configYAML.getString("options.reporting.github-name", "githubusername");
String password = configYAML.getString("options.reporting.github-password", "githubpassword");
splatterWrapper = new SplatterWrapper(getName(), username, password);
}
if (getRuinsSettings().isEnabled() && Bukkit.getPluginManager().getPlugin("WorldEdit") != null) {
getLogger().info("Ruins enabled");
debug(Level.INFO, "Ruins enabled");
RuinsWrapper ruinsWrapper = new RuinsWrapper();
File file = new File(getDataFolder(), "/ruins/");
if (!file.exists() && file.mkdirs()) {
saveResource("/ruins/ruin1.schematic", false);
saveResource("/ruins/ruin2.schematic", false);
saveResource("/ruins/ruin3.schematic", false);
saveResource("/ruins/ruin4.schematic", false);
saveResource("/ruins/ruin5.schematic", false);
saveResource("/ruins/ruin6.schematic", false);
}
for (File f : new File(getDataFolder(), "/ruins/").listFiles()) {
ruinsWrapper.addSchematicFile(f);
}
Bukkit.getPluginManager().registerEvents(ruinsWrapper, this);
}
startMetrics();
debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
private void startMetrics() {
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeResourceFiles() {
namesLoader.writeDefault("/resources/lore/general.txt", false, true);
namesLoader.writeDefault("/resources/lore/enchantments/damage_all.txt", false, true);
namesLoader.writeDefault("/resources/lore/materials/diamond_sword.txt", false, true);
namesLoader.writeDefault("/resources/lore/tiers/legendary.txt", false, true);
namesLoader.writeDefault("/resources/prefixes/general.txt", false, true);
namesLoader.writeDefault("/resources/prefixes/enchantments/damage_all.txt", false, true);
namesLoader.writeDefault("/resources/prefixes/materials/diamond_sword.txt", false, true);
namesLoader.writeDefault("/resources/prefixes/tiers/legendary.txt", false, true);
namesLoader.writeDefault("/resources/suffixes/general.txt", false, true);
namesLoader.writeDefault("/resources/suffixes/enchantments/damage_all.txt", false, true);
namesLoader.writeDefault("/resources/suffixes/materials/diamond_sword.txt", false, true);
namesLoader.writeDefault("/resources/suffixes/tiers/legendary.txt", false, true);
namesLoader.writeDefault("/resources/mobnames/general.txt", false, true);
}
private void unpackConfigurationFiles(String[] configurationFiles, boolean overwrite) {
for (String s : configurationFiles) {
YamlConfiguration yc = YamlConfiguration.loadConfiguration(getResource(s));
try {
File f = new File(getDataFolder(), s);
if (!f.exists()) {
yc.save(f);
continue;
}
if (overwrite) {
yc.save(f);
}
} catch (IOException e) {
getLogger().warning("Could not unpack " + s);
}
}
}
private void loadCoreSettings() {
MythicConfigSettings mcs = new MythicConfigSettings();
if (configYAML != null) {
mcs.setReportingEnabled(configYAML.getBoolean("options.reporting.enabled", false));
mcs.setDebugMode(configYAML.getBoolean("options.debug", false));
mcs.setItemDisplayNameFormat(configYAML.getString("display.itemDisplayNameFormat",
"%generalprefix% %generalsuffix%"));
mcs.setRandomLoreEnabled(configYAML.getBoolean("display.tooltips.randomLoreEnabled", false));
mcs.setRandomLoreChance(configYAML.getDouble("display.tooltips.randomLoreChance", 0.25));
mcs.getTooltipFormat().addAll(configYAML.getStringList("display.tooltips.format"));
}
if (itemGroupYAML != null && itemGroupYAML.isConfigurationSection("itemGroups")) {
ConfigurationSection idCS = itemGroupYAML.getConfigurationSection("itemGroups");
if (idCS.isConfigurationSection("toolGroups")) {
List<String> toolGroupList = new ArrayList<>();
ConfigurationSection toolCS = idCS.getConfigurationSection("toolGroups");
for (String toolKind : toolCS.getKeys(false)) {
List<String> idList = toolCS.getStringList(toolKind);
toolGroupList.add(toolKind + " (" + idList.size() + ")");
mcs.getItemTypesWithIds().put(toolKind.toLowerCase(), idList);
mcs.getToolTypes().add(toolKind.toLowerCase());
}
debug(Level.INFO, "Loaded tool groups: " + toolGroupList.toString());
}
if (idCS.isConfigurationSection("armorGroups")) {
List<String> armorGroupList = new ArrayList<>();
ConfigurationSection armorCS = idCS.getConfigurationSection("armorGroups");
for (String armorKind : armorCS.getKeys(false)) {
List<String> idList = armorCS.getStringList(armorKind);
armorGroupList.add(armorKind + " (" + idList.size() + ")");
mcs.getItemTypesWithIds().put(armorKind.toLowerCase(), idList);
mcs.getArmorTypes().add(armorKind.toLowerCase());
}
debug(Level.INFO, "Loaded armor groups: " + armorGroupList.toString());
}
if (idCS.isConfigurationSection("materialGroups")) {
List<String> materialGroupList = new ArrayList<>();
ConfigurationSection materialCS = idCS.getConfigurationSection("materialGroups");
for (String materialKind : materialCS.getKeys(false)) {
List<String> idList = materialCS.getStringList(materialKind);
materialGroupList.add(materialKind + " (" + idList.size() + ")");
mcs.getMaterialTypesWithIds().put(materialKind.toLowerCase(), idList);
mcs.getMaterialTypes().add(materialKind.toLowerCase());
}
debug(Level.INFO, "Loaded material groups: " + materialGroupList.toString());
}
}
if (languageYAML != null) {
for (String s : languageYAML.getKeys(true)) {
if (languageYAML.isConfigurationSection(s)) {
continue;
}
mcs.getLanguageMap().put(s, languageYAML.getString(s, s));
}
}
this.configSettings = mcs;
}
private void loadCreatureSpawningSettings() {
MythicCreatureSpawningSettings css = new MythicCreatureSpawningSettings();
if (creatureSpawningYAML != null) {
css.setEnabled(creatureSpawningYAML.getBoolean("enabled", true));
css.setGiveMobsEquipment(creatureSpawningYAML.getBoolean("options/give-mobs-equipment", true));
css.setGiveMobsNames(creatureSpawningYAML.getBoolean("options/give-mobs-names", true));
css.setCanMobsPickUpEquipment(creatureSpawningYAML.getBoolean("options/can-mobs-pick-up-equipment", true));
css.setBlankMobSpawnEnabled(creatureSpawningYAML.getBoolean("options/blank-mob-spawn.enabled", false));
css.setBlankMobSpawnSkeletonsSpawnWithBows(!creatureSpawningYAML.getBoolean("options/blank-mob-spawn" +
"/skeletons-no-bow", false));
css.setGlobalSpawnChance(creatureSpawningYAML.getDouble("globalSpawnChance", 0.25));
css.setPreventCustom(creatureSpawningYAML.getBoolean("spawnPrevention/custom", true));
css.setPreventSpawner(creatureSpawningYAML.getBoolean("spawnPrevention/spawner", true));
css.setPreventSpawnEgg(creatureSpawningYAML.getBoolean("spawnPrevention/spawnEgg", true));
if (creatureSpawningYAML.isConfigurationSection("spawnPrevention/aboveY")) {
ConfigurationSection cs = creatureSpawningYAML.getConfigurationSection("spawnPrevention/aboveY");
for (String wn : cs.getKeys(false)) {
if (cs.isConfigurationSection(wn)) {
continue;
}
css.setSpawnHeightLimit(wn, cs.getInt(wn, 255));
}
}
css.setCustomItemsSpawn(creatureSpawningYAML.getBoolean("customItems/spawn", true));
css.setOnlyCustomItemsSpawn(creatureSpawningYAML.getBoolean("customItems/onlySpawn", false));
css.setCustomItemSpawnChance(creatureSpawningYAML.getDouble("customItems/chance", 0.05));
if (creatureSpawningYAML.isConfigurationSection("tierDrops")) {
ConfigurationSection cs = creatureSpawningYAML.getConfigurationSection("tierDrops");
for (String key : cs.getKeys(false)) {
if (cs.isConfigurationSection(key)) {
continue;
}
List<String> strings = cs.getStringList(key);
EntityType et;
try {
et = EntityType.valueOf(key);
} catch (Exception e) {
continue;
}
Set<Tier> tiers = new HashSet<>(TierUtil.getTiersFromStrings(strings));
debug(Level.INFO, et.name() + " | " + TierUtil.getStringsFromTiers(tiers).toString());
css.setEntityTypeTiers(et, tiers);
}
}
if (creatureSpawningYAML.isConfigurationSection("spawnWithDropChance")) {
ConfigurationSection cs = creatureSpawningYAML.getConfigurationSection("spawnWithDropChance");
for (String key : cs.getKeys(false)) {
if (cs.isConfigurationSection(key)) {
continue;
}
EntityType et;
try {
et = EntityType.valueOf(key);
} catch (Exception e) {
continue;
}
double d = cs.getDouble(key, 0D);
css.setEntityTypeChance(et, d);
}
}
}
this.creatureSpawningSettings = css;
}
private void loadMobNames() {
Map<String, List<String>> mobNames = new HashMap<>();
File mobNameFolder = new File(getDataFolder(), "/resources/mobnames/");
if (!mobNameFolder.exists() && !mobNameFolder.mkdirs()) {
return;
}
List<String> generalMobNames = new ArrayList<>();
namesLoader.loadFile(generalMobNames, "/resources/mobnames/general.txt");
mobNames.put(NameType.MOB_NAME.getFormat(), generalMobNames);
int numOfLoadedMobNames = generalMobNames.size();
for (File f : mobNameFolder.listFiles()) {
if (f.getName().endsWith(".txt") && !f.getName().equals("general.txt")) {
List<String> nameList = new ArrayList<>();
namesLoader.loadFile(nameList, "/resources/mobnames/" + f.getName());
mobNames.put(NameType.MOB_NAME.getFormat() + "." + f.getName().replace(".txt", "").toLowerCase(), nameList);
numOfLoadedMobNames += nameList.size();
}
}
debug(Level.INFO, "Loaded mob names: " + numOfLoadedMobNames);
NameMap.getInstance().putAll(mobNames);
}
private void loadLore() {
Map<String, List<String>> lore = new HashMap<>();
File loreFolder = new File(getDataFolder(), "/resources/lore/");
if (!loreFolder.exists() && !loreFolder.mkdirs()) {
return;
}
List<String> generalLore = new ArrayList<>();
namesLoader.loadFile(generalLore, "/resources/lore/general.txt");
lore.put(NameType.GENERAL_LORE.getFormat(), generalLore);
int numOfLoadedLore = generalLore.size();
File tierLoreFolder = new File(loreFolder, "/tiers/");
if (tierLoreFolder.exists() && tierLoreFolder.isDirectory()) {
for (File f : tierLoreFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> loreList = new ArrayList<>();
namesLoader.loadFile(loreList, "/resources/lore/tiers/" + f.getName());
lore.put(NameType.TIER_LORE.getFormat() + f.getName().replace(".txt", "").toLowerCase(), loreList);
numOfLoadedLore += loreList.size();
}
}
}
File materialLoreFolder = new File(loreFolder, "/materials/");
if (materialLoreFolder.exists() && materialLoreFolder.isDirectory()) {
for (File f : materialLoreFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> loreList = new ArrayList<>();
namesLoader.loadFile(loreList, "/resources/lore/materials/" + f.getName());
lore.put(NameType.MATERIAL_LORE.getFormat() + f.getName().replace(".txt", "").toLowerCase(), loreList);
numOfLoadedLore += loreList.size();
}
}
}
File enchantmentLoreFolder = new File(loreFolder, "/enchantments/");
if (enchantmentLoreFolder.exists() && enchantmentLoreFolder.isDirectory()) {
for (File f : enchantmentLoreFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> loreList = new ArrayList<>();
namesLoader.loadFile(loreList, "/resources/lore/enchantments/" + f.getName());
lore.put(NameType.ENCHANTMENT_LORE.getFormat() + f.getName().replace(".txt", "").toLowerCase(), loreList);
numOfLoadedLore += loreList.size();
}
}
}
debug(Level.INFO, "Loaded lore: " + numOfLoadedLore);
NameMap.getInstance().putAll(lore);
}
private void loadSuffixes() {
Map<String, List<String>> suffixes = new HashMap<>();
File suffixFolder = new File(getDataFolder(), "/resources/suffixes/");
if (!suffixFolder.exists() && !suffixFolder.mkdirs()) {
return;
}
List<String> generalSuffixes = new ArrayList<>();
namesLoader.loadFile(generalSuffixes, "/resources/suffixes/general.txt");
suffixes.put(NameType.GENERAL_SUFFIX.getFormat(), generalSuffixes);
int numOfLoadedSuffixes = generalSuffixes.size();
File tierSuffixFolder = new File(suffixFolder, "/tiers/");
if (tierSuffixFolder.exists() && tierSuffixFolder.isDirectory()) {
for (File f : tierSuffixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> suffixList = new ArrayList<>();
namesLoader.loadFile(suffixList, "/resources/suffixes/tiers/" + f.getName());
suffixes.put(NameType.TIER_SUFFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(), suffixList);
numOfLoadedSuffixes += suffixList.size();
}
}
}
File materialSuffixFolder = new File(suffixFolder, "/materials/");
if (materialSuffixFolder.exists() && materialSuffixFolder.isDirectory()) {
for (File f : materialSuffixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> suffixList = new ArrayList<>();
namesLoader.loadFile(suffixList, "/resources/suffixes/materials/" + f.getName());
suffixes.put(NameType.MATERIAL_SUFFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(), suffixList);
numOfLoadedSuffixes += suffixList.size();
}
}
}
File enchantmentSuffixFolder = new File(suffixFolder, "/enchantments/");
if (enchantmentSuffixFolder.exists() && enchantmentSuffixFolder.isDirectory()) {
for (File f : enchantmentSuffixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> suffixList = new ArrayList<>();
namesLoader.loadFile(suffixList, "/resources/suffixes/enchantments/" + f.getName());
suffixes.put(NameType.ENCHANTMENT_SUFFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(), suffixList);
numOfLoadedSuffixes += suffixList.size();
}
}
}
debug(Level.INFO, "Loaded suffixes: " + numOfLoadedSuffixes);
NameMap.getInstance().putAll(suffixes);
}
private void loadPrefixes() {
Map<String, List<String>> prefixes = new HashMap<>();
File prefixFolder = new File(getDataFolder(), "/resources/prefixes/");
if (!prefixFolder.exists() && !prefixFolder.mkdirs()) {
return;
}
List<String> generalPrefixes = new ArrayList<>();
namesLoader.loadFile(generalPrefixes, "/resources/prefixes/general.txt");
prefixes.put(NameType.GENERAL_PREFIX.getFormat(), generalPrefixes);
int numOfLoadedPrefixes = generalPrefixes.size();
File tierPrefixFolder = new File(prefixFolder, "/tiers/");
if (tierPrefixFolder.exists() && tierPrefixFolder.isDirectory()) {
for (File f : tierPrefixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> prefixList = new ArrayList<>();
namesLoader.loadFile(prefixList, "/resources/prefixes/tiers/" + f.getName());
prefixes.put(NameType.TIER_PREFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(), prefixList);
numOfLoadedPrefixes += prefixList.size();
}
}
}
File materialPrefixFolder = new File(prefixFolder, "/materials/");
if (materialPrefixFolder.exists() && materialPrefixFolder.isDirectory()) {
for (File f : materialPrefixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> prefixList = new ArrayList<>();
namesLoader.loadFile(prefixList, "/resources/prefixes/materials/" + f.getName());
prefixes.put(NameType.MATERIAL_PREFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(), prefixList);
numOfLoadedPrefixes += prefixList.size();
}
}
}
File enchantmentPrefixFolder = new File(prefixFolder, "/enchantments/");
if (enchantmentPrefixFolder.exists() && enchantmentPrefixFolder.isDirectory()) {
for (File f : enchantmentPrefixFolder.listFiles()) {
if (f.getName().endsWith(".txt")) {
List<String> prefixList = new ArrayList<>();
namesLoader.loadFile(prefixList, "/resources/prefixes/enchantments/" + f.getName());
prefixes.put(NameType.ENCHANTMENT_PREFIX.getFormat() + f.getName().replace(".txt", "").toLowerCase(),
prefixList);
numOfLoadedPrefixes += prefixList.size();
}
}
}
debug(Level.INFO, "Loaded prefixes: " + numOfLoadedPrefixes);
NameMap.getInstance().putAll(prefixes);
}
private void loadRepairSettings() {
CommentedConventYamlConfiguration c = repairingYAML;
if (!c.isConfigurationSection("repair-costs")) {
defaultRepairCosts();
}
MythicRepairingSettings mrs = new MythicRepairingSettings();
mrs.setEnabled(c.getBoolean("enabled", true));
mrs.setPlaySounds(c.getBoolean("play-sounds", true));
ConfigurationSection costs = c.getConfigurationSection("repair-costs");
for (String key : costs.getKeys(false)) {
if (!costs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = costs.getConfigurationSection(key);
MaterialData matData = parseMaterialData(cs);
String itemName = cs.getString("item-name");
List<String> itemLore = cs.getStringList("item-lore");
List<MythicRepairCost> costList = new ArrayList<>();
ConfigurationSection costsSection = cs.getConfigurationSection("costs");
for (String costKey : costsSection.getKeys(false)) {
if (!costsSection.isConfigurationSection(costKey)) {
continue;
}
ConfigurationSection costSection = costsSection.getConfigurationSection(costKey);
MaterialData itemCost = parseMaterialData(costSection);
int experienceCost = costSection.getInt("experience-cost", 0);
int priority = costSection.getInt("priority", 0);
int amount = costSection.getInt("amount", 1);
double repairPerCost = costSection.getDouble("repair-per-cost", 0.1);
String costName = costSection.getString("item-name");
List<String> costLore = costSection.getStringList("item-lore");
MythicRepairCost rc = new MythicRepairCost(costKey, priority, experienceCost, repairPerCost, amount, itemCost,
costName, costLore);
costList.add(rc);
}
MythicRepairItem ri = new MythicRepairItem(key, matData, itemName, itemLore);
ri.addRepairCosts(costList.toArray(new MythicRepairCost[costList.size()]));
mrs.getRepairItemMap().put(ri.getName(), ri);
}
repairingSettings = mrs;
debug(Level.INFO, "Loaded repair items: " + mrs.getRepairItemMap().keySet().size());
}
private void defaultRepairCosts() {
Material[] wood = {Material.WOOD_AXE, Material.WOOD_HOE, Material.WOOD_PICKAXE, Material.WOOD_SPADE,
Material.WOOD_SWORD, Material.BOW, Material.FISHING_ROD};
Material[] stone = {Material.STONE_AXE, Material.STONE_PICKAXE, Material.STONE_HOE, Material.STONE_SWORD,
Material.STONE_SPADE};
Material[] leather = {Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET,
Material.LEATHER_LEGGINGS};
Material[] chain = {Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_LEGGINGS};
Material[] iron = {Material.IRON_AXE, Material.IRON_BOOTS, Material.IRON_CHESTPLATE, Material.IRON_HELMET,
Material.IRON_LEGGINGS, Material.IRON_PICKAXE, Material.IRON_HOE, Material.IRON_SPADE,
Material.IRON_SWORD};
Material[] diamond = {Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_HELMET, Material.DIAMOND_HOE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_PICKAXE,
Material.DIAMOND_SPADE, Material.DIAMOND_SWORD};
Material[] gold = {Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
Material.GOLD_LEGGINGS, Material.GOLD_PICKAXE, Material.GOLD_HOE, Material.GOLD_SPADE,
Material.GOLD_SWORD};
for (Material m : wood) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.WOOD.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : stone) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.STONE.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : gold) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.GOLD_INGOT.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : iron) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_INGOT.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : diamond) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.DIAMOND.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : leather) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.LEATHER.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : chain) {
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_FENCE.name());
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
repairingYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
repairingYAML.save();
}
private MaterialData parseMaterialData(ConfigurationSection cs) {
String materialDat = cs.getString("material-data", "");
String materialName = cs.getString("material-name", "");
if (materialDat.isEmpty()) {
return new MaterialData(Material.getMaterial(materialName));
}
int id = 0;
byte data = 0;
String[] split = materialDat.split(";");
switch (split.length) {
case 0:
break;
case 1:
id = NumberUtils.toInt(split[0], 0);
break;
default:
id = NumberUtils.toInt(split[0], 0);
data = NumberUtils.toByte(split[1], (byte) 0);
break;
}
return new MaterialData(id, data);
}
private void loadSockettingSettings() {
CommentedConventYamlConfiguration c = sockettingYAML;
MythicSockettingSettings mss = new MythicSockettingSettings();
mss.setEnabled(c.getBoolean("enabled", true));
mss.setUseAttackerItemInHand(c.getBoolean("options.use-attacker-item-in-hand", true));
mss.setUseAttackerArmorEquipped(c.getBoolean("options.use-attacker-armor-equipped", false));
mss.setUseDefenderItemInHand(c.getBoolean("options.use-defender-item-in-hand", false));
mss.setUseDefenderArmorEquipped(c.getBoolean("options.use-defender-armor-equipped", true));
mss.setPreventMultipleChangesFromSockets(c.getBoolean("options.prevent-multiple-changes-from-sockets", true));
mss.setSocketGemChanceToSpawn(c.getDouble("options.socket-gem-chance-to-spawn", 0.25));
List<String> socketGemMats = c.getStringList("options.socket-gem-material-ids");
List<MaterialData> socketGemMaterialDatas = new ArrayList<>();
for (String s : socketGemMats) {
int id;
byte data;
if (s.contains(";")) {
String[] split = s.split(";");
id = NumberUtils.toInt(split[0], 0);
data = (byte) NumberUtils.toInt(split[1], 0);
} else if (s.contains(":")) {
String[] split = s.split(":");
id = NumberUtils.toInt(split[0], 0);
data = (byte) NumberUtils.toInt(split[1], 0);
} else {
id = NumberUtils.toInt(s, 0);
data = 0;
}
if (id == 0) {
continue;
}
socketGemMaterialDatas.add(new MaterialData(id, data));
}
mss.setSocketGemMaterialDatas(socketGemMaterialDatas);
mss.setSocketGemName(c.getString("items.socket-name", "&6Socket Gem - %socketgem%"));
mss.setSocketGemLore(c.getStringList("items.socket-lore"));
mss.setSockettedItemString(c.getString("items.socketted-item-socket", "&6(Socket)"));
mss.setSockettedItemLore(c.getStringList("items.socketted-item-lore"));
sockettingSettings = mss;
}
private void loadArmorSets() {
armorSetsSettings.getArmorSetMap().clear();
List<String> loadedArmorSets = new ArrayList<>();
if (!armorSetsYAML.isConfigurationSection("armor-sets")) {
return;
}
ConfigurationSection cs = armorSetsYAML.getConfigurationSection("armor-sets");
for (String key : cs.getKeys(false)) {
if (!cs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection asCS = cs.getConfigurationSection(key);
ArmorSet as = new MythicArmorSet(key);
if (asCS.isConfigurationSection("one-item")) {
ConfigurationSection itemCS = cs.getConfigurationSection("one-item");
List<SocketEffect> itemEffects = new ArrayList<SocketEffect>(buildSocketPotionEffects(itemCS));
itemEffects.addAll(buildSocketParticleEffects(itemCS));
as.getOneItemEffects().addAll(itemEffects);
}
if (asCS.isConfigurationSection("two-item")) {
ConfigurationSection itemCS = cs.getConfigurationSection("two-item");
List<SocketEffect> itemEffects = new ArrayList<SocketEffect>(buildSocketPotionEffects(itemCS));
itemEffects.addAll(buildSocketParticleEffects(itemCS));
as.getTwoItemEffects().addAll(itemEffects);
}
if (asCS.isConfigurationSection("three-item")) {
ConfigurationSection itemCS = cs.getConfigurationSection("three-item");
List<SocketEffect> itemEffects = new ArrayList<SocketEffect>(buildSocketPotionEffects(itemCS));
itemEffects.addAll(buildSocketParticleEffects(itemCS));
as.getThreeItemEffects().addAll(itemEffects);
}
if (asCS.isConfigurationSection("four-item")) {
ConfigurationSection itemCS = cs.getConfigurationSection("four-item");
List<SocketEffect> itemEffects = new ArrayList<SocketEffect>(buildSocketPotionEffects(itemCS));
itemEffects.addAll(buildSocketParticleEffects(itemCS));
as.getFourItemEffects().addAll(itemEffects);
}
if (asCS.isConfigurationSection("five-item")) {
ConfigurationSection itemCS = cs.getConfigurationSection("five-item");
List<SocketEffect> itemEffects = new ArrayList<SocketEffect>(buildSocketPotionEffects(itemCS));
itemEffects.addAll(buildSocketParticleEffects(itemCS));
as.getFiveItemEffects().addAll(itemEffects);
}
armorSetsSettings.getArmorSetMap().put(key, as);
loadedArmorSets.add(key);
}
debug(Level.INFO, "Loaded armor sets: " + loadedArmorSets.toString());
}
private List<SocketParticleEffect> buildSocketParticleEffects(ConfigurationSection cs) {
List<SocketParticleEffect> socketParticleEffectList = new ArrayList<>();
if (!cs.isConfigurationSection("particle-effects")) {
return socketParticleEffectList;
}
ConfigurationSection cs1 = cs.getConfigurationSection("particle-effects");
for (String key : cs1.getKeys(false)) {
Effect pet;
try {
pet = Effect.valueOf(key);
} catch (Exception e) {
continue;
}
if (pet == null) {
continue;
}
int duration = cs1.getInt(key + ".duration");
int intensity = cs1.getInt(key + ".intensity");
int radius = cs1.getInt(key + ".radius");
String target = cs1.getString(key + ".target");
EffectTarget et = EffectTarget.getFromName(target);
if (et == null) {
et = EffectTarget.NONE;
}
boolean affectsWielder = cs1.getBoolean(key + ".affectsWielder");
boolean affectsTarget = cs1.getBoolean(key + ".affectsTarget");
socketParticleEffectList.add(new SocketParticleEffect(pet, intensity, duration, radius, et,
affectsWielder, affectsTarget));
}
return socketParticleEffectList;
}
private List<SocketPotionEffect> buildSocketPotionEffects(ConfigurationSection cs) {
List<SocketPotionEffect> socketPotionEffectList = new ArrayList<>();
if (!cs.isConfigurationSection("potion-effects")) {
return socketPotionEffectList;
}
ConfigurationSection cs1 = cs.getConfigurationSection("potion-effects");
for (String key : cs1.getKeys(false)) {
PotionEffectType pet = PotionEffectType.getByName(key);
if (pet == null) {
continue;
}
int duration = cs1.getInt(key + ".duration");
int intensity = cs1.getInt(key + ".intensity");
int radius = cs1.getInt(key + ".radius");
String target = cs1.getString(key + ".target");
EffectTarget et = EffectTarget.getFromName(target);
if (et == null) {
et = EffectTarget.NONE;
}
boolean affectsWielder = cs1.getBoolean(key + ".affectsWielder");
boolean affectsTarget = cs1.getBoolean(key + ".affectsTarget");
socketPotionEffectList.add(new SocketPotionEffect(pet, intensity, duration, radius, et, affectsWielder,
affectsTarget));
}
return socketPotionEffectList;
}
private void loadSocketGems() {
getSockettingSettings().getSocketGemMap().clear();
List<String> loadedSocketGems = new ArrayList<>();
if (!socketGemsYAML.isConfigurationSection("socket-gems")) {
return;
}
ConfigurationSection cs = socketGemsYAML.getConfigurationSection("socket-gems");
for (String key : cs.getKeys(false)) {
if (!cs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection gemCS = cs.getConfigurationSection(key);
GemType gemType = GemType.getFromName(gemCS.getString("type"));
if (gemType == null) {
gemType = GemType.ANY;
}
List<SocketPotionEffect> socketPotionEffects = buildSocketPotionEffects(gemCS);
List<SocketParticleEffect> socketParticleEffects = buildSocketParticleEffects(gemCS);
List<SocketEffect> socketEffects = new ArrayList<SocketEffect>(socketPotionEffects);
socketEffects.addAll(socketParticleEffects);
double chance = gemCS.getDouble("chance");
String prefix = gemCS.getString("prefix");
if (prefix != null && !prefix.equalsIgnoreCase("")) {
getSockettingSettings().getSocketGemPrefixes().add(prefix);
}
String suffix = gemCS.getString("suffix");
if (suffix != null && !suffix.equalsIgnoreCase("")) {
getSockettingSettings().getSocketGemSuffixes().add(suffix);
}
List<String> lore = gemCS.getStringList("lore");
Map<Enchantment, Integer> enchantments = new HashMap<>();
if (gemCS.isConfigurationSection("enchantments")) {
ConfigurationSection enchCS = gemCS.getConfigurationSection("enchantments");
for (String key1 : enchCS.getKeys(false)) {
Enchantment ench = null;
for (Enchantment ec : Enchantment.values()) {
if (ec.getName().equalsIgnoreCase(key1)) {
ench = ec;
break;
}
}
if (ench == null) {
continue;
}
int level = enchCS.getInt(key1);
enchantments.put(ench, level);
}
}
List<String> commands = gemCS.getStringList("commands");
List<SocketCommand> socketCommands = new ArrayList<>();
for (String s : commands) {
SocketCommand sc = new SocketCommand(s);
socketCommands.add(sc);
}
SocketGem sg = new SocketGem(key, gemType, socketEffects, chance, prefix, suffix, lore, enchantments,
socketCommands);
getSockettingSettings().getSocketGemMap().put(key, sg);
loadedSocketGems.add(key);
}
debug(Level.INFO, "Loaded socket gems: " + loadedSocketGems.toString());
}
private void loadIdentifyingSettings() {
CommentedConventYamlConfiguration c = identifyingYAML;
MythicIdentifyingSettings mis = new MythicIdentifyingSettings();
mis.setEnabled(c.getBoolean("enabled", true));
mis.setIdentityTomeName(c.getString("items.identity-tome.name", "&5Identity Tome"));
mis.setIdentityTomeLore(c.getStringList("items.identity-tome.lore"));
mis.setIdentityTomeChanceToSpawn(c.getDouble("items.identity-tome.chance-to-spawn", 0.1));
mis.setUnidentifiedItemName(c.getString("items.unidentified-item.name", "&FUnidentified Item"));
mis.setUnidentifiedItemLore(c.getStringList("items.unidentified-item.lore"));
mis.setUnidentifiedItemChanceToSpawn(c.getDouble("items.unidentified-item.chance-to-spawn", 0.5));
identifyingSettings = mis;
}
}
| true | true | public void onEnable() {
_INSTANCE = this;
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
namesLoader = new NamesLoader(this);
unpackConfigurationFiles(new String[]{"config.yml", "customItems.yml", "itemGroups.yml", "language.yml",
"tier.yml", "creatureSpawning.yml", "repairing.yml", "socketGems.yml", "socketting.yml",
"identifying.yml"}, false);
configYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().backupOnUpdate(true);
configYAML.options().updateOnLoad(true);
configYAML.load();
customItemYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "customItems.yml"),
YamlConfiguration.loadConfiguration(getResource("customItems.yml")).getString("version"));
customItemYAML.options().backupOnUpdate(true);
customItemYAML.options().updateOnLoad(true);
customItemYAML.load();
itemGroupYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "itemGroups.yml"),
YamlConfiguration.loadConfiguration(getResource("itemGroups.yml")).getString("version"));
itemGroupYAML.options().backupOnUpdate(true);
itemGroupYAML.options().updateOnLoad(true);
itemGroupYAML.load();
languageYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "language.yml"),
YamlConfiguration.loadConfiguration(getResource("language.yml")).getString("version"));
languageYAML.options().backupOnUpdate(true);
languageYAML.options().updateOnLoad(true);
languageYAML.load();
tierYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "tier.yml"),
YamlConfiguration.loadConfiguration(getResource("tier.yml")).getString("version"));
tierYAML.options().backupOnUpdate(true);
tierYAML.options().updateOnLoad(true);
tierYAML.load();
creatureSpawningYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "creatureSpawning.yml"),
YamlConfiguration.loadConfiguration(getResource("creatureSpawning.yml")).getString("version"));
creatureSpawningYAML.options().pathSeparator('/');
creatureSpawningYAML.options().backupOnUpdate(true);
creatureSpawningYAML.options().updateOnLoad(true);
creatureSpawningYAML.load();
repairingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "repairing.yml"),
YamlConfiguration.loadConfiguration(getResource("repairing.yml")).getString("version"));
repairingYAML.options().backupOnUpdate(true);
repairingYAML.options().updateOnLoad(true);
repairingYAML.load();
socketGemsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketGems.yml"),
YamlConfiguration.loadConfiguration(getResource("socketGems.yml")).getString("version"));
socketGemsYAML.options().backupOnUpdate(true);
socketGemsYAML.options().updateOnLoad(true);
socketGemsYAML.load();
sockettingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketting.yml"),
YamlConfiguration.loadConfiguration(getResource("socketting.yml")).getString("version"));
sockettingYAML.options().backupOnUpdate(true);
sockettingYAML.options().updateOnLoad(true);
sockettingYAML.load();
identifyingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "identifying.yml"),
YamlConfiguration.loadConfiguration(getResource("identifying.yml")).getString("version"));
identifyingYAML.options().backupOnUpdate(true);
identifyingYAML.options().updateOnLoad(true);
identifyingYAML.load();
ruinsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "ruins.yml"),
YamlConfiguration.loadConfiguration(getResource("ruins.yml")).getString("version"));
ruinsYAML.options().backupOnUpdate(true);
ruinsYAML.options().updateOnLoad(true);
ruinsYAML.load();
armorSetsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "armorSets.yml"),
YamlConfiguration.loadConfiguration(getResource("armorSets.yml")).getString("version"));
armorSetsYAML.options().backupOnUpdate(true);
armorSetsYAML.options().updateOnLoad(true);
armorSetsYAML.load();
writeResourceFiles();
reloadTiers();
reloadNames();
reloadCustomItems();
reloadSettings();
Bukkit.getPluginManager().registerEvents(new AnvilListener(), this);
commandHandler = new CommandHandler(this);
commandHandler.registerCommands(new MythicDropsCommand(this));
if (getCreatureSpawningSettings().isEnabled()) {
getLogger().info("Mobs spawning with equipment enabled");
debug(Level.INFO, "Mobs spawning with equipment enabled");
Bukkit.getPluginManager().registerEvents(new ItemSpawningListener(this), this);
}
if (getRepairingSettings().isEnabled()) {
getLogger().info("Repairing enabled");
debug(Level.INFO, "Repairing enabled");
Bukkit.getPluginManager().registerEvents(new RepairingListener(this), this);
}
if (getSockettingSettings().isEnabled()) {
getLogger().info("Socketting enabled");
debug(Level.INFO, "Socketting enabled");
Bukkit.getPluginManager().registerEvents(new SockettingListener(this), this);
}
if (getIdentifyingSettings().isEnabled()) {
getLogger().info("Identifying enabled");
debug(Level.INFO, "Identifying enabled");
Bukkit.getPluginManager().registerEvents(new IdentifyingListener(this), this);
}
if (getArmorSetsSettings().isEnabled()) {
getLogger().info("Armor Sets enabled");
debug(Level.INFO, "Armor Sets enabled");
Bukkit.getPluginManager().registerEvents(new ArmorSetListener(), this);
}
if (getConfigSettings().isReportingEnabled() && Bukkit.getPluginManager().getPlugin("Splatter") != null) {
String username = configYAML.getString("options.reporting.github-name", "githubusername");
String password = configYAML.getString("options.reporting.github-password", "githubpassword");
splatterWrapper = new SplatterWrapper(getName(), username, password);
}
if (getRuinsSettings().isEnabled() && Bukkit.getPluginManager().getPlugin("WorldEdit") != null) {
getLogger().info("Ruins enabled");
debug(Level.INFO, "Ruins enabled");
RuinsWrapper ruinsWrapper = new RuinsWrapper();
File file = new File(getDataFolder(), "/ruins/");
if (!file.exists() && file.mkdirs()) {
saveResource("/ruins/ruin1.schematic", false);
saveResource("/ruins/ruin2.schematic", false);
saveResource("/ruins/ruin3.schematic", false);
saveResource("/ruins/ruin4.schematic", false);
saveResource("/ruins/ruin5.schematic", false);
saveResource("/ruins/ruin6.schematic", false);
}
for (File f : new File(getDataFolder(), "/ruins/").listFiles()) {
ruinsWrapper.addSchematicFile(f);
}
Bukkit.getPluginManager().registerEvents(ruinsWrapper, this);
}
startMetrics();
debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
| public void onEnable() {
_INSTANCE = this;
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
namesLoader = new NamesLoader(this);
unpackConfigurationFiles(new String[]{"config.yml", "customItems.yml", "itemGroups.yml", "language.yml",
"tier.yml", "creatureSpawning.yml", "repairing.yml", "socketGems.yml", "socketting.yml",
"identifying.yml", "ruins.yml", "armorSets.yml"}, false);
configYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().backupOnUpdate(true);
configYAML.options().updateOnLoad(true);
configYAML.load();
customItemYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "customItems.yml"),
YamlConfiguration.loadConfiguration(getResource("customItems.yml")).getString("version"));
customItemYAML.options().backupOnUpdate(true);
customItemYAML.options().updateOnLoad(true);
customItemYAML.load();
itemGroupYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "itemGroups.yml"),
YamlConfiguration.loadConfiguration(getResource("itemGroups.yml")).getString("version"));
itemGroupYAML.options().backupOnUpdate(true);
itemGroupYAML.options().updateOnLoad(true);
itemGroupYAML.load();
languageYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "language.yml"),
YamlConfiguration.loadConfiguration(getResource("language.yml")).getString("version"));
languageYAML.options().backupOnUpdate(true);
languageYAML.options().updateOnLoad(true);
languageYAML.load();
tierYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "tier.yml"),
YamlConfiguration.loadConfiguration(getResource("tier.yml")).getString("version"));
tierYAML.options().backupOnUpdate(true);
tierYAML.options().updateOnLoad(true);
tierYAML.load();
creatureSpawningYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "creatureSpawning.yml"),
YamlConfiguration.loadConfiguration(getResource("creatureSpawning.yml")).getString("version"));
creatureSpawningYAML.options().pathSeparator('/');
creatureSpawningYAML.options().backupOnUpdate(true);
creatureSpawningYAML.options().updateOnLoad(true);
creatureSpawningYAML.load();
repairingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "repairing.yml"),
YamlConfiguration.loadConfiguration(getResource("repairing.yml")).getString("version"));
repairingYAML.options().backupOnUpdate(true);
repairingYAML.options().updateOnLoad(true);
repairingYAML.load();
socketGemsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketGems.yml"),
YamlConfiguration.loadConfiguration(getResource("socketGems.yml")).getString("version"));
socketGemsYAML.options().backupOnUpdate(true);
socketGemsYAML.options().updateOnLoad(true);
socketGemsYAML.load();
sockettingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "socketting.yml"),
YamlConfiguration.loadConfiguration(getResource("socketting.yml")).getString("version"));
sockettingYAML.options().backupOnUpdate(true);
sockettingYAML.options().updateOnLoad(true);
sockettingYAML.load();
identifyingYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "identifying.yml"),
YamlConfiguration.loadConfiguration(getResource("identifying.yml")).getString("version"));
identifyingYAML.options().backupOnUpdate(true);
identifyingYAML.options().updateOnLoad(true);
identifyingYAML.load();
ruinsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "ruins.yml"),
YamlConfiguration.loadConfiguration(getResource("ruins.yml")).getString("version"));
ruinsYAML.options().backupOnUpdate(true);
ruinsYAML.options().updateOnLoad(true);
ruinsYAML.load();
armorSetsYAML = new CommentedConventYamlConfiguration(new File(getDataFolder(), "armorSets.yml"),
YamlConfiguration.loadConfiguration(getResource("armorSets.yml")).getString("version"));
armorSetsYAML.options().backupOnUpdate(true);
armorSetsYAML.options().updateOnLoad(true);
armorSetsYAML.load();
writeResourceFiles();
reloadTiers();
reloadNames();
reloadCustomItems();
reloadSettings();
Bukkit.getPluginManager().registerEvents(new AnvilListener(), this);
commandHandler = new CommandHandler(this);
commandHandler.registerCommands(new MythicDropsCommand(this));
if (getCreatureSpawningSettings().isEnabled()) {
getLogger().info("Mobs spawning with equipment enabled");
debug(Level.INFO, "Mobs spawning with equipment enabled");
Bukkit.getPluginManager().registerEvents(new ItemSpawningListener(this), this);
}
if (getRepairingSettings().isEnabled()) {
getLogger().info("Repairing enabled");
debug(Level.INFO, "Repairing enabled");
Bukkit.getPluginManager().registerEvents(new RepairingListener(this), this);
}
if (getSockettingSettings().isEnabled()) {
getLogger().info("Socketting enabled");
debug(Level.INFO, "Socketting enabled");
Bukkit.getPluginManager().registerEvents(new SockettingListener(this), this);
}
if (getIdentifyingSettings().isEnabled()) {
getLogger().info("Identifying enabled");
debug(Level.INFO, "Identifying enabled");
Bukkit.getPluginManager().registerEvents(new IdentifyingListener(this), this);
}
if (getArmorSetsSettings().isEnabled()) {
getLogger().info("Armor Sets enabled");
debug(Level.INFO, "Armor Sets enabled");
Bukkit.getPluginManager().registerEvents(new ArmorSetListener(), this);
}
if (getConfigSettings().isReportingEnabled() && Bukkit.getPluginManager().getPlugin("Splatter") != null) {
String username = configYAML.getString("options.reporting.github-name", "githubusername");
String password = configYAML.getString("options.reporting.github-password", "githubpassword");
splatterWrapper = new SplatterWrapper(getName(), username, password);
}
if (getRuinsSettings().isEnabled() && Bukkit.getPluginManager().getPlugin("WorldEdit") != null) {
getLogger().info("Ruins enabled");
debug(Level.INFO, "Ruins enabled");
RuinsWrapper ruinsWrapper = new RuinsWrapper();
File file = new File(getDataFolder(), "/ruins/");
if (!file.exists() && file.mkdirs()) {
saveResource("/ruins/ruin1.schematic", false);
saveResource("/ruins/ruin2.schematic", false);
saveResource("/ruins/ruin3.schematic", false);
saveResource("/ruins/ruin4.schematic", false);
saveResource("/ruins/ruin5.schematic", false);
saveResource("/ruins/ruin6.schematic", false);
}
for (File f : new File(getDataFolder(), "/ruins/").listFiles()) {
ruinsWrapper.addSchematicFile(f);
}
Bukkit.getPluginManager().registerEvents(ruinsWrapper, this);
}
startMetrics();
debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
|
diff --git a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
index 68766d12..f231a82f 100644
--- a/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
+++ b/tests/org.jboss.tools.dummy.ui.bot.test/src/org/jboss/tools/dummy/ui/bot/test/DummyTest.java
@@ -1,69 +1,69 @@
package org.jboss.tools.dummy.ui.bot.test;
import static org.eclipse.swtbot.swt.finder.waits.Conditions.shellIsActive;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Dummy bot tests - designed to test jenkins slaves
* @author jpeterka
*
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public class DummyTest {
Logger log = Logger.getLogger("");
@BeforeClass
public static void before() {
}
@Test
public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
- prefMenu = "Preferences...";
+ prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
@Test
public void hundredTimes() {
final int cycles = 100;
for (int i = 0 ; i < cycles ; i++)
{
dummyTest();
log.info(i+1 + "/" + cycles + " try passed");
}
}
@AfterClass
public static void after() {
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.closeAllShells();
}
public boolean isOSX() {
String osName = System.getProperty("os.name");
boolean osX = osName.contains("OS X");
log.info("OS Name: " + osName);
return osX;
}
}
| true | true | public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences...";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
| public void dummyTest() {
String prefMenu = "Preferences";
String prefDlg = prefMenu;
String windowMenu = "Window";
if (isOSX()) {
prefMenu = "Preferences";
windowMenu = "Eclipse";
}
SWTWorkbenchBot bot = new SWTWorkbenchBot();
bot.menu(windowMenu).menu(prefMenu).click();
bot.waitUntil(shellIsActive(prefDlg), 10000);
SWTBotShell shell = bot.shell(prefDlg);
assertEquals(prefDlg,shell.getText());
bot.activeShell().close();
}
|
diff --git a/app/models/Asset.java b/app/models/Asset.java
index 4e4c0e1a..3d0988f0 100644
--- a/app/models/Asset.java
+++ b/app/models/Asset.java
@@ -1,567 +1,568 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*
*/
package models;
import controllers.DoSearch;
import helpers.Helpers;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.*;
import play.db.jpa.GenericModel;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XsltTransformer;
import play.db.jpa.JPABase;
import play.modules.search.Field;
import play.modules.search.Indexed;
/**
*
*
* This class holds all xml-files
* Variants of originals are held in variant-counter, original is number 0
* Name of xml-file is preserved as given when uploaded
* Name of assets should be on type
*
* Enunmeration of asset-type is kept in string due to db-restrinctions on jpa-enums
*
*/
@Indexed
@Entity
public class Asset extends GenericModel {
@Id
@SequenceGenerator(name = "asset_id_seq_gen", sequenceName = "asset_id_seq")
@GeneratedValue(generator = "asset_id_seq_gen")
public long id;
@Lob
public String xml;
@Lob
public String html;
@Field
@Lob
public String htmlAsText;
@Lob
public String comment;
@Lob
public String name;
@Lob
public String fileName;
public int variant;
public int pictureNumber = 0;
@Column(name = "import_date")
@Temporal(TemporalType.TIMESTAMP)
public java.util.Date importDate;
@Lob
public String rootName;
@Lob
public String type;
@Lob
public String refs;
/* no enum-support in db, unfornately */
public static String imageType = "imageType";
public static String countryImage = "countryuImage";
public static String introType = "introType";
public static String manusType = "manus";
public static String rootType = "root";
public static String variantType = "variant";
public static String commentType = "comment";
public static String mythType = "myth";
public static String personType = "person";
public static String placeType = "place";
public static String veiledningType = "veiledning";
public static String txrType = "txr";
public static String varListType = "varList";
public static String bibleType = "bible";
public static String registranten = "registranten";
public static String bookinventory = "bookinventory";
public static String mapVej = "mapVej";
public static String mapXml = "mapXml";
/**
* Used by images
* images on form rootname_number.jpg
*/
public Asset(String name, String fileName, String comment, String type) {
this.name = name;
this.fileName = fileName;
this.comment = comment;
this.type = type;
this.rootName = fileName.replace(".jpg", "").replaceFirst("_\\d+$", "");
System.out.println("Rootname: " + rootName);
}
public Asset(String name, String fileName, String html, String xml, String comment, int variant, String type, String ref) {
System.out.println("***** Constructing new asset, type is: " + type);
this.variant = variant;
this.name = name;
this.html = html;
this.xml = xml;
this.importDate = new java.util.Date();
this.comment = comment;
this.fileName = fileName;
this.rootName = getRootName(fileName, type);
this.type = type;
this.refs = ref;
System.out.println("Root-name: " + rootName);
}
/**
* Always make html searchable as text before saving
*/
@Override
public <T extends JPABase> T save() {
System.out.println("Hey - I am saved");
htmlAsText = Helpers.stripHtml(html);
return super.save();
}
/**
* create teaser for search-list
*
* @return html with lookfor highlighted
*/
public String getTeaser(String lookfor) {
return DoSearch.createTeaser(htmlAsText, lookfor);
}
/**
* Get the id for an asset
* Use the filename is a key
*
* @return database-id
*
*/
public long getCorrespondingRootId() {
System.out.println("Getting root for: " + this.fileName);
Asset root = Asset.find("rootName = ? and type = ?", rootName, Asset.rootType).first();
return root.id;
}
/**
* The txt-file should have a corresponding intro-file
* @return id of intro-file asset
*
*/
public String getCorrespondingIntro() {
System.out.println("Looking for rootname: " + rootName);
Asset intro = Asset.find("rootName = ? and type = ?", rootName, Asset.introType).first();
return (intro != null ? intro.html : "");
}
/**
* The txt-file should have a corresponding txr-file
* @return id of txt-file
*
*/
public String getCorrespondingTxr() {
Asset txr = Asset.find("rootName = ? and type = ?", rootName, Asset.txrType).first();
System.out.println("Txr is: " + txr);
return (txr != null ? txr.html : "");
}
/**
* The txt-file should have a corresponding comment-file
*
* @return comment-content as String after preprocessing
*
*/
public String getCorrespondingComment() {
Asset comment = Asset.find("fileName = ? and type = ?", rootName + "_com.xml", Asset.commentType).first();
// System.out.println("Corresponding comment: " + intro.html);
return (comment != null ? comment.html : "");
}
/**
* Get xml and references for this asset
* Currently not in use
*/
public String getHtmlAndReferences() {
return xml + refs;
}
/**
* Calculates root name of an asset, based on the syntax of the filename
* The root-name is stored in the asset model
* @return root-name of the asset
*/
public static String getRootName(String fileNameIn, String assetType) {
String fileName = fileNameIn;
fileName = fileName.replaceFirst(".xml", "").replaceFirst("_intro", "").replaceFirst("_com", "").replaceFirst("_txt", "").replaceFirst("_varList", "").replaceFirst("_txr", "").replaceFirst("_fax", "");
if (assetType.equals(Asset.rootType) ||
assetType.equals(Asset.commentType) ||
assetType.equals(Asset.introType) ||
assetType.equals(Asset.txrType) ||
assetType.equals(Asset.veiledningType) ||
assetType.equals(Asset.varListType)) return fileName;
Pattern pattern = Pattern.compile("(.*)_.*\\d+$");
Matcher matcher = pattern.matcher(fileName);
if (!matcher.matches()) {
System.out.println("Setting root name to: " + fileName);
return fileName;
} else {
System.out.println("Setting root name to (regexp match): " + matcher.group(1));
return matcher.group(1);
}
}
public static Asset uploadCountryImage(String name, String comment, File file) {
String fileName = file.getName();
Asset asset = new Asset(name, fileName, comment, Asset.countryImage);
asset.importDate = new Date();
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "images" + File.separator + fileName;
Helpers.copyfile(file.getAbsolutePath(), filePath);
asset.save();
return asset;
}
/**
*
* Handles upload of fix-image
* Binary file is copied and kept in the application-path
* Every picture has a number, this is calculated based on the file-name
* Asset with type Asset.imageType is created
*
*/
public static Asset uploadImage(String name, String comment, File file) {
String fileName = file.getName();
fileName = fileName.replaceFirst("_fax", "_").replaceFirst("_0+", "_");
Asset asset;
if (Asset.find("fileName = ?", fileName).first() != null) {
asset = Asset.find("fileName = ?", fileName).first();
asset.comment = comment;
asset.name = name;
asset.type = Asset.imageType;
} else {
asset = new Asset(name, fileName, comment, Asset.imageType);
}
asset.importDate = new Date();
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "images" + File.separator + fileName;
Helpers.copyfile(file.getAbsolutePath(), filePath);
String[] pictureNums = fileName.replace(".jpg", "").split("_");
int pictureNum = Integer.parseInt(pictureNums[pictureNums.length - 1]);
asset.pictureNumber = pictureNum;
asset.save();
return asset;
}
/**
* Keep a local version of the uploaded xml
* Might not be needed?
*
*/
private static String copyXmlToXmlDirectory(File epub) {
File newFile = new File(play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xml" + File.separator + epub.getName());
Helpers.copyfile(epub.getAbsolutePath(), newFile.getAbsolutePath());
return newFile.getAbsolutePath();
}
/**
*
* Handle upload of xml-file
* Calculate asset-type based on file-name
* Copy and keep xml-file
* Calculate and keep html based on the right xslt
*
* Note:
* variant = 0 means it is the original
*
*
*/
public static Asset uploadXmlFile(String name, String comment, File epub) {
int variant = 0;
String type;
System.out.println("Epub name: " + epub.getName());
if (epub.getName().equals("map_vej.xml")) {
type = Asset.mapVej;
} else if (epub.getName().startsWith("map_")) {
type = Asset.mapXml;
} else if (epub.getName().contains("_vej")) {
type = Asset.veiledningType;
} else if (epub.getName().equals("place.xml")) {
type = Asset.placeType;
} else if (epub.getName().equals("bible.xml")) {
type = Asset.bibleType;
} else if (epub.getName().equals("regList.xml")) {
type = Asset.registranten;
} else if (epub.getName().equals("pers.xml")) {
type = Asset.personType;
} else if (epub.getName().equals("myth.xml")) {
type = Asset.mythType;
} else if (epub.getName().replace(".xml", "").endsWith("_com")) {
type = Asset.commentType;
} else if (epub.getName().contains("intro")) {
type = Asset.introType;
} else if (epub.getName().contains("bookInventory")) {
type = Asset.bookinventory;
} else if (epub.getAbsolutePath().matches(".*_ms[1-9]*.xml")) {
System.out.println("Type is manustype!");
Pattern pattern = Pattern.compile("ms(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Manus number is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
}
type = Asset.manusType;
} else if (epub.getName().contains("txr")) {
type = Asset.txrType;
} else if (epub.getName().contains("varList")) {
System.out.println("Type is varList");
type = Asset.varListType;
} else {
Pattern pattern = Pattern.compile("v(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Variant is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
type = Asset.variantType;
} else {
System.out.println("No variant found");
type = Asset.rootType;
}
}
System.out.println("File: " + epub);
System.out.println("File-type: " + type);
String copiedFile = copyXmlToXmlDirectory(epub);
System.out.println("Copied file: " + copiedFile);
String html;
// consider a hash :-)
if (type.equals(Asset.mapVej) || type.equals(Asset.mapXml)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "vejXSLT.xsl");
} else if (type.equals(Asset.veiledningType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "veiledning.xsl"));
} else if (type.equals(Asset.placeType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "placeXSLT.xsl"));
} else if (type.equals(Asset.personType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "persXSLT.xsl");
} else if (type.equals(Asset.commentType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "comXSLT.xsl"));
} else if (type.equals(Asset.introType)) {
html = fixHtml(Asset.xmlToHtmlIntro(copiedFile));
} else if (type.equals(Asset.variantType)) {
html = fixHtml(Asset.xmlToHtmlVariant(copiedFile));
} else if (type.equals(Asset.rootType)) {
html = fixHtml(Asset.xmlToHtml(copiedFile));
} else if (type.equals(Asset.manusType)) {
html = Asset.xmlToHtmlManus(copiedFile);
} else if (type.equals(Asset.mythType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "mythXSLT.xsl");
} else if (type.equals(Asset.bibleType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "bibleXSLT.xsl");
} else if (type.equals(Asset.registranten)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "varListXSLT.xsl");
} else if (type.equals(Asset.txrType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "txrXSLT.xsl"));
} else if (type.equals(Asset.varListType)) {
html = Asset.xmlRefToHtml(copiedFile, "varListXSLT.xsl");
} else if (type.equals(Asset.bookinventory)) {
html = Asset.xmlRefToHtml(copiedFile, "bookInventoryXSLT.xsl");
} else {
html = "Not found: filetype unknown";
throw new Error("No recognized filetype found");
}
if (html.startsWith("Error")) {
throw new Error("Probably an error in xslt-stylesheet or xml: " + html);
}
// create or update asset
String xml = "";
try {
xml = Helpers.readFile(epub.getAbsolutePath());
} catch (IOException ex) {
Logger.getLogger(Asset.class.getName()).log(Level.SEVERE, null, ex);
}
// String refs = Helpers.getReferencesFromXml(xml, epub.getName().replaceFirst("", html));
String references = "";
Asset asset;
System.out.println("Filename: " + epub.getName());
if (Asset.find("filename", epub.getName()).fetch().size() > 0) {
System.out.println("--- Updating asset with name: " + epub.getName());
asset = Asset.find("filename", epub.getName()).first();
asset.name = name;
asset.html = html;
asset.comment = comment;
asset.variant = variant;
asset.importDate = new Date();
asset.type = type;
asset.refs = references;
asset.fileName = epub.getName();
asset.rootName = getRootName(epub.getName(), asset.type);
+ asset.xml = xml;
} else {
asset = new Asset(name, epub.getName(), html, xml, comment, variant, type, references);
}
asset.save();
System.out.println("Root-name: " + asset.rootName);
System.out.println("Asset is saved, total assets: " + Asset.findAll().size());
if (asset.type.equals(Asset.rootType)) {
Chapter.createChaptersFromAsset(asset);
}
return asset;
}
// remove headers so html can be shown in div
// consider fixing xslt later
private static String fixHtml(String html) {
// System.out.println("Fixing html - removing body");
// html = html.replaceFirst("(?s).*<body.*?>", "<div class='simple' id='top'>");
// System.out.println("Fixing html 2");
// html = html.replaceFirst("(?s)</body.*", "</div>");
// System.out.println("Fixing html 3");
html = html.replaceAll("<div class='[^']+'/>", "").replaceAll("<div class=\"[^\"]+\"/>", "");
System.out.println("Html if fixed :-)");
return html;
}
/**
* Get variants and manuses based on the root-asset
* @return List of variants, manuses and varLists connected to this asset
*
*/
public static List<Asset> getVariants(long assetId) {
Asset rootAsset = Asset.findById(assetId);
System.out.println("rootName: " + rootAsset.id);
List<Asset> variants = Asset.find("rootName = ? and (type = ? or type = ? or type = ?) order by type, variant", rootAsset.rootName, Asset.variantType, Asset.manusType, Asset.varListType).fetch();
return variants;
}
/**
* Get correspondig manus to an asset
* @return List of manuses
*/
public static List<Asset> getManus(long assetId) {
Asset rootAsset = Asset.findById(assetId);
List<Asset> manus = Asset.find("rootName = ? and type = ? ", rootAsset.rootName, "manus").fetch();
if (manus.isEmpty()) {
manus = Asset.find("rootName = ? and type = ? ", rootAsset.rootName.replaceFirst("_1", ""), "manus").fetch();
}
return manus;
}
/**
* Combine xml and xslt for ref-type assets
*/
public static String xmlRefToHtml(String fileName, String xsltPath) {
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + xsltPath;
return xmlToHtml(fileName, filePath);
}
/**
* Combine xml and xslt for myth-type assets
*/
public static String xmlToHtmlMyth(String fileName) {
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "mythXSLT.xsl";
return xmlToHtml(fileName, filePath);
}
/**
* Combine xml and xslt for manus-type assets
*/
public static String xmlToHtmlManus(String fileName) {
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "msXSLT.xsl";
return xmlToHtml(fileName, filePath);
}
/**
* Combine xml and xslt for intro-type assets
*/
public static String xmlToHtmlIntro(String fileName) {
System.out.println("Uploading introduction");
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "introXSLT.xsl";
return xmlToHtml(fileName, filePath);
}
/**
* Combine xml and xslt for var-type assets
*/
public static String xmlToHtmlVariant(String fileName) {
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "varXSLT.xsl";
return xmlToHtml(fileName, filePath);
}
/**
* Combine xml and xslt for root-type assets
*/
public static String xmlToHtml(String fileName) {
// String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "xhtml2" + File.separator + "tei.xsl";
String filePath = play.Play.applicationPath.getAbsolutePath() + File.separator + "public" + File.separator + "xslt" + File.separator + "txtXSLT.xsl";
return xmlToHtml(fileName, filePath);
}
/**
* Does the xslt-transformation of a xml-file and and a xslt-file
* @params fileName - name of xml-file
* @params fileName - name of xslt - file
*
*/
public static String xmlToHtml(String fileName, String filePath) {
System.out.println("User dir: " + System.getProperty("user.dir"));
try {
File xmlIn = new File(fileName);
StreamSource source = new StreamSource(xmlIn);
Processor proc = new Processor(false);
XsltCompiler comp = proc.newXsltCompiler();
System.out.println("Filepath: " + filePath);
XsltExecutable exp = comp.compile(new StreamSource(new File(filePath)));
Serializer out = new Serializer();
ByteArrayOutputStream buf = new ByteArrayOutputStream();
out.setOutputProperty(Serializer.Property.METHOD, "xhtml");
out.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
out.setOutputProperty(Serializer.Property.INDENT, "no");
out.setOutputProperty(Serializer.Property.ENCODING, "utf-8");
out.setOutputStream(buf);
// out.setOutputFile(new File("tour.html"));
XsltTransformer trans = exp.load();
// trans.setInitialTemplate(new QName("main"));
trans.setSource(source);
trans.setDestination(out);
trans.transform();
// System.out.println("Output generated: " + buf.toString());
return buf.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
return ("Error: " + e.toString());
}
}
public int getNumberOfPictures() {
System.out.println("**** Looking for rootName: " + rootName);
return Asset.find("rootName = ? and type = ?", rootName, Asset.imageType).fetch().size();
}
public String getFileNameWithoutXml() {
return this.rootName;
}
}
| true | true | public static Asset uploadXmlFile(String name, String comment, File epub) {
int variant = 0;
String type;
System.out.println("Epub name: " + epub.getName());
if (epub.getName().equals("map_vej.xml")) {
type = Asset.mapVej;
} else if (epub.getName().startsWith("map_")) {
type = Asset.mapXml;
} else if (epub.getName().contains("_vej")) {
type = Asset.veiledningType;
} else if (epub.getName().equals("place.xml")) {
type = Asset.placeType;
} else if (epub.getName().equals("bible.xml")) {
type = Asset.bibleType;
} else if (epub.getName().equals("regList.xml")) {
type = Asset.registranten;
} else if (epub.getName().equals("pers.xml")) {
type = Asset.personType;
} else if (epub.getName().equals("myth.xml")) {
type = Asset.mythType;
} else if (epub.getName().replace(".xml", "").endsWith("_com")) {
type = Asset.commentType;
} else if (epub.getName().contains("intro")) {
type = Asset.introType;
} else if (epub.getName().contains("bookInventory")) {
type = Asset.bookinventory;
} else if (epub.getAbsolutePath().matches(".*_ms[1-9]*.xml")) {
System.out.println("Type is manustype!");
Pattern pattern = Pattern.compile("ms(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Manus number is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
}
type = Asset.manusType;
} else if (epub.getName().contains("txr")) {
type = Asset.txrType;
} else if (epub.getName().contains("varList")) {
System.out.println("Type is varList");
type = Asset.varListType;
} else {
Pattern pattern = Pattern.compile("v(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Variant is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
type = Asset.variantType;
} else {
System.out.println("No variant found");
type = Asset.rootType;
}
}
System.out.println("File: " + epub);
System.out.println("File-type: " + type);
String copiedFile = copyXmlToXmlDirectory(epub);
System.out.println("Copied file: " + copiedFile);
String html;
// consider a hash :-)
if (type.equals(Asset.mapVej) || type.equals(Asset.mapXml)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "vejXSLT.xsl");
} else if (type.equals(Asset.veiledningType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "veiledning.xsl"));
} else if (type.equals(Asset.placeType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "placeXSLT.xsl"));
} else if (type.equals(Asset.personType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "persXSLT.xsl");
} else if (type.equals(Asset.commentType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "comXSLT.xsl"));
} else if (type.equals(Asset.introType)) {
html = fixHtml(Asset.xmlToHtmlIntro(copiedFile));
} else if (type.equals(Asset.variantType)) {
html = fixHtml(Asset.xmlToHtmlVariant(copiedFile));
} else if (type.equals(Asset.rootType)) {
html = fixHtml(Asset.xmlToHtml(copiedFile));
} else if (type.equals(Asset.manusType)) {
html = Asset.xmlToHtmlManus(copiedFile);
} else if (type.equals(Asset.mythType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "mythXSLT.xsl");
} else if (type.equals(Asset.bibleType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "bibleXSLT.xsl");
} else if (type.equals(Asset.registranten)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "varListXSLT.xsl");
} else if (type.equals(Asset.txrType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "txrXSLT.xsl"));
} else if (type.equals(Asset.varListType)) {
html = Asset.xmlRefToHtml(copiedFile, "varListXSLT.xsl");
} else if (type.equals(Asset.bookinventory)) {
html = Asset.xmlRefToHtml(copiedFile, "bookInventoryXSLT.xsl");
} else {
html = "Not found: filetype unknown";
throw new Error("No recognized filetype found");
}
if (html.startsWith("Error")) {
throw new Error("Probably an error in xslt-stylesheet or xml: " + html);
}
// create or update asset
String xml = "";
try {
xml = Helpers.readFile(epub.getAbsolutePath());
} catch (IOException ex) {
Logger.getLogger(Asset.class.getName()).log(Level.SEVERE, null, ex);
}
// String refs = Helpers.getReferencesFromXml(xml, epub.getName().replaceFirst("", html));
String references = "";
Asset asset;
System.out.println("Filename: " + epub.getName());
if (Asset.find("filename", epub.getName()).fetch().size() > 0) {
System.out.println("--- Updating asset with name: " + epub.getName());
asset = Asset.find("filename", epub.getName()).first();
asset.name = name;
asset.html = html;
asset.comment = comment;
asset.variant = variant;
asset.importDate = new Date();
asset.type = type;
asset.refs = references;
asset.fileName = epub.getName();
asset.rootName = getRootName(epub.getName(), asset.type);
} else {
asset = new Asset(name, epub.getName(), html, xml, comment, variant, type, references);
}
asset.save();
System.out.println("Root-name: " + asset.rootName);
System.out.println("Asset is saved, total assets: " + Asset.findAll().size());
if (asset.type.equals(Asset.rootType)) {
Chapter.createChaptersFromAsset(asset);
}
return asset;
}
| public static Asset uploadXmlFile(String name, String comment, File epub) {
int variant = 0;
String type;
System.out.println("Epub name: " + epub.getName());
if (epub.getName().equals("map_vej.xml")) {
type = Asset.mapVej;
} else if (epub.getName().startsWith("map_")) {
type = Asset.mapXml;
} else if (epub.getName().contains("_vej")) {
type = Asset.veiledningType;
} else if (epub.getName().equals("place.xml")) {
type = Asset.placeType;
} else if (epub.getName().equals("bible.xml")) {
type = Asset.bibleType;
} else if (epub.getName().equals("regList.xml")) {
type = Asset.registranten;
} else if (epub.getName().equals("pers.xml")) {
type = Asset.personType;
} else if (epub.getName().equals("myth.xml")) {
type = Asset.mythType;
} else if (epub.getName().replace(".xml", "").endsWith("_com")) {
type = Asset.commentType;
} else if (epub.getName().contains("intro")) {
type = Asset.introType;
} else if (epub.getName().contains("bookInventory")) {
type = Asset.bookinventory;
} else if (epub.getAbsolutePath().matches(".*_ms[1-9]*.xml")) {
System.out.println("Type is manustype!");
Pattern pattern = Pattern.compile("ms(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Manus number is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
}
type = Asset.manusType;
} else if (epub.getName().contains("txr")) {
type = Asset.txrType;
} else if (epub.getName().contains("varList")) {
System.out.println("Type is varList");
type = Asset.varListType;
} else {
Pattern pattern = Pattern.compile("v(\\d+)");
Matcher matcher = pattern.matcher(epub.getAbsolutePath());
String found = "no match";
if (matcher.find()) {
System.out.println("Variant is: " + matcher.group(1));
found = matcher.group(1);
variant = Integer.parseInt(found);
type = Asset.variantType;
} else {
System.out.println("No variant found");
type = Asset.rootType;
}
}
System.out.println("File: " + epub);
System.out.println("File-type: " + type);
String copiedFile = copyXmlToXmlDirectory(epub);
System.out.println("Copied file: " + copiedFile);
String html;
// consider a hash :-)
if (type.equals(Asset.mapVej) || type.equals(Asset.mapXml)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "vejXSLT.xsl");
} else if (type.equals(Asset.veiledningType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "veiledning.xsl"));
} else if (type.equals(Asset.placeType)) {
html = fixHtml(Asset.xmlRefToHtml(epub.getAbsolutePath(), "placeXSLT.xsl"));
} else if (type.equals(Asset.personType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "persXSLT.xsl");
} else if (type.equals(Asset.commentType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "comXSLT.xsl"));
} else if (type.equals(Asset.introType)) {
html = fixHtml(Asset.xmlToHtmlIntro(copiedFile));
} else if (type.equals(Asset.variantType)) {
html = fixHtml(Asset.xmlToHtmlVariant(copiedFile));
} else if (type.equals(Asset.rootType)) {
html = fixHtml(Asset.xmlToHtml(copiedFile));
} else if (type.equals(Asset.manusType)) {
html = Asset.xmlToHtmlManus(copiedFile);
} else if (type.equals(Asset.mythType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "mythXSLT.xsl");
} else if (type.equals(Asset.bibleType)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "bibleXSLT.xsl");
} else if (type.equals(Asset.registranten)) {
html = Asset.xmlRefToHtml(epub.getAbsolutePath(), "varListXSLT.xsl");
} else if (type.equals(Asset.txrType)) {
html = fixHtml(Asset.xmlRefToHtml(copiedFile, "txrXSLT.xsl"));
} else if (type.equals(Asset.varListType)) {
html = Asset.xmlRefToHtml(copiedFile, "varListXSLT.xsl");
} else if (type.equals(Asset.bookinventory)) {
html = Asset.xmlRefToHtml(copiedFile, "bookInventoryXSLT.xsl");
} else {
html = "Not found: filetype unknown";
throw new Error("No recognized filetype found");
}
if (html.startsWith("Error")) {
throw new Error("Probably an error in xslt-stylesheet or xml: " + html);
}
// create or update asset
String xml = "";
try {
xml = Helpers.readFile(epub.getAbsolutePath());
} catch (IOException ex) {
Logger.getLogger(Asset.class.getName()).log(Level.SEVERE, null, ex);
}
// String refs = Helpers.getReferencesFromXml(xml, epub.getName().replaceFirst("", html));
String references = "";
Asset asset;
System.out.println("Filename: " + epub.getName());
if (Asset.find("filename", epub.getName()).fetch().size() > 0) {
System.out.println("--- Updating asset with name: " + epub.getName());
asset = Asset.find("filename", epub.getName()).first();
asset.name = name;
asset.html = html;
asset.comment = comment;
asset.variant = variant;
asset.importDate = new Date();
asset.type = type;
asset.refs = references;
asset.fileName = epub.getName();
asset.rootName = getRootName(epub.getName(), asset.type);
asset.xml = xml;
} else {
asset = new Asset(name, epub.getName(), html, xml, comment, variant, type, references);
}
asset.save();
System.out.println("Root-name: " + asset.rootName);
System.out.println("Asset is saved, total assets: " + Asset.findAll().size());
if (asset.type.equals(Asset.rootType)) {
Chapter.createChaptersFromAsset(asset);
}
return asset;
}
|
diff --git a/JavaGL/src/arpong/logic/gameobjects/GameObject.java b/JavaGL/src/arpong/logic/gameobjects/GameObject.java
index 8df0c61..4118285 100644
--- a/JavaGL/src/arpong/logic/gameobjects/GameObject.java
+++ b/JavaGL/src/arpong/logic/gameobjects/GameObject.java
@@ -1,55 +1,55 @@
package arpong.logic.gameobjects;
import arpong.logic.primitives.BoundingBox;
import arpong.logic.primitives.Vector;
public class GameObject {
private BoundingBox boundingBox;
private Vector position;
private Vector velocity;
public BoundingBox getBoundingBox() {
return boundingBox;
}
public GameObject(BoundingBox box) {
this.boundingBox = box;
}
public Vector collidesWith(GameObject gameObject) {
// TODO: desperately need better collision point detection
BoundingBox bb = getBoundingBox();
Vector pos = getPosition();
BoundingBox shiftedBB = new BoundingBox(bb.getLowerLeft().plus(pos),
bb.getUpperRight().plus(pos));
BoundingBox objBB = gameObject.getBoundingBox();
- Vector objPos = getPosition();
+ Vector objPos = gameObject.getPosition();
BoundingBox shiftedObjBB = new BoundingBox(objBB.getLowerLeft().plus(objPos),
objBB.getUpperRight().plus(objPos));
if (shiftedBB.collidesWith(shiftedObjBB)) {
- return gameObject.getPosition();
+ return objPos;
}
return null;
}
public void setVelocity(Vector vector) {
this.velocity = vector;
}
public void setPosition(Vector position) {
this.position = position;
}
public Vector getVelocity() {
return velocity;
}
public Vector getPosition() {
return position;
}
public void move() {
setPosition(getPosition().plus(getVelocity()));
}
}
| false | true | public Vector collidesWith(GameObject gameObject) {
// TODO: desperately need better collision point detection
BoundingBox bb = getBoundingBox();
Vector pos = getPosition();
BoundingBox shiftedBB = new BoundingBox(bb.getLowerLeft().plus(pos),
bb.getUpperRight().plus(pos));
BoundingBox objBB = gameObject.getBoundingBox();
Vector objPos = getPosition();
BoundingBox shiftedObjBB = new BoundingBox(objBB.getLowerLeft().plus(objPos),
objBB.getUpperRight().plus(objPos));
if (shiftedBB.collidesWith(shiftedObjBB)) {
return gameObject.getPosition();
}
return null;
}
| public Vector collidesWith(GameObject gameObject) {
// TODO: desperately need better collision point detection
BoundingBox bb = getBoundingBox();
Vector pos = getPosition();
BoundingBox shiftedBB = new BoundingBox(bb.getLowerLeft().plus(pos),
bb.getUpperRight().plus(pos));
BoundingBox objBB = gameObject.getBoundingBox();
Vector objPos = gameObject.getPosition();
BoundingBox shiftedObjBB = new BoundingBox(objBB.getLowerLeft().plus(objPos),
objBB.getUpperRight().plus(objPos));
if (shiftedBB.collidesWith(shiftedObjBB)) {
return objPos;
}
return null;
}
|
diff --git a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesEntityListener.java b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesEntityListener.java
index 86e3bdd..f645d23 100644
--- a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesEntityListener.java
+++ b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesEntityListener.java
@@ -1,309 +1,315 @@
package com.mikeprimm.bukkit.AngryWolves;
import org.bukkit.entity.CreatureType;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.Material;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Random;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
/**
* Entity listener - listen for spawns of wolves
* @author MikePrimm
*/
public class AngryWolvesEntityListener extends EntityListener {
private final AngryWolves plugin;
private final Random rnd = new Random(System.currentTimeMillis());
private Map<String, Long> msg_ts_by_world = new HashMap<String, Long>();
private static final long SPAM_TIMER = 60000;
private static Set<Integer> hellhound_ids = new HashSet<Integer>();
private static Set<Integer> angrywolf_ids = new HashSet<Integer>();
private static final int HELLHOUND_FIRETICKS = 60*20; /* Do 60 seconds at a time */
public AngryWolvesEntityListener(final AngryWolves plugin) {
this.plugin = plugin;
}
private static class DoSpawn implements Runnable {
Location loc;
Player tgt;
boolean is_hellhound;
int health;
public void run() {
Wolf w = (Wolf)loc.getWorld().spawnCreature(loc, CreatureType.WOLF);
if(w != null) {
w.setAngry(true);
if(tgt != null)
w.setTarget(tgt);
if(is_hellhound) {
hellhound_ids.add(Integer.valueOf(w.getEntityId())); /* Add to table */
w.setFireTicks(HELLHOUND_FIRETICKS); /* Set it on fire */
w.setHealth(health);
}
angrywolf_ids.add(Integer.valueOf(w.getEntityId()));
}
}
}
private boolean checkLimit() {
return angrywolf_ids.size() < plugin.getPopulationLimit();
}
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getLocation();
boolean did_it = false;
CreatureType ct = event.getCreatureType();
+ if(ct == null)
+ return;
AngryWolves.BaseConfig cfg = null;
/* If monster spawn */
if(ct.equals(CreatureType.ZOMBIE) || ct.equals(CreatureType.CREEPER) ||
ct.equals(CreatureType.SPIDER) || ct.equals(CreatureType.SKELETON) ||
ct.equals(CreatureType.PIG_ZOMBIE)) {
/* Find configuration for our location */
cfg = plugin.findByLocation(loc);
//plugin.log.info("mob: " + cfg);
int rate = cfg.getMobToWolfRate(ct, plugin.isFullMoon(loc.getWorld()));
if(plugin.verbose) AngryWolves.log.info("mobrate(" + ct + ")=" + rate);
/* If so, percentage is relative to population of monsters (percent * 10% is chance we grab */
if((rate > 0) && (rnd.nextInt(1000) < rate) && checkLimit()) {
boolean ignore_terrain = cfg.getMobToWolfTerrainIgnore(); /* See if we're ignoring terrain */
Block b = loc.getBlock();
Biome bio = b.getBiome();
if(plugin.verbose) AngryWolves.log.info("biome=" + bio + ", ignore=" + ignore_terrain);
/* See if hellhound - only hellhounds substitute in Nether, use hellhound_rate elsewhere */
boolean do_hellhound = (bio.equals(Biome.HELL) || (rnd.nextInt(100) <= cfg.getHellhoundRate()));
/* If valid biome for wolf (or hellhound) */
if(ignore_terrain || bio.equals(Biome.FOREST) || bio.equals(Biome.TAIGA) || bio.equals(Biome.SEASONAL_FOREST) ||
bio.equals(Biome.HELL)) {
/* If hellhound in hell, we're good */
if(bio.equals(Biome.HELL)) {
}
else if(!ignore_terrain) {
while((b != null) && (b.getType().equals(Material.AIR))) {
b = b.getRelative(BlockFace.DOWN, 1);
}
/* Quit if we're not over soil */
if((b == null) || (!b.getType().equals(Material.GRASS))) {
if(plugin.verbose) AngryWolves.log.info("material=" + b.getType());
return;
}
}
event.setCancelled(true);
DoSpawn ds = new DoSpawn();
ds.loc = loc;
ds.is_hellhound = do_hellhound;
ds.health = do_hellhound?plugin.getHellhoundHealth():plugin.getAngryWolfHealth();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, ds);
did_it = true;
if(plugin.verbose) AngryWolves.log.info("Mapped " + ct + " spawn to angry wolf");
}
}
}
else if(ct.equals(CreatureType.WOLF)) {
Wolf w = (Wolf)event.getEntity();
/* If not angry and not tame */
if((w.isAngry() == false) && (plugin.isTame(w) == false) && (!plugin.isNormalSpawn())) {
cfg = plugin.findByLocation(loc);
//plugin.log.info("wolf: " + cfg);
int rate = cfg.getSpawnAngerRate();
int fmrate = cfg.getSpawnAngerRateMoon();
/* If higher rate during full moon, check if we're having one */
if((fmrate > rate) && plugin.isFullMoon(loc.getWorld())) {
rate = fmrate;
}
if((rate > 0) && (rnd.nextInt(100) <= rate) && checkLimit()) {
w.setAngry(true);
/* See if it is a hellhound! */
rate = cfg.getHellhoundRate();
if((rate > 0) && (rnd.nextInt(100) <= rate)) {
hellhound_ids.add(w.getEntityId());
w.setFireTicks(HELLHOUND_FIRETICKS);
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf into a hellhound");
+ w.setTamed(true); /* Get around health limit on untamed wolves */
w.setHealth(plugin.getHellhoundHealth());
+ w.setTamed(false);
}
else {
+ w.setTamed(true); /* Get around health limit on untamed wolves */
w.setHealth(plugin.getAngryWolfHealth());
+ w.setTamed(false);
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf angry");
}
did_it = true;
}
}
}
if(did_it) {
/* And get our spawn message */
String sm = cfg.getSpawnMsg();
double radius = (double)cfg.getSpawnMsgRadius();
if((sm != null) && (sm.length() > 0)) {
/* See if too soon (avoid spamming these messages) */
Long last = msg_ts_by_world.get(loc.getWorld().getName());
if((last == null) || ((last.longValue() + SPAM_TIMER) < System.currentTimeMillis())) {
msg_ts_by_world.put(loc.getWorld().getName(), Long.valueOf(System.currentTimeMillis()));
List<Player> pl = loc.getWorld().getPlayers();
for(Player p : pl) {
if(radius > 0.0) { /* If radius limit, see if player is close enough */
Location ploc = p.getLocation();
double dx = ploc.getX() - loc.getX();
double dy = ploc.getY() - loc.getY();
double dz = ploc.getZ() - loc.getZ();
if(((dx*dx) + (dy*dy) + (dz*dz)) <= (radius*radius)) {
p.sendMessage(sm);
}
}
else
p.sendMessage(sm);
}
}
}
}
}
@Override
public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled())
return;
Entity e = event.getEntity();
/* If fire damage, see if it is a hellhound */
if(isHellHound(e)) {
e.setFireTicks(HELLHOUND_FIRETICKS);
DamageCause dc = event.getCause();
if((dc == DamageCause.FIRE_TICK) || (dc == DamageCause.FIRE) || (dc == DamageCause.LAVA)) {
event.setCancelled(true); /* Cancel it - we're fireproof! */
return;
}
else if (plugin.getHellhoundDamageScale() != 1.0) {
int dmg = (int)Math.round(plugin.getHellhoundDamageScale() * (double)event.getDamage());
if(dmg != event.getDamage()) {
event.setDamage(dmg);
}
}
}
if(!(event instanceof EntityDamageByEntityEvent))
return;
EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent)event;
Entity damager = evt.getDamager();
if(damager instanceof Player) {
Player p = (Player)damager;
/* See if its a sheep */
if(!(e instanceof Sheep))
return;
Sheep s = (Sheep)e;
Location loc = s.getLocation();
AngryWolves.BaseConfig cfg = plugin.findByLocation(loc);
//plugin.log.info("sheep: " + cfg);
int rate = cfg.getWolfInSheepRate();
/* Use hashcode - random enough, and makes it so that something damaged
* once will trigger, or never will, even if damaged again */
if(new Random(e.hashCode()).nextInt(1000) >= rate)
return;
String msg = cfg.getWolfInSheepMsg();
if((msg != null) && (msg.length() > 0))
p.sendMessage(cfg.getWolfInSheepMsg());
evt.setCancelled(true); /* Cancel event */
e.remove(); /* Remove the sheep */
DoSpawn ds = new DoSpawn();
ds.loc = loc;
ds.tgt = p;
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, ds);
if(plugin.verbose) AngryWolves.log.info("Made attacked sheep into angry wolf");
}
else if(damager instanceof Wolf) {
if(!(e instanceof Player)) { /* Not a player - don't worry */
return;
}
/* If we don't do wolf-friends here, skip it (check based on player's location) */
AngryWolves.BaseConfig cfg = plugin.findByLocation(e.getLocation());
//plugin.log.info("wolffriend: " + cfg);
if(cfg.getWolfFriendActive() == false) {
return;
}
if(AngryWolvesPermissions.permission((Player)e, AngryWolves.WOLF_FRIEND_PERM)) {
event.setCancelled(true); /* Cancel it */
((Wolf)damager).setTarget(null); /* Target someone else */
if(plugin.verbose) AngryWolves.log.info("Cancelled attack on wolf-friend");
}
}
}
@Override
public void onEntityTarget(EntityTargetEvent event) {
if(event.isCancelled())
return;
Entity e = event.getEntity();
if(!(e instanceof Wolf)) /* Don't care about non-wolves */
return;
if(hellhound_ids.contains(e.getEntityId()))
e.setFireTicks(HELLHOUND_FIRETICKS);
Entity t = event.getTarget();
if(!(t instanceof Player)) /* Don't worry about non-player targets */
return;
Player p = (Player)t;
/* If we don't do wolf-friends here, skip it (check based on player's location) */
AngryWolves.BaseConfig cfg = plugin.findByLocation(p.getLocation());
if(cfg.getWolfFriendActive() == false) {
return;
}
if(AngryWolvesPermissions.permission(p, AngryWolves.WOLF_FRIEND_PERM)) { /* If player is a wolf-friend */
event.setCancelled(true); /* Cancel it - not a valid target */
if(plugin.verbose) AngryWolves.log.info("Cancelled target on wolf friend");
}
}
@Override
public void onEntityDeath(EntityDeathEvent event) {
Entity e = event.getEntity();
if(!(e instanceof Wolf)) /* Don't care about non-wolves */
return;
Wolf w = (Wolf)e;
/* Forget the dead hellhound */
boolean was_hellhound = hellhound_ids.remove(e.getEntityId());
angrywolf_ids.remove(e.getEntityId());
/* Check for loot */
AngryWolves.BaseConfig cfg = plugin.findByLocation(e.getLocation()); /* Get our configuration for location */
boolean drop_loot = false;
if(was_hellhound && (cfg.getHellHoundLootRate() >= 0)) {
drop_loot = cfg.getHellHoundLootRate() > rnd.nextInt(100);
}
else if(w.isAngry() && (cfg.getAngryWolfLootRate() >= 0)) {
drop_loot = cfg.getAngryWolfLootRate() > rnd.nextInt(100);
}
else {
drop_loot = cfg.getWolfLootRate() > rnd.nextInt(100);
}
if(drop_loot) {
List<Integer> loot;
if(was_hellhound && (cfg.getHellHoundLoot() != null))
loot = cfg.getHellHoundLoot();
else if(w.isAngry() && (cfg.getAngryWolfLoot() != null))
loot = cfg.getAngryWolfLoot();
else
loot = cfg.getWolfLoot();
int sz = loot.size();
if(sz > 0) {
int id = loot.get(rnd.nextInt(sz));
e.getWorld().dropItemNaturally(e.getLocation(), new ItemStack(id, 1));
}
}
}
public static final boolean isHellHound(Entity e) {
return hellhound_ids.contains(e.getEntityId());
}
}
| false | true | public void onCreatureSpawn(CreatureSpawnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getLocation();
boolean did_it = false;
CreatureType ct = event.getCreatureType();
AngryWolves.BaseConfig cfg = null;
/* If monster spawn */
if(ct.equals(CreatureType.ZOMBIE) || ct.equals(CreatureType.CREEPER) ||
ct.equals(CreatureType.SPIDER) || ct.equals(CreatureType.SKELETON) ||
ct.equals(CreatureType.PIG_ZOMBIE)) {
/* Find configuration for our location */
cfg = plugin.findByLocation(loc);
//plugin.log.info("mob: " + cfg);
int rate = cfg.getMobToWolfRate(ct, plugin.isFullMoon(loc.getWorld()));
if(plugin.verbose) AngryWolves.log.info("mobrate(" + ct + ")=" + rate);
/* If so, percentage is relative to population of monsters (percent * 10% is chance we grab */
if((rate > 0) && (rnd.nextInt(1000) < rate) && checkLimit()) {
boolean ignore_terrain = cfg.getMobToWolfTerrainIgnore(); /* See if we're ignoring terrain */
Block b = loc.getBlock();
Biome bio = b.getBiome();
if(plugin.verbose) AngryWolves.log.info("biome=" + bio + ", ignore=" + ignore_terrain);
/* See if hellhound - only hellhounds substitute in Nether, use hellhound_rate elsewhere */
boolean do_hellhound = (bio.equals(Biome.HELL) || (rnd.nextInt(100) <= cfg.getHellhoundRate()));
/* If valid biome for wolf (or hellhound) */
if(ignore_terrain || bio.equals(Biome.FOREST) || bio.equals(Biome.TAIGA) || bio.equals(Biome.SEASONAL_FOREST) ||
bio.equals(Biome.HELL)) {
/* If hellhound in hell, we're good */
if(bio.equals(Biome.HELL)) {
}
else if(!ignore_terrain) {
while((b != null) && (b.getType().equals(Material.AIR))) {
b = b.getRelative(BlockFace.DOWN, 1);
}
/* Quit if we're not over soil */
if((b == null) || (!b.getType().equals(Material.GRASS))) {
if(plugin.verbose) AngryWolves.log.info("material=" + b.getType());
return;
}
}
event.setCancelled(true);
DoSpawn ds = new DoSpawn();
ds.loc = loc;
ds.is_hellhound = do_hellhound;
ds.health = do_hellhound?plugin.getHellhoundHealth():plugin.getAngryWolfHealth();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, ds);
did_it = true;
if(plugin.verbose) AngryWolves.log.info("Mapped " + ct + " spawn to angry wolf");
}
}
}
else if(ct.equals(CreatureType.WOLF)) {
Wolf w = (Wolf)event.getEntity();
/* If not angry and not tame */
if((w.isAngry() == false) && (plugin.isTame(w) == false) && (!plugin.isNormalSpawn())) {
cfg = plugin.findByLocation(loc);
//plugin.log.info("wolf: " + cfg);
int rate = cfg.getSpawnAngerRate();
int fmrate = cfg.getSpawnAngerRateMoon();
/* If higher rate during full moon, check if we're having one */
if((fmrate > rate) && plugin.isFullMoon(loc.getWorld())) {
rate = fmrate;
}
if((rate > 0) && (rnd.nextInt(100) <= rate) && checkLimit()) {
w.setAngry(true);
/* See if it is a hellhound! */
rate = cfg.getHellhoundRate();
if((rate > 0) && (rnd.nextInt(100) <= rate)) {
hellhound_ids.add(w.getEntityId());
w.setFireTicks(HELLHOUND_FIRETICKS);
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf into a hellhound");
w.setHealth(plugin.getHellhoundHealth());
}
else {
w.setHealth(plugin.getAngryWolfHealth());
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf angry");
}
did_it = true;
}
}
}
if(did_it) {
/* And get our spawn message */
String sm = cfg.getSpawnMsg();
double radius = (double)cfg.getSpawnMsgRadius();
if((sm != null) && (sm.length() > 0)) {
/* See if too soon (avoid spamming these messages) */
Long last = msg_ts_by_world.get(loc.getWorld().getName());
if((last == null) || ((last.longValue() + SPAM_TIMER) < System.currentTimeMillis())) {
msg_ts_by_world.put(loc.getWorld().getName(), Long.valueOf(System.currentTimeMillis()));
List<Player> pl = loc.getWorld().getPlayers();
for(Player p : pl) {
if(radius > 0.0) { /* If radius limit, see if player is close enough */
Location ploc = p.getLocation();
double dx = ploc.getX() - loc.getX();
double dy = ploc.getY() - loc.getY();
double dz = ploc.getZ() - loc.getZ();
if(((dx*dx) + (dy*dy) + (dz*dz)) <= (radius*radius)) {
p.sendMessage(sm);
}
}
else
p.sendMessage(sm);
}
}
}
}
}
| public void onCreatureSpawn(CreatureSpawnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getLocation();
boolean did_it = false;
CreatureType ct = event.getCreatureType();
if(ct == null)
return;
AngryWolves.BaseConfig cfg = null;
/* If monster spawn */
if(ct.equals(CreatureType.ZOMBIE) || ct.equals(CreatureType.CREEPER) ||
ct.equals(CreatureType.SPIDER) || ct.equals(CreatureType.SKELETON) ||
ct.equals(CreatureType.PIG_ZOMBIE)) {
/* Find configuration for our location */
cfg = plugin.findByLocation(loc);
//plugin.log.info("mob: " + cfg);
int rate = cfg.getMobToWolfRate(ct, plugin.isFullMoon(loc.getWorld()));
if(plugin.verbose) AngryWolves.log.info("mobrate(" + ct + ")=" + rate);
/* If so, percentage is relative to population of monsters (percent * 10% is chance we grab */
if((rate > 0) && (rnd.nextInt(1000) < rate) && checkLimit()) {
boolean ignore_terrain = cfg.getMobToWolfTerrainIgnore(); /* See if we're ignoring terrain */
Block b = loc.getBlock();
Biome bio = b.getBiome();
if(plugin.verbose) AngryWolves.log.info("biome=" + bio + ", ignore=" + ignore_terrain);
/* See if hellhound - only hellhounds substitute in Nether, use hellhound_rate elsewhere */
boolean do_hellhound = (bio.equals(Biome.HELL) || (rnd.nextInt(100) <= cfg.getHellhoundRate()));
/* If valid biome for wolf (or hellhound) */
if(ignore_terrain || bio.equals(Biome.FOREST) || bio.equals(Biome.TAIGA) || bio.equals(Biome.SEASONAL_FOREST) ||
bio.equals(Biome.HELL)) {
/* If hellhound in hell, we're good */
if(bio.equals(Biome.HELL)) {
}
else if(!ignore_terrain) {
while((b != null) && (b.getType().equals(Material.AIR))) {
b = b.getRelative(BlockFace.DOWN, 1);
}
/* Quit if we're not over soil */
if((b == null) || (!b.getType().equals(Material.GRASS))) {
if(plugin.verbose) AngryWolves.log.info("material=" + b.getType());
return;
}
}
event.setCancelled(true);
DoSpawn ds = new DoSpawn();
ds.loc = loc;
ds.is_hellhound = do_hellhound;
ds.health = do_hellhound?plugin.getHellhoundHealth():plugin.getAngryWolfHealth();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, ds);
did_it = true;
if(plugin.verbose) AngryWolves.log.info("Mapped " + ct + " spawn to angry wolf");
}
}
}
else if(ct.equals(CreatureType.WOLF)) {
Wolf w = (Wolf)event.getEntity();
/* If not angry and not tame */
if((w.isAngry() == false) && (plugin.isTame(w) == false) && (!plugin.isNormalSpawn())) {
cfg = plugin.findByLocation(loc);
//plugin.log.info("wolf: " + cfg);
int rate = cfg.getSpawnAngerRate();
int fmrate = cfg.getSpawnAngerRateMoon();
/* If higher rate during full moon, check if we're having one */
if((fmrate > rate) && plugin.isFullMoon(loc.getWorld())) {
rate = fmrate;
}
if((rate > 0) && (rnd.nextInt(100) <= rate) && checkLimit()) {
w.setAngry(true);
/* See if it is a hellhound! */
rate = cfg.getHellhoundRate();
if((rate > 0) && (rnd.nextInt(100) <= rate)) {
hellhound_ids.add(w.getEntityId());
w.setFireTicks(HELLHOUND_FIRETICKS);
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf into a hellhound");
w.setTamed(true); /* Get around health limit on untamed wolves */
w.setHealth(plugin.getHellhoundHealth());
w.setTamed(false);
}
else {
w.setTamed(true); /* Get around health limit on untamed wolves */
w.setHealth(plugin.getAngryWolfHealth());
w.setTamed(false);
if(plugin.verbose) AngryWolves.log.info("Made a spawned wolf angry");
}
did_it = true;
}
}
}
if(did_it) {
/* And get our spawn message */
String sm = cfg.getSpawnMsg();
double radius = (double)cfg.getSpawnMsgRadius();
if((sm != null) && (sm.length() > 0)) {
/* See if too soon (avoid spamming these messages) */
Long last = msg_ts_by_world.get(loc.getWorld().getName());
if((last == null) || ((last.longValue() + SPAM_TIMER) < System.currentTimeMillis())) {
msg_ts_by_world.put(loc.getWorld().getName(), Long.valueOf(System.currentTimeMillis()));
List<Player> pl = loc.getWorld().getPlayers();
for(Player p : pl) {
if(radius > 0.0) { /* If radius limit, see if player is close enough */
Location ploc = p.getLocation();
double dx = ploc.getX() - loc.getX();
double dy = ploc.getY() - loc.getY();
double dz = ploc.getZ() - loc.getZ();
if(((dx*dx) + (dy*dy) + (dz*dz)) <= (radius*radius)) {
p.sendMessage(sm);
}
}
else
p.sendMessage(sm);
}
}
}
}
}
|
diff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.java
index f50b2a082..2488fe54b 100644
--- a/source/de/anomic/yacy/yacySeedDB.java
+++ b/source/de/anomic/yacy/yacySeedDB.java
@@ -1,680 +1,680 @@
// yacySeedDB.java
// -------------------------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 22.02.2005
//
// 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 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
package de.anomic.yacy;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import de.anomic.http.httpc;
import de.anomic.kelondro.kelondroDyn;
import de.anomic.kelondro.kelondroException;
import de.anomic.kelondro.kelondroMScoreCluster;
import de.anomic.kelondro.kelondroMap;
import de.anomic.net.ftpc;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
import de.anomic.server.serverSwitch;
import de.anomic.tools.disorderHeap;
public class yacySeedDB {
// global statics
public static final int commonHashLength = 12;
// this is the lenght of the hash key that is used:
// - for seed hashes (this Object)
// - for word hashes (plasmaIndexEntry.wordHashLength)
// - for L-URL hashes (plasmaLURL.urlHashLength)
// these hashes all shall be generated by base64.enhancedCoder
public static final String[] sortFields = new String[] {"LCount", "ICount", "Uptime", "Version", "LastSeen"};
public static final String[] accFields = new String[] {"LCount", "ICount"};
// class objects
private File seedActiveDBFile, seedPassiveDBFile, seedPotentialDBFile;
private disorderHeap seedQueue;
private kelondroMap seedActiveDB, seedPassiveDB, seedPotentialDB;
private int seedDBBufferKB;
public plasmaSwitchboard sb;
public yacySeed mySeed; // my own seed
public File myOwnSeedFile;
private Hashtable nameLookupCache;
public yacySeedDB(plasmaSwitchboard sb,
File seedActiveDBFile,
File seedPassiveDBFile,
File seedPotentialDBFile,
int bufferkb) throws IOException {
this.seedActiveDBFile = seedActiveDBFile;
this.seedPassiveDBFile = seedPassiveDBFile;
this.seedPotentialDBFile = seedPotentialDBFile;
this.mySeed = null; // my own seed
this.sb = sb;
// set up seed database
seedActiveDB = openSeedTable(seedActiveDBFile);
seedPassiveDB = openSeedTable(seedPassiveDBFile);
seedPotentialDB = openSeedTable(seedPotentialDBFile);
// create or init own seed
myOwnSeedFile = new File(sb.getRootPath(), sb.getConfig("yacyOwnSeedFile", "mySeed.txt"));
- if (myOwnSeedFile.exists()) {
+ if (myOwnSeedFile.exists() && (myOwnSeedFile.length() > 0)) {
// load existing identity
mySeed = yacySeed.load(myOwnSeedFile);
} else {
// create new identity
mySeed = yacySeed.genLocalSeed(sb);
// save of for later use
mySeed.save(myOwnSeedFile); // in a file
//writeMap(mySeed.hash, mySeed.dna, "new"); // in a database
}
mySeed.put("IP", ""); // we delete the old information to see what we have now
mySeed.put("Port", sb.getConfig("port", "8080")); // set my seed's correct port number
mySeed.put("PeerType", "virgin"); // markup startup condition
// start our virtual DNS service for yacy peers with empty cache
nameLookupCache = new Hashtable();
// check if we are in the seedCaches: this can happen if someone else published our seed
removeMySeed();
// set up seed queue (for probing candidates)
seedQueue = null;
}
public synchronized void removeMySeed() {
try {
seedActiveDB.remove(mySeed.hash);
seedPassiveDB.remove(mySeed.hash);
seedPotentialDB.remove(mySeed.hash);
} catch (IOException e) {}
}
private synchronized kelondroMap openSeedTable(File seedDBFile) throws IOException {
if (seedDBFile.exists()) {
// open existing seed database
return new kelondroMap(new kelondroDyn(seedDBFile, seedDBBufferKB * 0x400), sortFields, accFields);
} else {
// create new seed database
new File(seedDBFile.getParent()).mkdir();
return new kelondroMap(new kelondroDyn(seedDBFile, seedDBBufferKB * 0x400, commonHashLength, 480), sortFields, accFields);
}
}
private synchronized kelondroMap resetSeedTable(kelondroMap seedDB, File seedDBFile) {
// this is an emergency function that should only be used if any problem with the
// seed.db is detected
yacyCore.log.logDebug("seed-db " + seedDBFile.toString() + " reset (on-the-fly)");
try {
seedDB.close();
seedDBFile.delete();
// create new seed database
seedDB = openSeedTable(seedDBFile);
} catch (IOException e) {
e.printStackTrace();
}
return seedDB;
}
public synchronized void resetActiveTable() { seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile); }
public synchronized void resetPassiveTable() { seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile); }
public synchronized void resetPotentialTable() { seedPotentialDB = resetSeedTable(seedPotentialDB, seedPotentialDBFile); }
public void close() {
try {
seedActiveDB.close();
seedPassiveDB.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Enumeration seedsSortedConnected(boolean up, String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedActiveDB);
}
public Enumeration seedsSortedDisconnected(boolean up, String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedPassiveDB);
}
public Enumeration seedsSortedPotential(boolean up, String field) {
// enumerates seed-type objects: all seeds sequentially ordered by field
return new seedEnum(up, field, seedPotentialDB);
}
public Enumeration seedsConnected(boolean up, boolean rot, String firstHash) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), seedActiveDB);
}
public Enumeration seedsDisconnected(boolean up, boolean rot, String firstHash) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), seedPassiveDB);
}
public Enumeration seedsPotential(boolean up, boolean rot, String firstHash) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash.getBytes(), seedPotentialDB);
}
public yacySeed anySeed() {
// return just any probe candidate
yacySeed seed;
if ((seedQueue == null) || (seedQueue.size() == 0)) {
if (seedActiveDB.size() <= 0) return null;
// fill up the queue
seedQueue = new disorderHeap();
Iterator keyIt;
try {
keyIt = seedActiveDB.keys(true, false); // iteration of String - Objects
} catch (IOException e) {
yacyCore.log.logError("yacySeedCache.anySeed: seed.db not available: " + e.getMessage());
keyIt = (new HashSet()).iterator();
}
String seedHash;
String myIP = (mySeed == null) ? "" : ((String) mySeed.get("IP", "127.0.0.1"));
while (keyIt.hasNext()) {
seedHash = (String) keyIt.next();
try {
seed = new yacySeed(seedHash, seedActiveDB.get(seedHash));
// check here if the seed is equal to the own seed
// this should never be the case, but it happens if a redistribution circle exists
if ((mySeed != null) && (seedHash.equals(mySeed.hash))) {
// this seed should not be in the database
seedActiveDB.remove(seedHash);
} else {
// add to queue
seedQueue.add(seed);
}
} catch (IOException e) {}
}
// the queue is filled up!
}
if ((seedQueue == null) || (seedQueue.size() == 0)) return null;
return (yacySeed) seedQueue.remove();
}
public yacySeed anySeedType(String type) {
// this returns any seed that has a special PeerType
yacySeed ys;
String t;
for (int i = 0; i < seedActiveDB.size(); i++) {
ys = anySeed();
if (ys == null) return null;
t = (String) ys.get("PeerType", "");
if ((t != null) && (t.equals(type))) return ys;
}
return null;
}
public yacySeed[] seedsByAge(boolean up, int count) {
if (count > sizeConnected()) count = sizeConnected();
// fill a score object
kelondroMScoreCluster seedScore = new kelondroMScoreCluster();
yacySeed ys;
String t;
long absage;
Enumeration s = seedsConnected(true, false, null);
int searchcount = 1000;
if (searchcount > sizeConnected()) searchcount = sizeConnected();
try {
while ((s.hasMoreElements()) && (searchcount-- > 0)) {
ys = (yacySeed) s.nextElement();
if ((ys != null) && ((t = ys.get("LastSeen", "")).length() > 10)) try {
absage = Math.abs(yacyCore.universalTime() - yacyCore.shortFormatter.parse(t).getTime());
seedScore.addScore(ys.hash, (int) absage);
} catch (Exception e) {}
}
// result is now in the score object; create a result vector
yacySeed[] result = new yacySeed[count];
Iterator it = seedScore.scores(up);
int c = 0;
while ((c < count) && (it.hasNext())) result[c++] = getConnected((String) it.next());
return result;
} catch (kelondroException e) {
seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
System.out.println("Internal Error at yacySeedDB.seedsByAge: " + e.getMessage());
e.printStackTrace();
return null;
}
}
public int sizeConnected() {
return seedActiveDB.size();
/*
Enumeration e = seedsConnected(true, false, null);
int c = 0; while (e.hasMoreElements()) {c++; e.nextElement();}
return c;
*/
}
public int sizeDisconnected() {
return seedPassiveDB.size();
/*
Enumeration e = seedsDisconnected(true, false, null);
int c = 0; while (e.hasMoreElements()) {c++; e.nextElement();}
return c;
*/
}
public int sizePotential() {
return seedPotentialDB.size();
/*
Enumeration e = seedsPotential(true, false, null);
int c = 0; while (e.hasMoreElements()) {c++; e.nextElement();}
return c;
*/
}
public long countActiveURL() { return seedActiveDB.getAcc("LCount"); }
public long countActiveRWI() { return seedActiveDB.getAcc("ICount"); }
public long countPassiveURL() { return seedPassiveDB.getAcc("LCount"); }
public long countPassiveRWI() { return seedPassiveDB.getAcc("ICount"); }
public long countPotentialURL() { return seedPotentialDB.getAcc("LCount"); }
public long countPotentialRWI() { return seedPotentialDB.getAcc("ICount"); }
public void addConnected(yacySeed seed) {
if ((seed == null) || (!(seed.isProper()))) return;
//seed.put("LastSeen", yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
nameLookupCache.put(seed.getName(), seed);
seedActiveDB.set(seed.hash, seed.getMap());
seedPassiveDB.remove(seed.hash);
seedPotentialDB.remove(seed.hash);
} catch (IOException e){
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
} catch (kelondroException e){
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
} catch (IllegalArgumentException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
}
}
public void addDisconnected(yacySeed seed) {
if (seed == null) return;
try {
nameLookupCache.remove(seed.getName());
seedActiveDB.remove(seed.hash);
seedPotentialDB.remove(seed.hash);
} catch (Exception e) {}
//seed.put("LastSeen", yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
seedPassiveDB.set(seed.hash, seed.getMap());
} catch (IOException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
} catch (kelondroException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
} catch (IllegalArgumentException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
}
}
public void addPotential(yacySeed seed) {
if (seed == null) return;
try {
nameLookupCache.remove(seed.getName());
seedActiveDB.remove(seed.hash);
seedPassiveDB.remove(seed.hash);
} catch (Exception e) {}
if (!(seed.isProper())) return;
//seed.put("LastSeen", yacyCore.shortFormatter.format(new Date(yacyCore.universalTime())));
try {
seedPotentialDB.set(seed.hash, seed.getMap());
} catch (IOException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
} catch (kelondroException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
} catch (IllegalArgumentException e) {
System.out.println("ERROR add: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
}
}
public boolean hasConnected(String hash) {
try {
return (seedActiveDB.get(hash) != null);
} catch (IOException e) {
return false;
}
}
public boolean hasDisconnected(String hash) {
try {
return (seedPassiveDB.get(hash) != null);
} catch (IOException e) {
return false;
}
}
public boolean hasPotential(String hash) {
try {
return (seedPotentialDB.get(hash) != null);
} catch (IOException e) {
return false;
}
}
private yacySeed get(String hash, kelondroMap database) {
if (hash == null) return null;
if ((mySeed != null) && (hash.equals(mySeed.hash))) return mySeed;
try {
Map entry = database.get(hash);
if (entry == null) return null;
return new yacySeed(hash, entry);
} catch (IOException e) {
return null;
}
}
public yacySeed getConnected(String hash) {
return get(hash, seedActiveDB);
}
public yacySeed getDisconnected(String hash) {
return get(hash, seedPassiveDB);
}
public yacySeed lookupByName(String peerName) {
// reads a seed by searching by name
// local peer?
if (peerName.equals("localpeer")) return mySeed;
// then try to use the cache
yacySeed seed = (yacySeed) nameLookupCache.get(peerName);
if (seed != null) return seed;
// enumerate the cache and simultanous insert values
Enumeration e = seedsConnected(true, false, null);
String name;
while (e.hasMoreElements()) {
seed = (yacySeed) e.nextElement();
if (seed != null) {
name = seed.getName().toLowerCase();
if (seed.isProper()) nameLookupCache.put(name, seed);
if (name.equals(peerName)) return seed;
}
}
// check local seed
name = mySeed.getName().toLowerCase();
if (mySeed.isProper()) nameLookupCache.put(name, mySeed);
if (name.equals(peerName)) return mySeed;
// nothing found
return null;
}
public Vector storeCache(File seedFile) throws IOException {
return storeCache(seedFile, false);
}
private Vector storeCache(File seedFile, boolean addMySeed) throws IOException {
PrintWriter pw = null;
Vector v = new Vector(seedActiveDB.size()+1);
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(seedFile)));
// store own seed
String line;
if ((addMySeed) && (mySeed != null)) {
line = mySeed.genSeedStr(null);
v.add(line);
pw.print(line + serverCore.crlfString);
}
// store other seeds
yacySeed ys;
for (int i = 0; i < seedActiveDB.size(); i++) {
ys = anySeed();
if (ys != null) {
line = ys.genSeedStr(null);
v.add(line);
pw.print(line + serverCore.crlfString);
}
}
pw.flush();
} finally {
if (pw != null) try { pw.close(); } catch (Exception e) {}
}
return v;
}
public String uploadCache(yacySeedUploader uploader,
serverSwitch sb,
yacySeedDB seedDB,
// String seedFTPServer,
// String seedFTPAccount,
// String seedFTPPassword,
// File seedFTPPath,
URL seedURL) throws Exception {
// upload a seed file, if possible
if (seedURL == null) throw new NullPointerException("UPLOAD - Error: URL not given");
String log = null;
File seedFile = null;
try {
// create a seed file which for uploading ...
seedFile = new File("seedFile.txt");
Vector uv = storeCache(seedFile, true);
// uploading the seed file
log = uploader.uploadSeedFile(sb,seedDB,seedFile);
// check also if the result can be retrieved again
if (checkCache(uv, seedURL))
log = log + "UPLOAD CHECK - Success: the result vectors are equal" + serverCore.crlfString;
else {
throw new Exception("UPLOAD CHECK - Error: the result vector is different" + serverCore.crlfString);
}
} finally {
if (seedFile != null) seedFile.delete();
}
return log;
}
public String copyCache(File seedFile, URL seedURL) throws IOException {
if (seedURL == null) return "COPY - Error: URL not given";
Vector uv = storeCache(seedFile, true);
try {
// check also if the result can be retrieved again
if (checkCache(uv, seedURL))
return "COPY CHECK - Success: the result vectors are equal" + serverCore.crlfString;
else
return "COPY CHECK - Error: the result vector is different" + serverCore.crlfString;
} catch (IOException e) {
return "COPY CHECK - Error: IO problem " + e.getMessage() + serverCore.crlfString;
}
}
private boolean checkCache(Vector uv, URL seedURL) throws IOException {
// check if the result can be retrieved again
Vector check = httpc.wget(seedURL, 10000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
if ((check == null) || (uv == null) || (uv.size() != check.size())) {
return false;
} else {
int i;
for (i = 0; i < uv.size(); i++) {
if (!(((String) uv.elementAt(i)).equals((String) check.elementAt(i)))) return false;
}
if (i == uv.size()) return true;
}
return false;
}
public String resolveYacyAddress(String host) {
yacySeed seed;
int p;
String subdom = null;
if (host.endsWith(".yacyh")) {
// this is not functional at the moment
// caused by lowecasing of hashes at the browser client
p = host.indexOf(".");
if ((p > 0) && (p != (host.length() - 6))) {
subdom = host.substring(0, p);
host = host.substring(p + 1);
}
// check remote seeds
seed = getConnected(host.substring(0, host.length() - 6)); // checks only remote, not local
// check local seed
if (seed == null) {
if (host.substring(0, host.length() - 6).equals(mySeed.hash))
seed = mySeed;
else return null;
}
return seed.getAddress() + ((subdom == null) ? "" : ("/" + subdom));
} else if (host.endsWith(".yacy")) {
// identify subdomain
p = host.indexOf(".");
if ((p > 0) && (p != (host.length() - 5))) {
subdom = host.substring(0, p); // no double-dot attack possible, the subdom cannot have ".." in it
host = host.substring(p + 1); // if ever, the double-dots are here but do not harm
}
// identify domain
String domain = host.substring(0, host.length() - 5).toLowerCase();
seed = lookupByName(domain);
if (seed == null) return null;
if ((seed == mySeed) && (!(seed.isOnline()))) {
// take local ip instead of external
return serverCore.publicIP().getHostAddress() + ":" + sb.getConfig("port", "8080") + ((subdom == null) ? "" : ("/" + subdom));
}
return seed.getAddress() + ((subdom == null) ? "" : ("/" + subdom));
} else {
return null;
}
}
class seedEnum implements Enumeration {
kelondroMap.mapIterator it;
yacySeed nextSeed;
kelondroMap database;
public seedEnum(boolean up, boolean rot, byte[] firstKey, kelondroMap database) {
this.database = database;
try {
it = (firstKey == null) ? database.maps(up, rot) : database.maps(up, rot, firstKey);
nextSeed = internalNext();
} catch (IOException e) {
System.out.println("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
if (database == seedPassiveDB) seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
it = null;
} catch (kelondroException e) {
System.out.println("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
if (database == seedPassiveDB) seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
it = null;
}
}
public seedEnum(boolean up, String field, kelondroMap database) {
this.database = database;
try {
it = database.maps(up, field);
nextSeed = internalNext();
} catch (kelondroException e) {
System.out.println("ERROR seedLinEnum: seed.db corrupt (" + e.getMessage() + "); resetting seed.db");
e.printStackTrace();
if (database == seedActiveDB) seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile);
if (database == seedPassiveDB) seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile);
it = null;
} }
public boolean hasMoreElements() {
return (nextSeed != null);
}
public yacySeed internalNext() {
if ((it == null) || (!(it.hasNext()))) return null;
Map dna = (Map) it.next();
String hash = (String) dna.remove("key");
return new yacySeed(hash, dna);
}
public Object nextElement() {
yacySeed seed = nextSeed;
nextSeed = internalNext();
return seed;
}
}
}
| true | true | public yacySeedDB(plasmaSwitchboard sb,
File seedActiveDBFile,
File seedPassiveDBFile,
File seedPotentialDBFile,
int bufferkb) throws IOException {
this.seedActiveDBFile = seedActiveDBFile;
this.seedPassiveDBFile = seedPassiveDBFile;
this.seedPotentialDBFile = seedPotentialDBFile;
this.mySeed = null; // my own seed
this.sb = sb;
// set up seed database
seedActiveDB = openSeedTable(seedActiveDBFile);
seedPassiveDB = openSeedTable(seedPassiveDBFile);
seedPotentialDB = openSeedTable(seedPotentialDBFile);
// create or init own seed
myOwnSeedFile = new File(sb.getRootPath(), sb.getConfig("yacyOwnSeedFile", "mySeed.txt"));
if (myOwnSeedFile.exists()) {
// load existing identity
mySeed = yacySeed.load(myOwnSeedFile);
} else {
// create new identity
mySeed = yacySeed.genLocalSeed(sb);
// save of for later use
mySeed.save(myOwnSeedFile); // in a file
//writeMap(mySeed.hash, mySeed.dna, "new"); // in a database
}
mySeed.put("IP", ""); // we delete the old information to see what we have now
mySeed.put("Port", sb.getConfig("port", "8080")); // set my seed's correct port number
mySeed.put("PeerType", "virgin"); // markup startup condition
// start our virtual DNS service for yacy peers with empty cache
nameLookupCache = new Hashtable();
// check if we are in the seedCaches: this can happen if someone else published our seed
removeMySeed();
// set up seed queue (for probing candidates)
seedQueue = null;
}
| public yacySeedDB(plasmaSwitchboard sb,
File seedActiveDBFile,
File seedPassiveDBFile,
File seedPotentialDBFile,
int bufferkb) throws IOException {
this.seedActiveDBFile = seedActiveDBFile;
this.seedPassiveDBFile = seedPassiveDBFile;
this.seedPotentialDBFile = seedPotentialDBFile;
this.mySeed = null; // my own seed
this.sb = sb;
// set up seed database
seedActiveDB = openSeedTable(seedActiveDBFile);
seedPassiveDB = openSeedTable(seedPassiveDBFile);
seedPotentialDB = openSeedTable(seedPotentialDBFile);
// create or init own seed
myOwnSeedFile = new File(sb.getRootPath(), sb.getConfig("yacyOwnSeedFile", "mySeed.txt"));
if (myOwnSeedFile.exists() && (myOwnSeedFile.length() > 0)) {
// load existing identity
mySeed = yacySeed.load(myOwnSeedFile);
} else {
// create new identity
mySeed = yacySeed.genLocalSeed(sb);
// save of for later use
mySeed.save(myOwnSeedFile); // in a file
//writeMap(mySeed.hash, mySeed.dna, "new"); // in a database
}
mySeed.put("IP", ""); // we delete the old information to see what we have now
mySeed.put("Port", sb.getConfig("port", "8080")); // set my seed's correct port number
mySeed.put("PeerType", "virgin"); // markup startup condition
// start our virtual DNS service for yacy peers with empty cache
nameLookupCache = new Hashtable();
// check if we are in the seedCaches: this can happen if someone else published our seed
removeMySeed();
// set up seed queue (for probing candidates)
seedQueue = null;
}
|
diff --git a/talk/client/ContactsList.java b/talk/client/ContactsList.java
index 325b42f..703ddec 100644
--- a/talk/client/ContactsList.java
+++ b/talk/client/ContactsList.java
@@ -1,79 +1,81 @@
package talk.client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import talk.common.*;
import java.util.*;
import javax.swing.event.*;
public class ContactsList extends JList {
private ContactsPanel contactsPanel;
ContactsList(DefaultListModel contactsListModel, ContactsPanel contactsPanel) {
super(contactsListModel);
this.contactsPanel = contactsPanel;
//this.addListSelectionListener(new ConatacsListActionListener());
this.addMouseListener(new ConatacsListMouseAdapter());
}
// public void actionPerformed(ActionEvent e) {
// Object o = e.getSource();
// System.out.println(o);
// }
// class ConatacsListActionListener implements ListSelectionListener {
// public void valueChanged(ListSelectionEvent e) {
// if(e.getValueIsAdjusting()) return;
// ContactsList cl = (ContactsList) e.getSource();
// System.out.println(cl.getSelectedIndex());
// }
// }
class ConatacsListMouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e) {
ContactsList cl = (ContactsList) e.getSource();
if (e.getClickCount() == 2) {
int index = cl.locationToIndex(e.getPoint());
- String us = (String)cl.getModel().getElementAt(index);
- System.out.println("Double clicked on Item " + index + ": us:" + us);
- String[] uname = us.split(":");
- contactsPanel.clientGUI.findOrCreateTab(uname[uname.length-1]);
+ try {
+ String us = (String)cl.getModel().getElementAt(index);
+ System.out.println("Double clicked on Item " + index + ": us:" + us);
+ String[] uname = us.split(":");
+ contactsPanel.clientGUI.findOrCreateTab(uname[uname.length-1]);
+ } catch (Exception ex) { }
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
}
// final JList list = new JList(dataModel);
// MouseListener mouseListener = new MouseAdapter() {
// public void mouseClicked(MouseEvent e) {
// if (e.getClickCount() == 2) {
// int index = list.locationToIndex(e.getPoint());
// System.out.println("Double clicked on Item " + index);
// }
// }
// };
// list.addMouseListener(mouseListener);
| true | true | public void mouseClicked(MouseEvent e) {
ContactsList cl = (ContactsList) e.getSource();
if (e.getClickCount() == 2) {
int index = cl.locationToIndex(e.getPoint());
String us = (String)cl.getModel().getElementAt(index);
System.out.println("Double clicked on Item " + index + ": us:" + us);
String[] uname = us.split(":");
contactsPanel.clientGUI.findOrCreateTab(uname[uname.length-1]);
}
}
| public void mouseClicked(MouseEvent e) {
ContactsList cl = (ContactsList) e.getSource();
if (e.getClickCount() == 2) {
int index = cl.locationToIndex(e.getPoint());
try {
String us = (String)cl.getModel().getElementAt(index);
System.out.println("Double clicked on Item " + index + ": us:" + us);
String[] uname = us.split(":");
contactsPanel.clientGUI.findOrCreateTab(uname[uname.length-1]);
} catch (Exception ex) { }
}
}
|
diff --git a/src/main/java/br/com/arsmachina/authentication/entity/Role.java b/src/main/java/br/com/arsmachina/authentication/entity/Role.java
index 5850970..08b0987 100644
--- a/src/main/java/br/com/arsmachina/authentication/entity/Role.java
+++ b/src/main/java/br/com/arsmachina/authentication/entity/Role.java
@@ -1,199 +1,199 @@
// Copyright 2008 Thiago H. de Paula Figueiredo
//
// 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 br.com.arsmachina.authentication.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.validator.NotNull;
/**
* Class that represents a role an user can have in the application. It is used to avoid creating
* {@link User} subclasses, thus solving the problem of the same user having more than one role at
* the same time.
*
* @author Thiago H. de Paula Figueiredo
*/
@Entity
@Table(name = "`role`")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Role implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private User user;
/**
* Returns the value of the <code>id</code> property.
*
* @return a {@link Integer}.
*/
@Id
@GeneratedValue
public Integer getId() {
return id;
}
/**
* Changes the value of the <code>id</code> property.
*
* @param id a {@link Integer}.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Returns the value of the <code>user</code> property.
*
* @return a {@link User}.
*/
@ManyToOne(optional = false)
@JoinColumn(nullable = false)
@NotNull
public User getUser() {
return user;
}
/**
* Changes the value of the <code>user</code> property.
*
* @param user a {@link User}.
*/
public void setUser(User user) {
this.user = user;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
- if (getClass() != obj.getClass())
+ if (obj instanceof Role == false)
return false;
final Role other = (Role) obj;
if (id == null) {
- if (other.id != null)
+ if (other.getId() != null)
return false;
}
- else if (!id.equals(other.id))
+ else if (!id.equals(other.getId()))
return false;
return true;
}
/**
* Invokes <code>user.getEmail()<code>.
* @return
* @see br.com.arsmachina.authentication.entity.User#getEmail()
*/
@Transient
public String getEmail() {
return user.getEmail();
}
/**
* Invokes <code>user.getLogin()<code>.
* @return
* @see br.com.arsmachina.authentication.entity.User#getLogin()
*/
@Transient
public String getLogin() {
return user.getLogin();
}
/**
* Invokes <code>user.getName()<code>.
* @return a {@link String}.
* @see br.com.arsmachina.authentication.entity.User#getName()
*/
@Transient
public String getName() {
return user.getName();
}
/**
* Invokes <code>user.isCredentialsExpired()<code>.
* @return a <code>boolean</code>.
* @see br.com.arsmachina.authentication.entity.User#isCredentialsExpired()
*/
@Transient
public boolean isCredentialsExpired() {
return user.isCredentialsExpired();
}
/**
* Invokes <code>user.isEnabled()<code>.
* @return a <code>boolean</code>.
* @see br.com.arsmachina.authentication.entity.User#isEnabled()
*/
@Transient
public boolean isEnabled() {
return user.isEnabled();
}
/**
* Invokes <code>user.isExpired()<code>.
* @return a <code>boolean</code>.
* @see br.com.arsmachina.authentication.entity.User#isExpired()
*/
@Transient
public boolean isExpired() {
return user.isExpired();
}
/**
* Invokes <code>user.isLocked()<code>.
* @return a <code>boolean</code>.
* @see br.com.arsmachina.authentication.entity.User#isLocked()
*/
@Transient
public boolean isLocked() {
return user.isLocked();
}
/**
* Invokes <code>user.isLoggedIn()<code>.
* @return a <code>boolean</code>.
* @see br.com.arsmachina.authentication.entity.User#isLoggedIn()
*/
@Transient
public boolean isLoggedIn() {
return user.isLoggedIn();
}
}
| false | true | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Role other = (Role) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
| public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Role == false)
return false;
final Role other = (Role) obj;
if (id == null) {
if (other.getId() != null)
return false;
}
else if (!id.equals(other.getId()))
return false;
return true;
}
|
diff --git a/src/main/java/tconstruct/weaponry/WeaponryActiveToolMod.java b/src/main/java/tconstruct/weaponry/WeaponryActiveToolMod.java
index 87187a450..d07f97444 100644
--- a/src/main/java/tconstruct/weaponry/WeaponryActiveToolMod.java
+++ b/src/main/java/tconstruct/weaponry/WeaponryActiveToolMod.java
@@ -1,38 +1,38 @@
package tconstruct.weaponry;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import tconstruct.library.ActiveToolMod;
import tconstruct.library.weaponry.IAmmo;
public class WeaponryActiveToolMod extends ActiveToolMod {
@Override
public boolean damageTool(ItemStack stack, int damage, EntityLivingBase entity) {
if(stack.getItem() == TinkerWeaponry.javelin && stack.hasTagCompound()) {
NBTTagCompound tags = stack.getTagCompound().getCompoundTag("InfiTool");
IAmmo ammo =(IAmmo)stack.getItem();
if(tags.getInteger("Damage") == 0)
{
- int rem = ammo.addAmmo(1, stack);
+ int rem = ammo.consumeAmmo(1, stack);
if(rem > 0)
return true;
}
else if(ammo.getAmmoCount(stack) > 0)
{
int d = tags.getInteger("Damage") + damage;
int max = tags.getInteger("TotalDurability");
if(d > max)
{
tags.setInteger("Damage", 0);
return true;
}
}
}
// all other ammo items can't be damaged
else if(stack.getItem() instanceof IAmmo)
return true;
return false;
}
}
| true | true | public boolean damageTool(ItemStack stack, int damage, EntityLivingBase entity) {
if(stack.getItem() == TinkerWeaponry.javelin && stack.hasTagCompound()) {
NBTTagCompound tags = stack.getTagCompound().getCompoundTag("InfiTool");
IAmmo ammo =(IAmmo)stack.getItem();
if(tags.getInteger("Damage") == 0)
{
int rem = ammo.addAmmo(1, stack);
if(rem > 0)
return true;
}
else if(ammo.getAmmoCount(stack) > 0)
{
int d = tags.getInteger("Damage") + damage;
int max = tags.getInteger("TotalDurability");
if(d > max)
{
tags.setInteger("Damage", 0);
return true;
}
}
}
// all other ammo items can't be damaged
else if(stack.getItem() instanceof IAmmo)
return true;
return false;
}
| public boolean damageTool(ItemStack stack, int damage, EntityLivingBase entity) {
if(stack.getItem() == TinkerWeaponry.javelin && stack.hasTagCompound()) {
NBTTagCompound tags = stack.getTagCompound().getCompoundTag("InfiTool");
IAmmo ammo =(IAmmo)stack.getItem();
if(tags.getInteger("Damage") == 0)
{
int rem = ammo.consumeAmmo(1, stack);
if(rem > 0)
return true;
}
else if(ammo.getAmmoCount(stack) > 0)
{
int d = tags.getInteger("Damage") + damage;
int max = tags.getInteger("TotalDurability");
if(d > max)
{
tags.setInteger("Damage", 0);
return true;
}
}
}
// all other ammo items can't be damaged
else if(stack.getItem() instanceof IAmmo)
return true;
return false;
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/httpbinding/HttpExternalService.java b/axis2/src/main/java/org/apache/ode/axis2/httpbinding/HttpExternalService.java
index de67e29d7..735857bf6 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/httpbinding/HttpExternalService.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/httpbinding/HttpExternalService.java
@@ -1,440 +1,440 @@
/*
* 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.ode.axis2.httpbinding;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.ExternalService;
import org.apache.ode.axis2.ODEService;
import org.apache.ode.axis2.Properties;
import org.apache.ode.bpel.epr.EndpointFactory;
import org.apache.ode.bpel.epr.WSAEndpoint;
import org.apache.ode.bpel.iapi.BpelServer;
import org.apache.ode.bpel.iapi.EndpointReference;
import org.apache.ode.bpel.iapi.Message;
import org.apache.ode.bpel.iapi.MessageExchange;
import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange;
import org.apache.ode.bpel.iapi.ProcessConf;
import org.apache.ode.bpel.iapi.Scheduler;
import org.apache.ode.utils.DOMUtils;
import org.apache.ode.utils.Namespaces;
import org.apache.ode.utils.wsdl.Messages;
import org.apache.ode.utils.wsdl.WsdlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.wsdl.Binding;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.Fault;
import javax.wsdl.Operation;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.extensions.mime.MIMEContent;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
/**
* @author <a href="mailto:[email protected]">Alexis Midon</a>
*/
public class HttpExternalService implements ExternalService {
private static final Log log = LogFactory.getLog(HttpExternalService.class);
private static final Messages msgs = Messages.getMessages(Messages.class);
private MultiThreadedHttpConnectionManager connections;
protected ExecutorService executorService;
protected Scheduler scheduler;
protected BpelServer server;
protected ProcessConf pconf;
private String targetNamespace;
protected QName serviceName;
protected String portName;
protected WSAEndpoint endpointReference;
protected HttpMethodConverter httpMethodConverter;
protected Binding portBinding;
public HttpExternalService(ProcessConf pconf, QName serviceName, String portName, ExecutorService executorService, Scheduler scheduler, BpelServer server) {
this.portName = portName;
this.serviceName = serviceName;
this.executorService = executorService;
this.scheduler = scheduler;
this.server = server;
this.pconf = pconf;
Definition definition = pconf.getDefinitionForService(serviceName);
targetNamespace = definition.getTargetNamespace();
Service serviceDef = definition.getService(serviceName);
if (serviceDef == null)
throw new IllegalArgumentException(msgs.msgServiceDefinitionNotFound(serviceName));
Port port = serviceDef.getPort(portName);
if (port == null)
throw new IllegalArgumentException(msgs.msgPortDefinitionNotFound(serviceName, portName));
portBinding = port.getBinding();
if (portBinding == null)
throw new IllegalArgumentException(msgs.msgBindingNotFound(portName));
// validate the http binding
if (!WsdlUtils.useHTTPBinding(port)) {
throw new IllegalArgumentException(msgs.msgNoHTTPBindingForPort(portName));
}
// throws an IllegalArgumentException if not valid
new HttpBindingValidator(this.portBinding).validate();
// initial endpoint reference
Element eprElmt = ODEService.genEPRfromWSDL(definition, serviceName, portName);
if (eprElmt == null)
throw new IllegalArgumentException(msgs.msgPortDefinitionNotFound(serviceName, portName));
endpointReference = EndpointFactory.convertToWSA(ODEService.createServiceRef(eprElmt));
httpMethodConverter = new HttpMethodConverter(this.portBinding);
connections = new MultiThreadedHttpConnectionManager();
}
public String getPortName() {
return portName;
}
public QName getServiceName() {
return serviceName;
}
public void close() {
connections.shutdown();
}
public EndpointReference getInitialEndpointReference() {
return endpointReference;
}
public void invoke(PartnerRoleMessageExchange odeMex) {
if (log.isDebugEnabled()) log.debug("Preparing " + getClass().getSimpleName() + " invocation...");
try {
// note: don't make this map an instance attribute, so we always get the latest version
final Map<String, String> properties = pconf.getEndpointProperties(endpointReference);
final HttpParams params = Properties.HttpClient.translate(properties);
// build the http method
final HttpMethod method = httpMethodConverter.createHttpRequest(odeMex, params);
// create a client
HttpClient client = new HttpClient(connections);
// don't forget to wire params so that EPR properties are passed around
client.getParams().setDefaults(params);
// configure the client (proxy, security, etc)
HttpClientHelper.configure(client.getHostConfiguration(), client.getState(), method.getURI(), params);
// this callable encapsulates the http method execution and the process of the response
final Callable executionCallable;
// execute it
boolean isTwoWay = odeMex.getMessageExchangePattern() == MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
if (isTwoWay) {
// two way
executionCallable = new HttpExternalService.TwoWayCallable(client, method, odeMex);
scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
public void afterCompletion(boolean success) {
// If the TX is rolled back, then we don't send the request.
if (!success) return;
// The invocation must happen in a separate thread
executorService.submit(executionCallable);
}
public void beforeCompletion() {
}
});
odeMex.replyAsync();
} else {
// one way, just execute and forget
executionCallable = new HttpExternalService.OneWayCallable(client, method, odeMex);
executorService.submit(executionCallable);
odeMex.replyOneWayOk();
}
} catch (UnsupportedEncodingException e) {
String errmsg = "The HTTP encoding returned isn't supported " + odeMex;
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
} catch (URIException e) {
String errmsg = "Error sending message to " + getClass().getSimpleName() + " for ODE mex " + odeMex;
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
} catch (Exception e) {
String errmsg = "Unknown HTTP call error for ODE mex " + odeMex;
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
}
}
private class OneWayCallable implements Callable<Void> {
HttpMethod method;
PartnerRoleMessageExchange odeMex;
HttpClient client;
public OneWayCallable(HttpClient client, HttpMethod method, PartnerRoleMessageExchange odeMex) {
this.method = method;
this.odeMex = odeMex;
this.client = client;
}
public Void call() throws Exception {
try {
// simply execute the http method
if (log.isDebugEnabled())
log.debug("Executing http request : " + method.getName() + " " + method.getURI());
final int statusCode = client.executeMethod(method);
// invoke getResponseBody to force the loading of the body
// Actually the processResponse may happen in a separate thread and
// as a result the connection might be closed before the body processing (see the finally clause below).
byte[] responseBody = method.getResponseBody();
// ... and process the response
processResponse(statusCode);
} catch (final IOException e) {
// ODE MEX needs to be invoked in a TX.
try {
scheduler.execIsolatedTransaction(new Callable<Void>() {
public Void call() throws Exception {
String errmsg = "Unable to execute http request : " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
return null;
}
});
} catch (Exception e1) {
String errmsg = "Error executing reply transaction; reply will be lost.";
log.error(errmsg, e);
}
} finally {
method.releaseConnection();
}
return null;
}
public void processResponse(int statusCode) {
// a one-way message does not care about the response
try {
// log the URI since the engine may have moved on while this One Way request was executing
if (statusCode >= 400) {
if (log.isWarnEnabled())
log.warn("OneWay http request [" + method.getURI() + "] failed with status: " + method.getStatusLine());
} else {
if (log.isDebugEnabled())
log.debug("OneWay http request [" + method.getURI() + "] status: " + method.getStatusLine());
}
} catch (URIException e) {
if (log.isDebugEnabled()) log.debug(e);
}
}
}
private class TwoWayCallable extends OneWayCallable {
public TwoWayCallable(org.apache.commons.httpclient.HttpClient client, HttpMethod method, PartnerRoleMessageExchange odeMex) {
super(client, method, odeMex);
}
public void processResponse(final int statusCode) {
try {
// ODE MEX needs to be invoked in a TX.
scheduler.execIsolatedTransaction(new Callable<Void>() {
public Void call() throws Exception {
if (statusCode >= 200 && statusCode < 300) {
_2xx_success();
} else if (statusCode >= 300 && statusCode < 400) {
_3xx_redirection();
} else if (statusCode >= 400 && statusCode < 500) {
_4xx_badRequest();
} else if (statusCode >= 500 && statusCode < 600) {
_5xx_serverError();
} else {
unmanagedStatus();
}
return null;
}
});
} catch (Exception e) {
String errmsg = "Error executing reply transaction; reply will be lost.";
log.error(errmsg, e);
}
}
private void unmanagedStatus() throws IOException {
String errmsg = "Unmanaged Status Code! " + method.getStatusLine();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
/**
* For 500s if a fault is defined in the WSDL and the response body contains the corresponding xml doc, then reply with a fault ; else reply with failure.
*
* @throws IOException
*/
private void _5xx_serverError() throws IOException {
String errmsg = "Internal Server Error! " + method.getStatusLine();
log.error(errmsg);
Operation opDef = odeMex.getOperation();
BindingOperation opBinding = portBinding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName());
if (opDef.getFaults().isEmpty()) {
errmsg = "Operation has no fault. This 500 error will be considered as a failure.";
if (log.isDebugEnabled()) log.debug(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
} else if (opBinding.getBindingFaults().isEmpty()) {
errmsg = "No fault binding. This 500 error will be considered as a failure.";
if (log.isDebugEnabled()) log.debug(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
} else if (method.getResponseBodyAsStream() == null) {
errmsg = "No body in the response. This 500 error will be considered as a failure.";
if (log.isDebugEnabled()) log.debug(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
} else {
final InputStream bodyAsStream = method.getResponseBodyAsStream();
try {
Element bodyEl = DOMUtils.parse(bodyAsStream).getDocumentElement();
QName bodyName = new QName(bodyEl.getNamespaceURI(), bodyEl.getNodeName());
Fault faultDef = WsdlUtils.inferFault(opDef, bodyName);
// is this fault bound with ODE extension?
if (!WsdlUtils.isOdeFault(opBinding.getBindingFault(faultDef.getName()))) {
errmsg = "Fault " + bodyName + " is not bound with " + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "fault") + ". This 500 error will be considered as a failure.";
if (log.isDebugEnabled()) log.debug(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
} else {
Part partDef = (Part) faultDef.getMessage().getParts().values().iterator().next();
// build the element to be sent back
Document odeMsg = DOMUtils.newDocument();
Element odeMsgEl = odeMsg.createElementNS(null, "message");
Element partEl = odeMsgEl.getOwnerDocument().createElementNS(null, partDef.getName());
odeMsgEl.appendChild(partEl);
// import the response body
partEl.appendChild(odeMsgEl.getOwnerDocument().importNode(bodyEl, true));
QName faultType = new QName(targetNamespace, faultDef.getName());
Message response = odeMex.createMessage(faultType);
response.setMessage(odeMsgEl);
// extract and set headers
httpMethodConverter.extractHttpResponseHeaders(response, method, faultDef.getMessage(), opBinding.getBindingOutput());
// finally send the fault. We did it!
odeMex.replyWithFault(faultType, response);
}
} catch (Exception e) {
errmsg = "Unable to parse the response body as xml. This 500 error will be considered as a failure.";
if (log.isDebugEnabled()) log.debug(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method, false));
}
}
}
private void _4xx_badRequest() throws IOException {
String errmsg = "Bad Request! " + method.getStatusLine();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
private void _3xx_redirection() throws IOException {
String errmsg = "Redirections are not supported! " + method.getStatusLine();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
private void _2xx_success() {
if (log.isDebugEnabled()) log.debug("Http Status Line=" + method.getStatusLine());
if (log.isDebugEnabled()) log.debug("Received response for MEX " + odeMex);
Operation opDef = odeMex.getOperation();
BindingOperation opBinding = portBinding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName());
// assumption is made that a response may have at most one body. HttpBindingValidator checks this.
MIMEContent outputContent = WsdlUtils.getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
- boolean isBodyMandatory = outputContent != null && !outputContent.getType().endsWith("text/xml");
+ boolean isBodyMandatory = outputContent != null && outputContent.getType().endsWith("text/xml");
try {
final InputStream bodyAsStream = method.getResponseBodyAsStream();
if (isBodyMandatory && bodyAsStream == null) {
String errmsg = "Response body is mandatory but missing! Msg Id=" + odeMex.getMessageExchangeId();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
} else {
javax.wsdl.Message outputMessage = odeMex.getOperation().getOutput().getMessage();
Message odeResponse = odeMex.createMessage(outputMessage.getQName());
// handle the body if any
if (bodyAsStream != null) {
// only text/xml is supported in the response body
try {
Element bodyElement = DOMUtils.parse(bodyAsStream).getDocumentElement();
// we expect a single part per output message
// see org.apache.ode.axis2.httpbinding.HttpBindingValidator call in constructor
Part part = (Part) outputMessage.getParts().values().iterator().next();
Element partElement = httpMethodConverter.createPartElement(part, bodyElement);
odeResponse.setPart(part.getName(), partElement);
} catch (Exception e) {
String errmsg = "Unable to parse the response body: " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
// handle headers
httpMethodConverter.extractHttpResponseHeaders(odeResponse, method, outputMessage, opBinding.getBindingOutput());
try {
if (log.isInfoEnabled())
log.info("Response:\n" + DOMUtils.domToString(odeResponse.getMessage()));
odeMex.reply(odeResponse);
} catch (Exception ex) {
String errmsg = "Unable to process response: " + ex.getMessage();
log.error(errmsg, ex);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
}
} catch (IOException e) {
String errmsg = "Unable to get the request body : " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
}
}
| true | true | private void _2xx_success() {
if (log.isDebugEnabled()) log.debug("Http Status Line=" + method.getStatusLine());
if (log.isDebugEnabled()) log.debug("Received response for MEX " + odeMex);
Operation opDef = odeMex.getOperation();
BindingOperation opBinding = portBinding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName());
// assumption is made that a response may have at most one body. HttpBindingValidator checks this.
MIMEContent outputContent = WsdlUtils.getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
boolean isBodyMandatory = outputContent != null && !outputContent.getType().endsWith("text/xml");
try {
final InputStream bodyAsStream = method.getResponseBodyAsStream();
if (isBodyMandatory && bodyAsStream == null) {
String errmsg = "Response body is mandatory but missing! Msg Id=" + odeMex.getMessageExchangeId();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
} else {
javax.wsdl.Message outputMessage = odeMex.getOperation().getOutput().getMessage();
Message odeResponse = odeMex.createMessage(outputMessage.getQName());
// handle the body if any
if (bodyAsStream != null) {
// only text/xml is supported in the response body
try {
Element bodyElement = DOMUtils.parse(bodyAsStream).getDocumentElement();
// we expect a single part per output message
// see org.apache.ode.axis2.httpbinding.HttpBindingValidator call in constructor
Part part = (Part) outputMessage.getParts().values().iterator().next();
Element partElement = httpMethodConverter.createPartElement(part, bodyElement);
odeResponse.setPart(part.getName(), partElement);
} catch (Exception e) {
String errmsg = "Unable to parse the response body: " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
// handle headers
httpMethodConverter.extractHttpResponseHeaders(odeResponse, method, outputMessage, opBinding.getBindingOutput());
try {
if (log.isInfoEnabled())
log.info("Response:\n" + DOMUtils.domToString(odeResponse.getMessage()));
odeMex.reply(odeResponse);
} catch (Exception ex) {
String errmsg = "Unable to process response: " + ex.getMessage();
log.error(errmsg, ex);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
}
} catch (IOException e) {
String errmsg = "Unable to get the request body : " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
| private void _2xx_success() {
if (log.isDebugEnabled()) log.debug("Http Status Line=" + method.getStatusLine());
if (log.isDebugEnabled()) log.debug("Received response for MEX " + odeMex);
Operation opDef = odeMex.getOperation();
BindingOperation opBinding = portBinding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName());
// assumption is made that a response may have at most one body. HttpBindingValidator checks this.
MIMEContent outputContent = WsdlUtils.getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
boolean isBodyMandatory = outputContent != null && outputContent.getType().endsWith("text/xml");
try {
final InputStream bodyAsStream = method.getResponseBodyAsStream();
if (isBodyMandatory && bodyAsStream == null) {
String errmsg = "Response body is mandatory but missing! Msg Id=" + odeMex.getMessageExchangeId();
log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
} else {
javax.wsdl.Message outputMessage = odeMex.getOperation().getOutput().getMessage();
Message odeResponse = odeMex.createMessage(outputMessage.getQName());
// handle the body if any
if (bodyAsStream != null) {
// only text/xml is supported in the response body
try {
Element bodyElement = DOMUtils.parse(bodyAsStream).getDocumentElement();
// we expect a single part per output message
// see org.apache.ode.axis2.httpbinding.HttpBindingValidator call in constructor
Part part = (Part) outputMessage.getParts().values().iterator().next();
Element partElement = httpMethodConverter.createPartElement(part, bodyElement);
odeResponse.setPart(part.getName(), partElement);
} catch (Exception e) {
String errmsg = "Unable to parse the response body: " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
// handle headers
httpMethodConverter.extractHttpResponseHeaders(odeResponse, method, outputMessage, opBinding.getBindingOutput());
try {
if (log.isInfoEnabled())
log.info("Response:\n" + DOMUtils.domToString(odeResponse.getMessage()));
odeMex.reply(odeResponse);
} catch (Exception ex) {
String errmsg = "Unable to process response: " + ex.getMessage();
log.error(errmsg, ex);
odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, HttpClientHelper.prepareDetailsElement(method));
}
}
} catch (IOException e) {
String errmsg = "Unable to get the request body : " + e.getMessage();
log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
return;
}
}
|
diff --git a/src/Program.java b/src/Program.java
index 5c481a0..f0dbdff 100644
--- a/src/Program.java
+++ b/src/Program.java
@@ -1,148 +1,151 @@
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import simpleformat.*;
import simpleformat2clutograph.SimpleFormat2ClutoGraph;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author saricas
*/
public class Program {
public static void main(String[] args)
throws TransformerConfigurationException, TransformerException, IOException, FileNotFoundException, FileFormatNotSupportedException {
if (args.length != 3) {
System.err.println("Usage:");
System.err.println(" java -jar Xmi2Graphml.jar xmiFileName"
+ " authorityThreshold(float) hubThreshold(float)");
System.exit(1);
}
File xmiFile = new File("./" + args[0]);
InputStream xslGraphml =
Program.class.getResourceAsStream("/xmi2graphml/xmi2graphml.xsl");
InputStream xslSimpleFormat =
Program.class.getResourceAsStream("/xmi2simpleformat/xmi2simpleformat.xsl");
Source xmiSource = new StreamSource(xmiFile);
Source xsltGraphml = new StreamSource(xslGraphml);
Source xsltSimpleFormat = new StreamSource(xslSimpleFormat);
String fileName = args[0].substring(0, args[0].indexOf(".xmi"));
File graphml = new File("./" + fileName + ".graphml");
File simpleFormat = new File("./" + fileName + ".smpl");
Result resultGraphml = new StreamResult(graphml);
Result resultSimpleFormat = new StreamResult(simpleFormat);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer transGraphml = transFact.newTransformer(xsltGraphml);
Transformer transSimpleFormat = transFact.newTransformer(xsltSimpleFormat);
transGraphml.setOutputProperty(OutputKeys.INDENT, "yes");
transGraphml.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transSimpleFormat.setOutputProperty(OutputKeys.INDENT, "yes");
transSimpleFormat.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
if (createFile(graphml)) {
System.out.println("Creating graphml file...");
transGraphml.transform(xmiSource, resultGraphml);
System.out.println("Transformation completed. Output file: " + graphml.getCanonicalPath());
}
if (createFile(simpleFormat)) {
System.out.println("Creating simpleformat file...");
transSimpleFormat.transform(xmiSource, resultSimpleFormat);
System.out.println("Transformation completed. Output file: " + simpleFormat.getCanonicalPath());
}
// create sparse graph matrix file for cluto clustering tool
File graphFile = new File("./" + fileName + ".graph");
if (createFile(graphFile)) {
System.out.println("Creating graph file...");
SimpleFormat2ClutoGraph sf2cg = new SimpleFormat2ClutoGraph(simpleFormat);
sf2cg.write(graphFile);
System.out.println("Transformation completed. Output file: " + graphFile.getCanonicalPath());
}
// calculate authority, hub and cycle classes from simpleformat
System.out.println("Calculating authority, hub and cycle classes.");
Tokenizer tokenizer = new Tokenizer(simpleFormat);
List<simpleformat.Class> klasses = tokenizer.tokenize();
File resultsFile = new File("./" + fileName + ".txt");
createFile(resultsFile);
FileOutputStream ostream = new FileOutputStream(resultsFile);
DataOutputStream out = new DataOutputStream(ostream);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out));
wr.write("Authority parameter: " + String.valueOf(Float.parseFloat(args[1])));
wr.newLine();
wr.write("Hub parameter: " + String.valueOf(Float.parseFloat(args[2])));
wr.newLine();
wr.newLine();
AuthorityClassFinder authorityClassFinder =
new AuthorityClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[1]));
List<simpleformat.Class> authorityList = authorityClassFinder.find();
HubClassFinder hubClassFinder =
new HubClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[2]));
List<simpleformat.Class> hubList = hubClassFinder.find();
// filter out god classes
List<simpleformat.Class> godList = new ArrayList<simpleformat.Class>();
- for (simpleformat.Class c : authorityList) {
+ for (int i=0; i < authorityList.size(); i++)
+ {
+ simpleformat.Class c = authorityList.get(i);
if (hubList.contains(c)) {
c.setType(simpleformat.Class.GOD);
authorityList.remove(c);
hubList.remove(c);
godList.add(c);
+ i--;
}
}
printResults("God", godList, wr);
printResults("Authority", authorityList, wr);
printResults("Hub", hubList, wr);
CycleClassFinder cycleClassFinder = new CycleClassFinder(klasses);
List<simpleformat.Class> cycleList = cycleClassFinder.find();
printResults("Cycle", cycleList, wr);
wr.close();
}
private static void printResults(String title, List<simpleformat.Class> list, BufferedWriter wr)
throws IOException {
System.out.println(title + " count: " + String.valueOf(list.size()));
wr.write(title + " count: " + String.valueOf(list.size()));
wr.newLine();
for (simpleformat.Class c : list) {
System.out.println("- " + c.getName());
wr.write("- " + c.getName());
wr.newLine();
}
System.out.println();
wr.newLine();
}
private static boolean createFile(File f) throws IOException {
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
return f.createNewFile();
return false;
}
}
| false | true | public static void main(String[] args)
throws TransformerConfigurationException, TransformerException, IOException, FileNotFoundException, FileFormatNotSupportedException {
if (args.length != 3) {
System.err.println("Usage:");
System.err.println(" java -jar Xmi2Graphml.jar xmiFileName"
+ " authorityThreshold(float) hubThreshold(float)");
System.exit(1);
}
File xmiFile = new File("./" + args[0]);
InputStream xslGraphml =
Program.class.getResourceAsStream("/xmi2graphml/xmi2graphml.xsl");
InputStream xslSimpleFormat =
Program.class.getResourceAsStream("/xmi2simpleformat/xmi2simpleformat.xsl");
Source xmiSource = new StreamSource(xmiFile);
Source xsltGraphml = new StreamSource(xslGraphml);
Source xsltSimpleFormat = new StreamSource(xslSimpleFormat);
String fileName = args[0].substring(0, args[0].indexOf(".xmi"));
File graphml = new File("./" + fileName + ".graphml");
File simpleFormat = new File("./" + fileName + ".smpl");
Result resultGraphml = new StreamResult(graphml);
Result resultSimpleFormat = new StreamResult(simpleFormat);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer transGraphml = transFact.newTransformer(xsltGraphml);
Transformer transSimpleFormat = transFact.newTransformer(xsltSimpleFormat);
transGraphml.setOutputProperty(OutputKeys.INDENT, "yes");
transGraphml.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transSimpleFormat.setOutputProperty(OutputKeys.INDENT, "yes");
transSimpleFormat.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
if (createFile(graphml)) {
System.out.println("Creating graphml file...");
transGraphml.transform(xmiSource, resultGraphml);
System.out.println("Transformation completed. Output file: " + graphml.getCanonicalPath());
}
if (createFile(simpleFormat)) {
System.out.println("Creating simpleformat file...");
transSimpleFormat.transform(xmiSource, resultSimpleFormat);
System.out.println("Transformation completed. Output file: " + simpleFormat.getCanonicalPath());
}
// create sparse graph matrix file for cluto clustering tool
File graphFile = new File("./" + fileName + ".graph");
if (createFile(graphFile)) {
System.out.println("Creating graph file...");
SimpleFormat2ClutoGraph sf2cg = new SimpleFormat2ClutoGraph(simpleFormat);
sf2cg.write(graphFile);
System.out.println("Transformation completed. Output file: " + graphFile.getCanonicalPath());
}
// calculate authority, hub and cycle classes from simpleformat
System.out.println("Calculating authority, hub and cycle classes.");
Tokenizer tokenizer = new Tokenizer(simpleFormat);
List<simpleformat.Class> klasses = tokenizer.tokenize();
File resultsFile = new File("./" + fileName + ".txt");
createFile(resultsFile);
FileOutputStream ostream = new FileOutputStream(resultsFile);
DataOutputStream out = new DataOutputStream(ostream);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out));
wr.write("Authority parameter: " + String.valueOf(Float.parseFloat(args[1])));
wr.newLine();
wr.write("Hub parameter: " + String.valueOf(Float.parseFloat(args[2])));
wr.newLine();
wr.newLine();
AuthorityClassFinder authorityClassFinder =
new AuthorityClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[1]));
List<simpleformat.Class> authorityList = authorityClassFinder.find();
HubClassFinder hubClassFinder =
new HubClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[2]));
List<simpleformat.Class> hubList = hubClassFinder.find();
// filter out god classes
List<simpleformat.Class> godList = new ArrayList<simpleformat.Class>();
for (simpleformat.Class c : authorityList) {
if (hubList.contains(c)) {
c.setType(simpleformat.Class.GOD);
authorityList.remove(c);
hubList.remove(c);
godList.add(c);
}
}
printResults("God", godList, wr);
printResults("Authority", authorityList, wr);
printResults("Hub", hubList, wr);
CycleClassFinder cycleClassFinder = new CycleClassFinder(klasses);
List<simpleformat.Class> cycleList = cycleClassFinder.find();
printResults("Cycle", cycleList, wr);
wr.close();
}
| public static void main(String[] args)
throws TransformerConfigurationException, TransformerException, IOException, FileNotFoundException, FileFormatNotSupportedException {
if (args.length != 3) {
System.err.println("Usage:");
System.err.println(" java -jar Xmi2Graphml.jar xmiFileName"
+ " authorityThreshold(float) hubThreshold(float)");
System.exit(1);
}
File xmiFile = new File("./" + args[0]);
InputStream xslGraphml =
Program.class.getResourceAsStream("/xmi2graphml/xmi2graphml.xsl");
InputStream xslSimpleFormat =
Program.class.getResourceAsStream("/xmi2simpleformat/xmi2simpleformat.xsl");
Source xmiSource = new StreamSource(xmiFile);
Source xsltGraphml = new StreamSource(xslGraphml);
Source xsltSimpleFormat = new StreamSource(xslSimpleFormat);
String fileName = args[0].substring(0, args[0].indexOf(".xmi"));
File graphml = new File("./" + fileName + ".graphml");
File simpleFormat = new File("./" + fileName + ".smpl");
Result resultGraphml = new StreamResult(graphml);
Result resultSimpleFormat = new StreamResult(simpleFormat);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer transGraphml = transFact.newTransformer(xsltGraphml);
Transformer transSimpleFormat = transFact.newTransformer(xsltSimpleFormat);
transGraphml.setOutputProperty(OutputKeys.INDENT, "yes");
transGraphml.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transSimpleFormat.setOutputProperty(OutputKeys.INDENT, "yes");
transSimpleFormat.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
if (createFile(graphml)) {
System.out.println("Creating graphml file...");
transGraphml.transform(xmiSource, resultGraphml);
System.out.println("Transformation completed. Output file: " + graphml.getCanonicalPath());
}
if (createFile(simpleFormat)) {
System.out.println("Creating simpleformat file...");
transSimpleFormat.transform(xmiSource, resultSimpleFormat);
System.out.println("Transformation completed. Output file: " + simpleFormat.getCanonicalPath());
}
// create sparse graph matrix file for cluto clustering tool
File graphFile = new File("./" + fileName + ".graph");
if (createFile(graphFile)) {
System.out.println("Creating graph file...");
SimpleFormat2ClutoGraph sf2cg = new SimpleFormat2ClutoGraph(simpleFormat);
sf2cg.write(graphFile);
System.out.println("Transformation completed. Output file: " + graphFile.getCanonicalPath());
}
// calculate authority, hub and cycle classes from simpleformat
System.out.println("Calculating authority, hub and cycle classes.");
Tokenizer tokenizer = new Tokenizer(simpleFormat);
List<simpleformat.Class> klasses = tokenizer.tokenize();
File resultsFile = new File("./" + fileName + ".txt");
createFile(resultsFile);
FileOutputStream ostream = new FileOutputStream(resultsFile);
DataOutputStream out = new DataOutputStream(ostream);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out));
wr.write("Authority parameter: " + String.valueOf(Float.parseFloat(args[1])));
wr.newLine();
wr.write("Hub parameter: " + String.valueOf(Float.parseFloat(args[2])));
wr.newLine();
wr.newLine();
AuthorityClassFinder authorityClassFinder =
new AuthorityClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[1]));
List<simpleformat.Class> authorityList = authorityClassFinder.find();
HubClassFinder hubClassFinder =
new HubClassFinder(klasses, tokenizer.getEdgeCount(), Float.parseFloat(args[2]));
List<simpleformat.Class> hubList = hubClassFinder.find();
// filter out god classes
List<simpleformat.Class> godList = new ArrayList<simpleformat.Class>();
for (int i=0; i < authorityList.size(); i++)
{
simpleformat.Class c = authorityList.get(i);
if (hubList.contains(c)) {
c.setType(simpleformat.Class.GOD);
authorityList.remove(c);
hubList.remove(c);
godList.add(c);
i--;
}
}
printResults("God", godList, wr);
printResults("Authority", authorityList, wr);
printResults("Hub", hubList, wr);
CycleClassFinder cycleClassFinder = new CycleClassFinder(klasses);
List<simpleformat.Class> cycleList = cycleClassFinder.find();
printResults("Cycle", cycleList, wr);
wr.close();
}
|
diff --git a/src/main/java/syam/likes/database/Database.java b/src/main/java/syam/likes/database/Database.java
index 2f735ed..6f818c3 100644
--- a/src/main/java/syam/likes/database/Database.java
+++ b/src/main/java/syam/likes/database/Database.java
@@ -1,285 +1,285 @@
/**
* Likes - Package: syam.likes.database
* Created: 2012/10/10 7:03:46
*/
package syam.likes.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.logging.Logger;
import syam.likes.LikesPlugin;
/**
* Database (Database.java)
* @author syam(syamn)
*/
public class Database {
// Logger
public static final Logger log = LikesPlugin.log;
private static final String logPrefix = LikesPlugin.logPrefix;
private static final String msgPrefix = LikesPlugin.msgPrefix;
private static LikesPlugin plugin;
private static String connectionString = null;
private static String tablePrefix = null;
private static Connection connection = null;
private static long reconnectTimestamp = 0;
/**
* コンストラクタ
* @param plugin FlagGameプラグインインスタンス
*/
public Database(final LikesPlugin plugin){
this.plugin = plugin;
// 接続情報読み込み
connectionString = "jdbc:mysql://" + plugin.getConfigs().getMySQLaddress() + ":" + plugin.getConfigs().getMySQLport()
+ "/" + plugin.getConfigs().getMySQLdbname() + "?user=" + plugin.getConfigs().getMySQLusername() + "&password=" + plugin.getConfigs().getMySQLuserpass();
tablePrefix = plugin.getConfigs().getMySQLtablePrefix();
connect(); // 接続
// ドライバを読み込む
try{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(connectionString);
}catch (ClassNotFoundException ex1){
log.severe(ex1.getLocalizedMessage());
}catch (SQLException ex2){
log.severe(ex2.getLocalizedMessage());
printErrors(ex2);
}
}
/**
* データベースに接続する
*/
public static void connect(){
try{
log.info(logPrefix+ "Attempting connection to MySQL..");
Properties connectionProperties = new Properties();
connectionProperties.put("autoReconnect", "false");
connectionProperties.put("maxReconnects", "0");
connection = DriverManager.getConnection(connectionString, connectionProperties);
log.info(logPrefix+ "Connected MySQL database!");
}catch (SQLException ex){
log.severe(logPrefix+ "Could not connect MySQL database!");
ex.printStackTrace();
printErrors(ex);
}
}
/**
* データベース構造を構築する
*/
public void createStructure(){
// ユーザーデータテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (" +
"`player_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるID
"`player_name` varchar(32) NOT NULL," + // プレイヤー名
"PRIMARY KEY (`player_id`)," +
"UNIQUE KEY `player_name` (`player_name`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ユーザープロフィールテーブル
- write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "profile` (" +
+ write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "profiles` (" +
"`player_id` int(10) unsigned NOT NULL," + // 割り当てられたプレイヤーID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`like_give` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeした回数
"`like_receive` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeされた回数
"`lastlikegave` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeした日時
"PRIMARY KEY (`player_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// Like看板データテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "signs` (" +
"`sign_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てる看板ID
"`sign_name` varchar(32) NOT NULL," + // 看板の名前
"`player_id` int(10) unsigned NOT NULL," + // 所有者のユーザID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`liked` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeカウント
"`lastliked` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeされた日時
"`world` varchar(255) NOT NULL," + // ワールド名
"`x` int(10) NOT NULL," + // x
"`y` int(10) NOT NULL," + // y
"`z` int(10) NOT NULL," + // z
"PRIMARY KEY (`sign_id`)," +
"UNIQUE KEY `sign_name` (`sign_name`)," +
"KEY `x_y_z` (`x`,`y`,`z`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ログデータ
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "likes` (" +
"`like_id` int(12) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるLikeID
"`player_id` int(10) unsigned NOT NULL," + // プレイヤーID
"`sign_id` int(10) unsigned NOT NULL," + // 対象の看板ID
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`timestamp` int(32) unsigned NOT NULL," + // タイムスタンプ
"PRIMARY KEY (`like_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
}
/**
* 書き込みのSQLクエリーを発行する
* @param sql 発行するSQL文
* @return クエリ成功ならtrue、他はfalse
*/
public boolean write(String sql){
// 接続確認
if (isConnected()){
try{
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate(); // 実行
// 後処理
statement.close();
return true;
}catch (SQLException ex){
printErrors(ex);
return false;
}
}
// 未接続
else{
attemptReconnect();
}
return false;
}
/**
* 読み出しのSQLクエリーを発行する
* @param sql 発行するSQL文
* @return SQLクエリで得られたデータ
*/
public HashMap<Integer, ArrayList<String>> read(String sql){
ResultSet resultSet;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
// 接続確認
if (isConnected()){
try{
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery(); // 実行
// 結果のレコード数だけ繰り返す
while (resultSet.next()){
ArrayList<String> column = new ArrayList<String>();
// カラム内のデータを順にリストに追加
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++){
column.add(resultSet.getString(i));
}
// 返すマップにレコード番号とリストを追加
rows.put(resultSet.getRow(), column);
}
// 後処理
resultSet.close();
statement.close();
}catch (SQLException ex){
printErrors(ex);
}
}
// 未接続
else{
attemptReconnect();
}
return rows;
}
/**
* int型の値を取得します
* @param sql 発行するSQL文
* @return 最初のローにある数値
*/
public int getInt(String sql){
ResultSet resultSet;
int result = 0;
// 接続確認
if (isConnected()){
try{
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery(); // 実行
if (resultSet.next()){
result = resultSet.getInt(1);
}else{
// 結果がなければ0を返す
result = 0;
}
// 後処理
resultSet.close();
statement.close();
}catch (SQLException ex){
printErrors(ex);
}
}
// 未接続
else{
attemptReconnect();
}
return result;
}
/**
* 接続状況を返す
* @return 接続中ならtrue、タイムアウトすればfalse
*/
public static boolean isConnected(){
if (connection == null){
return false;
}
try{
return connection.isValid(3);
}catch (SQLException ex){
return false;
}
}
/**
* MySQLデータベースへ再接続を試みる
*/
public static void attemptReconnect(){
final int RECONNECT_WAIT_TICKS = 60000;
final int RECONNECT_DELAY_TICKS = 1200;
if (reconnectTimestamp + RECONNECT_WAIT_TICKS < System.currentTimeMillis()){
reconnectTimestamp = System.currentTimeMillis();
log.severe(logPrefix+ "Conection to MySQL was lost! Attempting to reconnect 60 seconds...");
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new MySQLReconnect(plugin), RECONNECT_DELAY_TICKS);
}
}
/**
* エラーを出力する
* @param ex
*/
private static void printErrors(SQLException ex){
log.warning("SQLException:" +ex.getMessage());
log.warning("SQLState:" +ex.getSQLState());
log.warning("ErrorCode:" +ex.getErrorCode());
}
}
| true | true | public void createStructure(){
// ユーザーデータテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (" +
"`player_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるID
"`player_name` varchar(32) NOT NULL," + // プレイヤー名
"PRIMARY KEY (`player_id`)," +
"UNIQUE KEY `player_name` (`player_name`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ユーザープロフィールテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "profile` (" +
"`player_id` int(10) unsigned NOT NULL," + // 割り当てられたプレイヤーID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`like_give` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeした回数
"`like_receive` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeされた回数
"`lastlikegave` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeした日時
"PRIMARY KEY (`player_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// Like看板データテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "signs` (" +
"`sign_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てる看板ID
"`sign_name` varchar(32) NOT NULL," + // 看板の名前
"`player_id` int(10) unsigned NOT NULL," + // 所有者のユーザID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`liked` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeカウント
"`lastliked` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeされた日時
"`world` varchar(255) NOT NULL," + // ワールド名
"`x` int(10) NOT NULL," + // x
"`y` int(10) NOT NULL," + // y
"`z` int(10) NOT NULL," + // z
"PRIMARY KEY (`sign_id`)," +
"UNIQUE KEY `sign_name` (`sign_name`)," +
"KEY `x_y_z` (`x`,`y`,`z`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ログデータ
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "likes` (" +
"`like_id` int(12) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるLikeID
"`player_id` int(10) unsigned NOT NULL," + // プレイヤーID
"`sign_id` int(10) unsigned NOT NULL," + // 対象の看板ID
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`timestamp` int(32) unsigned NOT NULL," + // タイムスタンプ
"PRIMARY KEY (`like_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
}
| public void createStructure(){
// ユーザーデータテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (" +
"`player_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるID
"`player_name` varchar(32) NOT NULL," + // プレイヤー名
"PRIMARY KEY (`player_id`)," +
"UNIQUE KEY `player_name` (`player_name`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ユーザープロフィールテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "profiles` (" +
"`player_id` int(10) unsigned NOT NULL," + // 割り当てられたプレイヤーID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`like_give` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeした回数
"`like_receive` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeされた回数
"`lastlikegave` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeした日時
"PRIMARY KEY (`player_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// Like看板データテーブル
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "signs` (" +
"`sign_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てる看板ID
"`sign_name` varchar(32) NOT NULL," + // 看板の名前
"`player_id` int(10) unsigned NOT NULL," + // 所有者のユーザID
"`status` int(2) NOT NULL DEFAULT '0'," + // ステータス値
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`liked` int(12) unsigned NOT NULL DEFAULT '0'," + // Likeカウント
"`lastliked` int(32) unsigned NOT NULL DEFAULT '0'," + // 最後にLikeされた日時
"`world` varchar(255) NOT NULL," + // ワールド名
"`x` int(10) NOT NULL," + // x
"`y` int(10) NOT NULL," + // y
"`z` int(10) NOT NULL," + // z
"PRIMARY KEY (`sign_id`)," +
"UNIQUE KEY `sign_name` (`sign_name`)," +
"KEY `x_y_z` (`x`,`y`,`z`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
// ログデータ
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "likes` (" +
"`like_id` int(12) unsigned NOT NULL AUTO_INCREMENT," + // 割り当てるLikeID
"`player_id` int(10) unsigned NOT NULL," + // プレイヤーID
"`sign_id` int(10) unsigned NOT NULL," + // 対象の看板ID
"`text` varchar(255) DEFAULT NULL," + // メッセージ
"`timestamp` int(32) unsigned NOT NULL," + // タイムスタンプ
"PRIMARY KEY (`like_id`)" +
") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
}
|
diff --git a/web/src/main/java/ar/noxit/ehockey/web/pages/report/ReportePrinterFriendly.java b/web/src/main/java/ar/noxit/ehockey/web/pages/report/ReportePrinterFriendly.java
index 0f39427..5fa5324 100644
--- a/web/src/main/java/ar/noxit/ehockey/web/pages/report/ReportePrinterFriendly.java
+++ b/web/src/main/java/ar/noxit/ehockey/web/pages/report/ReportePrinterFriendly.java
@@ -1,15 +1,15 @@
package ar.noxit.ehockey.web.pages.report;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import ar.noxit.ehockey.model.Jugador;
import ar.noxit.ehockey.service.IJugadorService;
import ar.noxit.ehockey.web.pages.base.AbstractColorLessBasePage;
public class ReportePrinterFriendly extends AbstractColorLessBasePage {
public ReportePrinterFriendly(IModel<Jugador> jugadorModel) {
- add(new JugadorReportePanel("jugadorpanel", jugadorModel));
+ add(new JugadorReportePanel("paneljugador", jugadorModel));
}
}
| true | true | public ReportePrinterFriendly(IModel<Jugador> jugadorModel) {
add(new JugadorReportePanel("jugadorpanel", jugadorModel));
}
| public ReportePrinterFriendly(IModel<Jugador> jugadorModel) {
add(new JugadorReportePanel("paneljugador", jugadorModel));
}
|
diff --git a/src/java/org/catacombae/jfuse/test/FUSE26Test.java b/src/java/org/catacombae/jfuse/test/FUSE26Test.java
index 0eb6f49..bc042a0 100644
--- a/src/java/org/catacombae/jfuse/test/FUSE26Test.java
+++ b/src/java/org/catacombae/jfuse/test/FUSE26Test.java
@@ -1,55 +1,55 @@
/*-
* jFUSE - FUSE bindings for Java
* Copyright (C) 2008-2009 Erik Larsson <[email protected]>
*
* This library 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 library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.catacombae.jfuse.test;
import org.catacombae.jfuse.FUSE26Capabilities;
import org.catacombae.jfuse.FUSE26FileSystemAdapter;
import org.catacombae.jfuse.types.system.LongRef;
import org.catacombae.jfuse.types.system.Stat;
/**
*
* @author erik
*/
public class FUSE26Test {
public static void main(String[] args) {
FUSE26Capabilities c = new FUSE26Capabilities();
//c.print(System.out, "");
FUSE26FileSystemAdapter fs = new Yada() {
@Override
public int getattr(byte[] path, Stat stat) {
return -ENOENT;
}
};
- fs.getCapabilities().print(System.out, "");
+ fs.getFUSECapabilities().print(System.out, "");
}
private static class Yada extends FUSE26FileSystemAdapter {
@Override
public int bmap(byte[] path,
long blocksize,
LongRef idx) {
return -ENOENT;
}
}
}
| true | true | public static void main(String[] args) {
FUSE26Capabilities c = new FUSE26Capabilities();
//c.print(System.out, "");
FUSE26FileSystemAdapter fs = new Yada() {
@Override
public int getattr(byte[] path, Stat stat) {
return -ENOENT;
}
};
fs.getCapabilities().print(System.out, "");
}
| public static void main(String[] args) {
FUSE26Capabilities c = new FUSE26Capabilities();
//c.print(System.out, "");
FUSE26FileSystemAdapter fs = new Yada() {
@Override
public int getattr(byte[] path, Stat stat) {
return -ENOENT;
}
};
fs.getFUSECapabilities().print(System.out, "");
}
|
diff --git a/core/src/main/java/hudson/console/HudsonExceptionNote.java b/core/src/main/java/hudson/console/HudsonExceptionNote.java
index 3800b9484..3ffb7352d 100644
--- a/core/src/main/java/hudson/console/HudsonExceptionNote.java
+++ b/core/src/main/java/hudson/console/HudsonExceptionNote.java
@@ -1,95 +1,96 @@
package hudson.console;
import hudson.Extension;
import hudson.MarkupText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Placed on the beginning of the exception stack trace produced by Hudson, which in turn produces hyperlinked stack trace.
*
* <p>
* Exceptions in the user code (like junit etc) should be handled differently. This is only for exceptions
* that occur inside Hudson.
*
* @author Kohsuke Kawaguchi
* @since 1.349
*/
public class HudsonExceptionNote extends ConsoleNote<Object> {
@Override
public ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) {
// An exception stack trace looks like this:
// org.acme.FooBarException: message
// <TAB>at org.acme.Foo.method(Foo.java:123)
// Caused by: java.lang.ClassNotFoundException:
String line = text.getText();
int end = line.indexOf(':',charPos);
if (end<0) {
if (CLASSNAME.matcher(line.substring(charPos)).matches())
end = line.length();
else
return null; // unexpected format. abort.
}
text.addHyperlink(charPos,end,annotateClassName(line.substring(charPos,end)));
return new ConsoleAnnotator() {
public ConsoleAnnotator annotate(Object context, MarkupText text) {
String line = text.getText();
Matcher m = STACK_TRACE_ELEMENT.matcher(line);
if (m.find()) {// allow the match to happen in the middle of a line to cope with prefix. Ant and Maven put them, among many other tools.
text.addHyperlink(m.start()+4,m.end(),annotateMethodName(m.group(1),m.group(2),m.group(3),Integer.parseInt(m.group(4))));
return this;
}
int idx = line.indexOf(CAUSED_BY);
if (idx>=0) {
int s = idx + CAUSED_BY.length();
int e = line.indexOf(':', s);
+ if (e<0) e = line.length();
text.addHyperlink(s,e,annotateClassName(line.substring(s,e)));
return this;
}
// looks like we are done with the stack trace
return null;
}
};
}
// TODO; separate out the annotations and mark up
private String annotateMethodName(String className, String methodName, String sourceFileName, int lineNumber) {
// for now
return "http://grepcode.com/search/?query="+className+'.'+methodName+"&entity=method";
}
private String annotateClassName(String className) {
// for now
return "http://grepcode.com/search?query="+className;
}
@Extension
public static final class DescriptorImpl extends ConsoleAnnotationDescriptor {
@Override
public String getDisplayName() {
return "Exception Stack Trace";
}
}
/**
* Regular expression that represents a valid class name.
*/
private static final String CLASSNAME_PATTERN = "[\\p{L}0-9$_.]+";
private static final Pattern CLASSNAME = Pattern.compile(CLASSNAME_PATTERN+"\r?\n?");
/**
* Matches to the line like "\tat org.acme.Foo.method(File.java:123)"
* and captures class name, method name, source file name, and line number separately.
*/
private static final Pattern STACK_TRACE_ELEMENT = Pattern.compile("\tat ("+CLASSNAME_PATTERN+")\\.([\\p{L}0-9$_<>]+)\\((\\S+):([0-9]+)\\)");
private static final String CAUSED_BY = "Caused by: ";
}
| true | true | public ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) {
// An exception stack trace looks like this:
// org.acme.FooBarException: message
// <TAB>at org.acme.Foo.method(Foo.java:123)
// Caused by: java.lang.ClassNotFoundException:
String line = text.getText();
int end = line.indexOf(':',charPos);
if (end<0) {
if (CLASSNAME.matcher(line.substring(charPos)).matches())
end = line.length();
else
return null; // unexpected format. abort.
}
text.addHyperlink(charPos,end,annotateClassName(line.substring(charPos,end)));
return new ConsoleAnnotator() {
public ConsoleAnnotator annotate(Object context, MarkupText text) {
String line = text.getText();
Matcher m = STACK_TRACE_ELEMENT.matcher(line);
if (m.find()) {// allow the match to happen in the middle of a line to cope with prefix. Ant and Maven put them, among many other tools.
text.addHyperlink(m.start()+4,m.end(),annotateMethodName(m.group(1),m.group(2),m.group(3),Integer.parseInt(m.group(4))));
return this;
}
int idx = line.indexOf(CAUSED_BY);
if (idx>=0) {
int s = idx + CAUSED_BY.length();
int e = line.indexOf(':', s);
text.addHyperlink(s,e,annotateClassName(line.substring(s,e)));
return this;
}
// looks like we are done with the stack trace
return null;
}
};
}
| public ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) {
// An exception stack trace looks like this:
// org.acme.FooBarException: message
// <TAB>at org.acme.Foo.method(Foo.java:123)
// Caused by: java.lang.ClassNotFoundException:
String line = text.getText();
int end = line.indexOf(':',charPos);
if (end<0) {
if (CLASSNAME.matcher(line.substring(charPos)).matches())
end = line.length();
else
return null; // unexpected format. abort.
}
text.addHyperlink(charPos,end,annotateClassName(line.substring(charPos,end)));
return new ConsoleAnnotator() {
public ConsoleAnnotator annotate(Object context, MarkupText text) {
String line = text.getText();
Matcher m = STACK_TRACE_ELEMENT.matcher(line);
if (m.find()) {// allow the match to happen in the middle of a line to cope with prefix. Ant and Maven put them, among many other tools.
text.addHyperlink(m.start()+4,m.end(),annotateMethodName(m.group(1),m.group(2),m.group(3),Integer.parseInt(m.group(4))));
return this;
}
int idx = line.indexOf(CAUSED_BY);
if (idx>=0) {
int s = idx + CAUSED_BY.length();
int e = line.indexOf(':', s);
if (e<0) e = line.length();
text.addHyperlink(s,e,annotateClassName(line.substring(s,e)));
return this;
}
// looks like we are done with the stack trace
return null;
}
};
}
|
diff --git a/DASA/src/tagger/Tagger.java b/DASA/src/tagger/Tagger.java
index bb55727..acbe7fe 100644
--- a/DASA/src/tagger/Tagger.java
+++ b/DASA/src/tagger/Tagger.java
@@ -1,52 +1,47 @@
package tagger;
import java.io.File;
import java.io.IOException;
import common.FileInOut;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
public class Tagger {
File in;
public Tagger (String path)
{
this.in = new File(path);
}
public String addTags()
{
MaxentTagger tagger = null;
String result = new String ();
try {
- tagger = new MaxentTagger(
- "models/english-bidirectional-distsim.tagger");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ tagger = new MaxentTagger("models/english-bidirectional-distsim.tagger");
+ }
+ finally {
}
try {
result = tagger.tagString(FileInOut.readFile(this.in));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
Tagger newTagger = new Tagger("corpus/test1");
System.out.println(newTagger.addTags());
}
}
| true | true | public String addTags()
{
MaxentTagger tagger = null;
String result = new String ();
try {
tagger = new MaxentTagger(
"models/english-bidirectional-distsim.tagger");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
result = tagger.tagString(FileInOut.readFile(this.in));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
| public String addTags()
{
MaxentTagger tagger = null;
String result = new String ();
try {
tagger = new MaxentTagger("models/english-bidirectional-distsim.tagger");
}
finally {
}
try {
result = tagger.tagString(FileInOut.readFile(this.in));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
|
diff --git a/servicemix-soap/src/main/java/org/apache/servicemix/soap/handlers/security/BaseCrypto.java b/servicemix-soap/src/main/java/org/apache/servicemix/soap/handlers/security/BaseCrypto.java
index e184477ef..676f6555f 100644
--- a/servicemix-soap/src/main/java/org/apache/servicemix/soap/handlers/security/BaseCrypto.java
+++ b/servicemix-soap/src/main/java/org/apache/servicemix/soap/handlers/security/BaseCrypto.java
@@ -1,594 +1,594 @@
/*
* Copyright 2005-2006 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.servicemix.soap.handlers.security;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.X509NameTokenizer;
public abstract class BaseCrypto implements Crypto {
private static final String SKI_OID = "2.5.29.14";
private String provider;
private CertificateFactory certFact;
private String defaultX509Alias;
/**
* @param defaultX509Alias the defaultX509Alias to set
*/
public void setDefaultX509Alias(String defaultX509Alias) {
this.defaultX509Alias = defaultX509Alias;
}
/**
* @return the provider
*/
public String getProvider() {
return provider;
}
/**
* @param provider the provider to set
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Return a X509 Certificate alias in the keystore according to a given Certificate
* <p/>
*
* @param cert The certificate to lookup
* @return alias name of the certificate that matches the given certificate
* or null if no such certificate was found.
*/
public String getAliasForX509Cert(Certificate cert) throws WSSecurityException {
try {
String alias = getCertificateAlias(cert);
if (alias != null)
return alias;
// Use brute force search
String[] allAliases = getAliases();
for (int i = 0; i < allAliases.length; i++) {
Certificate cert2 = getCertificate(alias);
if (cert2.equals(cert)) {
return alias;
}
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
}
/**
* Lookup a X509 Certificate in the keystore according to a given
* the issuer of a Certficate.
* <p/>
* The search gets all alias names of the keystore and gets the certificate chain
* for each alias. Then the Issuer fo each certificate of the chain
* is compared with the parameters.
*
* @param issuer The issuer's name for the certificate
* @return alias name of the certificate that matches the issuer name
* or null if no such certificate was found.
*/
public String getAliasForX509Cert(String issuer) throws WSSecurityException {
return getAliasForX509Cert(issuer, null, false);
}
/**
* Lookup a X509 Certificate in the keystore according to a given
* SubjectKeyIdentifier.
* <p/>
* The search gets all alias names of the keystore and gets the certificate chain
* or certificate for each alias. Then the SKI for each user certificate
* is compared with the SKI parameter.
*
* @param skiBytes The SKI info bytes
* @return alias name of the certificate that matches serialNumber and issuer name
* or null if no such certificate was found.
* @throws org.apache.ws.security.WSSecurityException
* if problems during keystore handling or wrong certificate (no SKI data)
*/
public String getAliasForX509Cert(byte[] skiBytes) throws WSSecurityException {
Certificate cert = null;
try {
String[] allAliases = getAliases();
for (int i = 0; i < allAliases.length; i++) {
String alias = allAliases[i];
cert = getCertificateChainOrCertificate(alias);
if (cert instanceof X509Certificate) {
byte[] data = getSKIBytesFromCert((X509Certificate) cert);
if (Arrays.equals(data, skiBytes)) {
return alias;
}
}
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
}
return null;
}
/**
* Lookup a X509 Certificate in the keystore according to a given serial number and
* the issuer of a Certficate.
* <p/>
* The search gets all alias names of the keystore and gets the certificate chain
* for each alias. Then the SerialNumber and Issuer fo each certificate of the chain
* is compared with the parameters.
*
* @param issuer The issuer's name for the certificate
* @param serialNumber The serial number of the certificate from the named issuer
* @return alias name of the certificate that matches serialNumber and issuer name
* or null if no such certificate was found.
*/
public String getAliasForX509Cert(String issuer, BigInteger serialNumber) throws WSSecurityException {
return getAliasForX509Cert(issuer, serialNumber, true);
}
/**
* Lookup a X509 Certificate in the keystore according to a given
* Thumbprint.
* <p/>
* The search gets all alias names of the keystore, then reads the certificate chain
* or certificate for each alias. Then the thumbprint for each user certificate
* is compared with the thumbprint parameter.
*
* @param thumb The SHA1 thumbprint info bytes
* @return alias name of the certificate that matches the thumbprint
* or null if no such certificate was found.
* @throws org.apache.ws.security.WSSecurityException
* if problems during keystore handling or wrong certificate
*/
public String getAliasForX509CertThumb(byte[] thumb) throws WSSecurityException {
Certificate cert = null;
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e1) {
throw new WSSecurityException(0, "noSHA1availabe");
}
try {
String[] allAliases = getAliases();
for (int i = 0; i < allAliases.length; i++) {
String alias = allAliases[i];
cert = getCertificateChainOrCertificate(alias);
if (cert instanceof X509Certificate) {
sha.reset();
try {
sha.update(cert.getEncoded());
} catch (CertificateEncodingException e1) {
throw new WSSecurityException(
WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"encodeError");
}
byte[] data = sha.digest();
if (Arrays.equals(data, thumb)) {
return alias;
}
}
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
}
/**
* Lookup X509 Certificates in the keystore according to a given DN of the subject of the certificate
* <p/>
* The search gets all alias names of the keystore and gets the certificate (chain)
* for each alias. Then the DN of the certificate is compared with the parameters.
*
* @param subjectDN The DN of subject to look for in the keystore
* @return Vector with all alias of certificates with the same DN as given in the parameters
* @throws org.apache.ws.security.WSSecurityException
*
*/
public String[] getAliasesForDN(String subjectDN) throws WSSecurityException {
// Store the aliases found
Vector aliases = new Vector();
Certificate cert = null;
// The DN to search the keystore for
Vector subjectRDN = splitAndTrim(subjectDN);
// Look at every certificate in the keystore
try {
String[] allAliases = getAliases();
for (int i = 0; i < allAliases.length; i++) {
String alias = allAliases[i];
cert = getCertificateChainOrCertificate(alias);
if (cert instanceof X509Certificate) {
Vector foundRDN = splitAndTrim(((X509Certificate) cert).getSubjectDN().getName());
if (subjectRDN.equals(foundRDN)) {
aliases.add(alias);
}
}
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
}
// Convert the vector into an array
return (String[]) aliases.toArray(new String[aliases.size()]);
}
/**
* get a byte array given an array of X509 certificates.
* <p/>
*
* @param reverse If set the first certificate in the array data will
* the last in the byte array
* @param certs The certificates to convert
* @return The byte array for the certficates ordered according
* to the reverse flag
* @throws WSSecurityException
*/
public byte[] getCertificateData(boolean reverse, X509Certificate[] certs) throws WSSecurityException {
Vector list = new Vector();
for (int i = 0; i < certs.length; i++) {
if (reverse) {
list.insertElementAt(certs[i], 0);
} else {
list.add(certs[i]);
}
}
try {
CertPath path = getCertificateFactory().generateCertPath(list);
return path.getEncoded();
} catch (CertificateEncodingException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"encodeError");
} catch (CertificateException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
}
/**
* Singleton certificate factory for this Crypto instance.
* <p/>
*
* @return Returns a <code>CertificateFactory</code> to construct
* X509 certficates
* @throws org.apache.ws.security.WSSecurityException
*
*/
public synchronized CertificateFactory getCertificateFactory() throws WSSecurityException {
if (certFact == null) {
try {
if (provider == null || provider.length() == 0) {
certFact = CertificateFactory.getInstance("X.509");
} else {
certFact = CertificateFactory.getInstance("X.509", provider);
}
} catch (CertificateException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"unsupportedCertType");
} catch (NoSuchProviderException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"noSecProvider");
}
}
return certFact;
}
/**
* Gets the list of certificates for a given alias.
* <p/>
*
* @param alias Lookup certificate chain for this alias
* @return Array of X509 certificates for this alias name, or
* null if this alias does not exist in the keystore
*/
public X509Certificate[] getCertificates(String alias) throws WSSecurityException {
try {
Certificate[] certs = getCertificateChain(alias);
if (certs != null && certs.length > 0) {
List x509certs = new ArrayList();
for (int i = 0; i < certs.length; i++) {
if (certs[i] instanceof X509Certificate) {
x509certs.add(certs[i]);
}
}
return (X509Certificate[]) x509certs.toArray(new X509Certificate[x509certs.size()]);
}
// no cert chain, so lets check if getCertificate gives us a result.
Certificate cert = getCertificate(alias);
if (cert instanceof X509Certificate) {
return new X509Certificate[] { (X509Certificate) cert };
}
return null;
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
}
}
public String getDefaultX509Alias() {
return defaultX509Alias;
}
public KeyStore getKeyStore() {
return null;
}
/**
* Gets the private key identified by <code>alias</> and <code>password</code>.
* <p/>
*
* @param alias The alias (<code>KeyStore</code>) of the key owner
* @param password The password needed to access the private key
* @return The private key
* @throws Exception
*/
public abstract PrivateKey getPrivateKey(String alias, String password) throws Exception;
/**
* Reads the SubjectKeyIdentifier information from the certificate.
* <p/>
* If the the certificate does not contain a SKI extension then
* try to compute the SKI according to RFC3280 using the
* SHA-1 hash value of the public key. The second method described
* in RFC3280 is not support. Also only RSA public keys are supported.
* If we cannot compute the SKI throw a WSSecurityException.
*
* @param cert The certificate to read SKI
* @return The byte array conating the binary SKI data
*/
public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException {
/*
* Gets the DER-encoded OCTET string for the extension value (extnValue)
* identified by the passed-in oid String. The oid string is represented
* by a set of positive whole numbers separated by periods.
*/
byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);
if (cert.getVersion() < 3 || derEncodedValue == null) {
PublicKey key = cert.getPublicKey();
if (!(key instanceof RSAPublicKey)) {
throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" });
}
byte[] encoded = key.getEncoded();
// remove 22-byte algorithm ID and header
byte[] value = new byte[encoded.length - 22];
System.arraycopy(encoded, 22, value, 0, value.length);
MessageDigest sha;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException ex) {
throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no SHA1 message digest availabe" });
}
sha.reset();
sha.update(value);
return sha.digest();
}
/*
* Strip away first four bytes from the DerValue (tag and length of
* ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
*/
byte abyte0[] = new byte[derEncodedValue.length - 4];
System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
return abyte0;
}
public X509Certificate[] getX509Certificates(byte[] data, boolean reverse) throws WSSecurityException {
InputStream in = new ByteArrayInputStream(data);
CertPath path = null;
try {
path = getCertificateFactory().generateCertPath(in);
} catch (CertificateException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
List l = path.getCertificates();
X509Certificate[] certs = new X509Certificate[l.size()];
Iterator iterator = l.iterator();
for (int i = 0; i < l.size(); i++) {
certs[(reverse) ? (l.size() - 1 - i) : i] = (X509Certificate) iterator.next();
}
return certs;
}
/**
* load a X509Certificate from the input stream.
* <p/>
*
* @param in The <code>InputStream</code> array containg the X509 data
* @return An X509 certificate
* @throws WSSecurityException
*/
public X509Certificate loadCertificate(InputStream in) throws WSSecurityException {
X509Certificate cert = null;
try {
cert = (X509Certificate) getCertificateFactory().generateCertificate(in);
} catch (CertificateException e) {
throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
return cert;
}
/**
* Uses the CertPath API to validate a given certificate chain
* <p/>
*
* @param certs Certificate chain to validate
* @return true if the certificate chain is valid, false otherwise
* @throws WSSecurityException
*/
public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
try {
// Generate cert path
java.util.List certList = java.util.Arrays.asList(certs);
CertPath path = this.getCertificateFactory().generateCertPath(certList);
// Use the certificates in the keystore as TrustAnchors
- Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
+ Set hashSet = new HashSet();
String[] aliases = getTrustCertificates();
for (int i = 0; i < aliases.length; i++) {
Certificate cert = getCertificate(aliases[i]);
if (cert instanceof X509Certificate) {
hashSet.add(new TrustAnchor((X509Certificate) cert, null));
}
}
PKIXParameters param = new PKIXParameters(hashSet);
// Do not check a revocation list
param.setRevocationEnabled(false);
// Verify the trust path using the above settings
CertPathValidator certPathValidator;
if (provider == null || provider.length() == 0) {
certPathValidator = CertPathValidator.getInstance("PKIX");
} else {
certPathValidator = CertPathValidator.getInstance("PKIX", provider);
}
certPathValidator.validate(path, param);
} catch (NoSuchProviderException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (NoSuchAlgorithmException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertificateException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (InvalidAlgorithmParameterException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertPathValidatorException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (KeyStoreException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
}
return true;
}
protected Vector splitAndTrim(String inString) {
X509NameTokenizer nmTokens = new X509NameTokenizer(inString);
Vector vr = new Vector();
while (nmTokens.hasMoreTokens()) {
vr.add(nmTokens.nextToken());
}
java.util.Collections.sort(vr);
return vr;
}
protected Certificate getCertificateChainOrCertificate(String alias) throws KeyStoreException {
Certificate[] certs = getCertificateChain(alias);
Certificate cert = null;
if (certs == null || certs.length == 0) {
// no cert chain, so lets check if getCertificate gives us a result.
cert = getCertificate(alias);
if (cert == null) {
return null;
}
} else {
cert = certs[0];
}
return cert;
}
/*
* need to check if "getCertificateChain" also finds certificates that are
* used for enryption only, i.e. they may not be signed by a CA
* Otherwise we must define a restriction how to use certificate:
* each certificate must be signed by a CA or is a self signed Certificate
* (this should work as well).
* --- remains to be tested in several ways --
*/
private String getAliasForX509Cert(String issuer, BigInteger serialNumber,
boolean useSerialNumber)
throws WSSecurityException {
Vector issuerRDN = splitAndTrim(issuer);
X509Certificate x509cert = null;
Vector certRDN = null;
Certificate cert = null;
try {
String[] allAliases = getAliases();
for (int i = 0; i < allAliases.length; i++) {
String alias = allAliases[i];
cert = getCertificateChainOrCertificate(alias);
if (cert instanceof X509Certificate) {
x509cert = (X509Certificate) cert;
if (!useSerialNumber ||
useSerialNumber && x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
certRDN = splitAndTrim(x509cert.getIssuerDN().getName());
if (certRDN.equals(issuerRDN)) {
return alias;
}
}
}
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
}
protected abstract String[] getAliases() throws KeyStoreException;
protected abstract Certificate[] getCertificateChain(String alias) throws KeyStoreException;
protected abstract Certificate getCertificate(String alias) throws KeyStoreException;
protected abstract String getCertificateAlias(Certificate cert) throws KeyStoreException;
protected abstract String[] getTrustCertificates() throws KeyStoreException;
}
| true | true | public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
try {
// Generate cert path
java.util.List certList = java.util.Arrays.asList(certs);
CertPath path = this.getCertificateFactory().generateCertPath(certList);
// Use the certificates in the keystore as TrustAnchors
Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
String[] aliases = getTrustCertificates();
for (int i = 0; i < aliases.length; i++) {
Certificate cert = getCertificate(aliases[i]);
if (cert instanceof X509Certificate) {
hashSet.add(new TrustAnchor((X509Certificate) cert, null));
}
}
PKIXParameters param = new PKIXParameters(hashSet);
// Do not check a revocation list
param.setRevocationEnabled(false);
// Verify the trust path using the above settings
CertPathValidator certPathValidator;
if (provider == null || provider.length() == 0) {
certPathValidator = CertPathValidator.getInstance("PKIX");
} else {
certPathValidator = CertPathValidator.getInstance("PKIX", provider);
}
certPathValidator.validate(path, param);
} catch (NoSuchProviderException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (NoSuchAlgorithmException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertificateException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (InvalidAlgorithmParameterException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertPathValidatorException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (KeyStoreException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
}
return true;
}
| public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
try {
// Generate cert path
java.util.List certList = java.util.Arrays.asList(certs);
CertPath path = this.getCertificateFactory().generateCertPath(certList);
// Use the certificates in the keystore as TrustAnchors
Set hashSet = new HashSet();
String[] aliases = getTrustCertificates();
for (int i = 0; i < aliases.length; i++) {
Certificate cert = getCertificate(aliases[i]);
if (cert instanceof X509Certificate) {
hashSet.add(new TrustAnchor((X509Certificate) cert, null));
}
}
PKIXParameters param = new PKIXParameters(hashSet);
// Do not check a revocation list
param.setRevocationEnabled(false);
// Verify the trust path using the above settings
CertPathValidator certPathValidator;
if (provider == null || provider.length() == 0) {
certPathValidator = CertPathValidator.getInstance("PKIX");
} else {
certPathValidator = CertPathValidator.getInstance("PKIX", provider);
}
certPathValidator.validate(path, param);
} catch (NoSuchProviderException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (NoSuchAlgorithmException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertificateException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (InvalidAlgorithmParameterException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (CertPathValidatorException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
} catch (KeyStoreException ex) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] { ex.getMessage() },
(Throwable) ex);
}
return true;
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/transform/SimpleGroupCalculator.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/transform/SimpleGroupCalculator.java
index de516e27f..29ff8c3ce 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/transform/SimpleGroupCalculator.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/transform/SimpleGroupCalculator.java
@@ -1,478 +1,481 @@
/*
*************************************************************************
* Copyright (c) 2004, 2011 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.executor.transform;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.birt.core.archive.RAOutputStream;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.aggregation.IProgressiveAggregationHelper;
import org.eclipse.birt.data.engine.executor.cache.RowResultSet;
import org.eclipse.birt.data.engine.executor.transform.group.GroupBy;
import org.eclipse.birt.data.engine.executor.transform.group.GroupInfo;
import org.eclipse.birt.data.engine.impl.DataEngineSession;
import org.eclipse.birt.data.engine.impl.document.stream.StreamManager;
import org.eclipse.birt.data.engine.odi.IAggrInfo;
import org.eclipse.birt.data.engine.odi.IQuery.GroupSpec;
import org.eclipse.birt.data.engine.odi.IResultClass;
import org.eclipse.birt.data.engine.odi.IResultObject;
public class SimpleGroupCalculator implements IGroupCalculator
{
private IResultObject previous;
private IResultObject next;
private IResultObject current;
private GroupBy[] groupBys;
private Integer[] groupInstanceIndex;
private int[] latestAggrAvailableIndex;
private StreamManager streamManager;
private RAOutputStream[] groupOutput;
private RAOutputStream[] aggrRAOutput;
private DataOutputStream[] aggrOutput;
private DataOutputStream[] aggrIndexOutput;
//Output Stream for Overall index + Running index
private RAOutputStream combinedAggrIndexRAOutput;
private DataOutputStream combinedAggrIndexOutput;
private RAOutputStream combinedAggrRAOutput;
private DataOutputStream combinedAggrOutput;
private IProgressiveAggregationHelper aggrHelper;
private List<List<String>> groupAggrs;
private List<String> runningAggrs;
private List<String> overallAggrs;
public SimpleGroupCalculator( DataEngineSession session, GroupSpec[] groups, IResultClass rsMeta ) throws DataException
{
this.groupBys = new GroupBy[groups.length];
this.latestAggrAvailableIndex = new int[groups.length];
Arrays.fill( this.latestAggrAvailableIndex, -1 );
for ( int i = 0; i < groups.length; ++i )
{
int keyIndex = groups[i].getKeyIndex( );
String keyColumn = groups[i].getKeyColumn( );
// Convert group key name to index for faster future access
// assume priority of keyColumn is higher than keyIndex
if ( keyColumn != null )
keyIndex = rsMeta.getFieldIndex( keyColumn );
this.groupBys[i] = GroupBy.newInstance( groups[i],
keyIndex,
keyColumn,
rsMeta.getFieldValueClass( keyIndex ) );
}
this.groupInstanceIndex = new Integer[groupBys.length];
Arrays.fill( this.groupInstanceIndex, 0 );
this.groupAggrs = new ArrayList<List<String>>();
this.runningAggrs = new ArrayList<String>();
this.overallAggrs = new ArrayList<String>();
this.aggrOutput = new DataOutputStream[0];
for( int i = 0; i < groups.length; i++ )
{
this.groupAggrs.add( new ArrayList<String>() );
}
}
public void setAggrHelper( IProgressiveAggregationHelper aggrHelper ) throws DataException
{
this.aggrHelper = aggrHelper;
for ( String aggrName : this.aggrHelper.getAggrNames( ) )
{
IAggrInfo aggrInfo = this.aggrHelper.getAggrInfo( aggrName );
if ( aggrInfo.getAggregation( ).getType( ) == IAggrFunction.RUNNING_AGGR )
{
this.runningAggrs.add( aggrName );
}
else if ( aggrInfo.getGroupLevel( ) == 0 )
{
this.overallAggrs.add( aggrName );
}
else if ( this.aggrHelper.getAggrInfo( aggrName ).getGroupLevel( ) <= this.groupAggrs.size( ) )
{
this.groupAggrs.get( this.aggrHelper.getAggrInfo( aggrName )
.getGroupLevel( ) - 1 ).add( aggrName );
}
}
}
private int getBreakingGroup( IResultObject obj1, IResultObject obj2 ) throws DataException
{
if( obj1 == null )
return 0;
if( obj2 == null )
return 0;
for( int i = 0; i < this.groupBys.length; i++ )
{
int columnIndex = groupBys[i].getColumnIndex( );
if( !groupBys[i].isInSameGroup( obj1.getFieldValue( columnIndex ), obj2.getFieldValue( columnIndex ) ) )
{
return i + 1;
}
}
return this.groupBys.length+1;
}
public int getStartingGroup( ) throws DataException
{
return this.getBreakingGroup( previous, current );
}
public int getEndingGroup( ) throws DataException
{
return this.getBreakingGroup( current, next );
}
public void registerPreviousResultObject( IResultObject previous )
{
this.previous = previous;
}
public void registerCurrentResultObject( IResultObject current )
{
this.current = current;
}
public void registerNextResultObject( RowResultSet rowResultSet ) throws DataException
{
this.next = rowResultSet.getNext( );
}
/**
* Do grouping, and fill group indexes
*
* @param stopsign
* @throws DataException
*/
public void next( int rowId ) throws DataException
{
// breakLevel is the outermost group number to differentiate row
// data
int breakLevel;
if ( this.previous == null )
breakLevel = 0; // Special case for first row
else
breakLevel = getBreakLevel( this.current, this.previous );
//String tobePrint = "";
try
{
// Create a new group in each group level between
// [ breakLevel ... groupDefs.length - 1]
for ( int level = breakLevel; level < groupInstanceIndex.length; level++ )
{
GroupInfo group = new GroupInfo( );
if ( level != 0 )
group.parent = groupInstanceIndex[level - 1] - 1;
if ( level == groupInstanceIndex.length - 1 )
{
// at leaf group level, first child is the first row, which
// is current row
group.firstChild = rowId;
}
else
{
// Our first child is the group to be created at the next
// level
// in the next loop
group.firstChild = groupInstanceIndex[level + 1];
}
groupInstanceIndex[level]++;
if ( this.streamManager != null )
{
IOUtil.writeInt( this.groupOutput[level], group.parent );
IOUtil.writeInt( this.groupOutput[level], group.firstChild );
+ //Add this per report engine's request.
+ //See ted 41188
+ this.groupOutput[level].flush( );
/*tobePrint += "["
+ level + ":" + group.firstChild + ","
+ group.parent + "]";*/
if ( this.previous != null )
{
saveToAggrValuesToDocument( level, rowId );
}
}
}
this.aggrHelper.onRow( this.getStartingGroup( ), this.getEndingGroup( ), this.current, rowId);
if ( this.runningAggrs.size( ) > 0 )
{
for ( String aggrName : this.runningAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput,
this.aggrHelper.getLatestAggrValue( aggrName ) );
}
IOUtil.writeLong( this.combinedAggrIndexOutput,
this.combinedAggrRAOutput.getOffset( ) );
}
if ( this.next == null )
{
for ( int i = 0; i < this.aggrOutput.length; i++ )
{
saveToAggrValuesToDocument( i, rowId );
}
if( this.overallAggrs.size( ) > 0 && this.combinedAggrIndexOutput!= null )
{
this.combinedAggrIndexRAOutput.seek( 0 );
IOUtil.writeLong( this.combinedAggrIndexOutput, this.combinedAggrRAOutput.getOffset( ) );
for( String aggrName: overallAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput, this.aggrHelper.getLatestAggrValue( aggrName ) );
}
}
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
/*if ( !tobePrint.isEmpty( ) )
System.out.println( tobePrint );
*/
}
private void saveToAggrValuesToDocument( int i , int rowId) throws IOException,
DataException
{
if ( this.aggrOutput[i] != null )
{
for ( String aggrName : this.groupAggrs.get( i ) )
{
IOUtil.writeObject( this.aggrOutput[i],
this.aggrHelper.getLatestAggrValue( aggrName ) );
}
if ( this.aggrIndexOutput[i] != null )
{
IOUtil.writeLong( this.aggrIndexOutput[i],
this.aggrRAOutput[i].getOffset( ) );
}
}
this.latestAggrAvailableIndex[i] = rowId-1;
}
/**
* Helper method to get the group break level between 2 rows
*
* @param currRow
* @param prevRow
* @return
* @throws DataException
*/
private int getBreakLevel( IResultObject currRow, IResultObject prevRow) throws DataException
{
assert currRow != null;
assert prevRow != null;
int breakLevel = 0;
for ( ; breakLevel < this.groupBys.length; breakLevel++ )
{
int colIndex = this.groupBys[breakLevel].getColumnIndex( );
Object currObjectValue = null;
Object prevObjectValue = null;
if ( colIndex >= 0 )
{
currObjectValue = currRow.getFieldValue( colIndex );
prevObjectValue = prevRow.getFieldValue( colIndex );
}
GroupBy groupBy = this.groupBys[breakLevel];
if ( !groupBy.isInSameGroup( currObjectValue, prevObjectValue ) )
{
//current group is the break level
//reset the groupBys of the inner groups within current group for the following compare
for (int i = breakLevel + 1; i < this.groupBys.length; i++)
{
this.groupBys[i].reset( );
}
break;
}
}
return breakLevel;
}
public void close( ) throws DataException
{
try
{
if ( this.groupOutput!= null )
{
for( int i = 0; i < this.groupOutput.length; i++ )
{
this.groupOutput[i].seek( 0 );
IOUtil.writeInt( this.groupOutput[i], this.groupInstanceIndex[i] );
this.groupOutput[i].close( );
}
this.groupOutput = null;
}
if ( this.aggrOutput!= null )
{
for( int i = 0; i < this.aggrOutput.length; i++ )
{
if( this.aggrOutput[i]!= null )
this.aggrOutput[i].close( );
}
this.aggrOutput = null;
}
if ( this.aggrIndexOutput!= null )
{
for( int i = 0; i < this.aggrIndexOutput.length; i++ )
{
if( this.aggrIndexOutput[i]!= null )
this.aggrIndexOutput[i].close( );
}
this.aggrIndexOutput = null;
}
if( this.overallAggrs.size( ) > 0 && this.combinedAggrIndexOutput!= null )
{
this.combinedAggrIndexRAOutput.close( );
this.combinedAggrOutput.close( );
}
if( this.aggrHelper!= null )
{
this.aggrHelper.close( );
this.aggrHelper = null;
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
}
public void doSave( StreamManager manager ) throws DataException
{
try {
this.streamManager = manager;
if (this.streamManager != null) {
this.groupOutput = new RAOutputStream[this.groupBys.length];
this.aggrOutput = new DataOutputStream[this.groupBys.length];
this.aggrRAOutput = new RAOutputStream[this.groupBys.length];
this.aggrIndexOutput = new DataOutputStream[this.groupBys.length];
if (this.overallAggrs.size() > 0
|| this.runningAggrs.size() > 0) {
this.combinedAggrIndexRAOutput = (RAOutputStream) streamManager
.getOutStream(
DataEngineContext.COMBINED_AGGR_INDEX_STREAM,
StreamManager.ROOT_STREAM,
StreamManager.BASE_SCOPE);
this.combinedAggrRAOutput = (RAOutputStream) streamManager
.getOutStream(
DataEngineContext.COMBINED_AGGR_VALUE_STREAM,
StreamManager.ROOT_STREAM,
StreamManager.BASE_SCOPE);
this.combinedAggrOutput = new DataOutputStream(
this.combinedAggrRAOutput);
this.combinedAggrIndexOutput = new DataOutputStream(
this.combinedAggrIndexRAOutput);
// write place holder for Overall aggregation index
IOUtil.writeLong(this.combinedAggrIndexOutput, -1);
// write the size of overall aggregation
IOUtil.writeInt(this.combinedAggrOutput,
this.overallAggrs.size());
for (int i = 0; i < this.overallAggrs.size(); i++) {
IOUtil.writeString(this.combinedAggrOutput,
this.overallAggrs.get(i));
}
IOUtil.writeInt(this.combinedAggrOutput,
this.runningAggrs.size());
for (int i = 0; i < this.runningAggrs.size(); i++) {
IOUtil.writeString(this.combinedAggrOutput,
this.runningAggrs.get(i));
}
// write the starting index of first running aggregation
IOUtil.writeLong(this.combinedAggrIndexOutput,
this.combinedAggrRAOutput.getOffset());
}
for (int i = 0; i < this.groupBys.length; i++) {
this.groupOutput[i] = (RAOutputStream) streamManager
.getOutStream(
DataEngineContext.PROGRESSIVE_VIEWING_GROUP_STREAM,
i);
IOUtil.writeInt(this.groupOutput[i], Integer.MAX_VALUE);
if (!this.groupAggrs.get(i).isEmpty()) {
this.aggrRAOutput[i] = streamManager.getOutStream(
DataEngineContext.AGGR_VALUE_STREAM, i);
this.aggrIndexOutput[i] = new DataOutputStream(
streamManager.getOutStream(
DataEngineContext.AGGR_INDEX_STREAM, i));
this.aggrOutput[i] = new DataOutputStream(
this.aggrRAOutput[i]);
// The group level
IOUtil.writeInt(this.aggrOutput[i], i + 1);
// The number of aggregations in the group
IOUtil.writeInt(this.aggrOutput[i], this.groupAggrs
.get(i).size());
for (String aggrName : this.groupAggrs.get(i)) {
IOUtil.writeString(new DataOutputStream(
this.aggrOutput[i]), aggrName);
}
IOUtil.writeLong(this.aggrIndexOutput[i],
this.aggrRAOutput[i].getOffset());
}
}
}
} catch (IOException e) {
throw new DataException(e.getLocalizedMessage(), e);
}
}
public boolean isAggrAtIndexAvailable( String aggrName, int currentIndex ) throws DataException
{
assert this.aggrHelper!= null;
if( this.aggrHelper.getAggrInfo( aggrName ).getAggregation( ).getType( ) == IAggrFunction.RUNNING_AGGR )
return true;
if( this.aggrHelper.getAggrInfo( aggrName ).getGroupLevel( ) == 0 )
return this.current == null;
return this.latestAggrAvailableIndex[this.aggrHelper.getAggrInfo( aggrName ).getGroupLevel( )-1] >= currentIndex;
}
public Integer[] getGroupInstanceIndex()
{
return this.groupInstanceIndex;
}
}
| true | true | public void next( int rowId ) throws DataException
{
// breakLevel is the outermost group number to differentiate row
// data
int breakLevel;
if ( this.previous == null )
breakLevel = 0; // Special case for first row
else
breakLevel = getBreakLevel( this.current, this.previous );
//String tobePrint = "";
try
{
// Create a new group in each group level between
// [ breakLevel ... groupDefs.length - 1]
for ( int level = breakLevel; level < groupInstanceIndex.length; level++ )
{
GroupInfo group = new GroupInfo( );
if ( level != 0 )
group.parent = groupInstanceIndex[level - 1] - 1;
if ( level == groupInstanceIndex.length - 1 )
{
// at leaf group level, first child is the first row, which
// is current row
group.firstChild = rowId;
}
else
{
// Our first child is the group to be created at the next
// level
// in the next loop
group.firstChild = groupInstanceIndex[level + 1];
}
groupInstanceIndex[level]++;
if ( this.streamManager != null )
{
IOUtil.writeInt( this.groupOutput[level], group.parent );
IOUtil.writeInt( this.groupOutput[level], group.firstChild );
/*tobePrint += "["
+ level + ":" + group.firstChild + ","
+ group.parent + "]";*/
if ( this.previous != null )
{
saveToAggrValuesToDocument( level, rowId );
}
}
}
this.aggrHelper.onRow( this.getStartingGroup( ), this.getEndingGroup( ), this.current, rowId);
if ( this.runningAggrs.size( ) > 0 )
{
for ( String aggrName : this.runningAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput,
this.aggrHelper.getLatestAggrValue( aggrName ) );
}
IOUtil.writeLong( this.combinedAggrIndexOutput,
this.combinedAggrRAOutput.getOffset( ) );
}
if ( this.next == null )
{
for ( int i = 0; i < this.aggrOutput.length; i++ )
{
saveToAggrValuesToDocument( i, rowId );
}
if( this.overallAggrs.size( ) > 0 && this.combinedAggrIndexOutput!= null )
{
this.combinedAggrIndexRAOutput.seek( 0 );
IOUtil.writeLong( this.combinedAggrIndexOutput, this.combinedAggrRAOutput.getOffset( ) );
for( String aggrName: overallAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput, this.aggrHelper.getLatestAggrValue( aggrName ) );
}
}
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
/*if ( !tobePrint.isEmpty( ) )
System.out.println( tobePrint );
*/
}
| public void next( int rowId ) throws DataException
{
// breakLevel is the outermost group number to differentiate row
// data
int breakLevel;
if ( this.previous == null )
breakLevel = 0; // Special case for first row
else
breakLevel = getBreakLevel( this.current, this.previous );
//String tobePrint = "";
try
{
// Create a new group in each group level between
// [ breakLevel ... groupDefs.length - 1]
for ( int level = breakLevel; level < groupInstanceIndex.length; level++ )
{
GroupInfo group = new GroupInfo( );
if ( level != 0 )
group.parent = groupInstanceIndex[level - 1] - 1;
if ( level == groupInstanceIndex.length - 1 )
{
// at leaf group level, first child is the first row, which
// is current row
group.firstChild = rowId;
}
else
{
// Our first child is the group to be created at the next
// level
// in the next loop
group.firstChild = groupInstanceIndex[level + 1];
}
groupInstanceIndex[level]++;
if ( this.streamManager != null )
{
IOUtil.writeInt( this.groupOutput[level], group.parent );
IOUtil.writeInt( this.groupOutput[level], group.firstChild );
//Add this per report engine's request.
//See ted 41188
this.groupOutput[level].flush( );
/*tobePrint += "["
+ level + ":" + group.firstChild + ","
+ group.parent + "]";*/
if ( this.previous != null )
{
saveToAggrValuesToDocument( level, rowId );
}
}
}
this.aggrHelper.onRow( this.getStartingGroup( ), this.getEndingGroup( ), this.current, rowId);
if ( this.runningAggrs.size( ) > 0 )
{
for ( String aggrName : this.runningAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput,
this.aggrHelper.getLatestAggrValue( aggrName ) );
}
IOUtil.writeLong( this.combinedAggrIndexOutput,
this.combinedAggrRAOutput.getOffset( ) );
}
if ( this.next == null )
{
for ( int i = 0; i < this.aggrOutput.length; i++ )
{
saveToAggrValuesToDocument( i, rowId );
}
if( this.overallAggrs.size( ) > 0 && this.combinedAggrIndexOutput!= null )
{
this.combinedAggrIndexRAOutput.seek( 0 );
IOUtil.writeLong( this.combinedAggrIndexOutput, this.combinedAggrRAOutput.getOffset( ) );
for( String aggrName: overallAggrs )
{
IOUtil.writeObject( this.combinedAggrOutput, this.aggrHelper.getLatestAggrValue( aggrName ) );
}
}
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
/*if ( !tobePrint.isEmpty( ) )
System.out.println( tobePrint );
*/
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/analytics/dao/SurveyQuestionSummaryDao.java b/GAE/src/org/waterforpeople/mapping/analytics/dao/SurveyQuestionSummaryDao.java
index 9c2fa3b92..a090a1a3a 100644
--- a/GAE/src/org/waterforpeople/mapping/analytics/dao/SurveyQuestionSummaryDao.java
+++ b/GAE/src/org/waterforpeople/mapping/analytics/dao/SurveyQuestionSummaryDao.java
@@ -1,99 +1,102 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.analytics.dao;
import java.util.List;
import javax.jdo.PersistenceManager;
import org.waterforpeople.mapping.analytics.domain.SurveyQuestionSummary;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.servlet.PersistenceFilter;
/**
* updates survey question objects
*
* @author Christopher Fagiani
*
*/
public class SurveyQuestionSummaryDao extends BaseDAO<SurveyQuestionSummary> {
public SurveyQuestionSummaryDao() {
super(SurveyQuestionSummary.class);
}
/**
* synchronized static method so that only 1 thread can be updating a
* summary at a time. This is inefficient but is the only way we can be sure
* we're keeping the count consistent since there is no "select for update"
* or sql dml-like construct
*
* @param answer
*/
@SuppressWarnings("rawtypes")
public static synchronized void incrementCount(QuestionAnswerStore answer,
int unit) {
PersistenceManager pm = PersistenceFilter.getManager();
String answerText = answer.getValue();
String[] answers;
if (answerText != null && answerText.contains("|")) {
answers = answerText.split("\\|");
} else {
answers = new String[] { answerText };
}
for (int i = 0; i < answers.length; i++) {
+ // find surveyQuestionSummary objects with the right question id and answer text
javax.jdo.Query query = pm.newQuery(SurveyQuestionSummary.class);
query
.setFilter("questionId == questionIdParam && response == answerParam");
query
.declareParameters("String questionIdParam, String answerParam");
List results = (List) query.execute(answer.getQuestionID(),
answers[i]);
SurveyQuestionSummary summary = null;
if ((results == null || results.size() == 0) && unit > 0) {
+ // no previous surveyQuestionSummary for this answer, make a new one
summary = new SurveyQuestionSummary();
summary.setCount(new Long(unit));
summary.setQuestionId(answer.getQuestionID());
summary.setResponse(answers[i]);
} else if (results != null && results.size() > 0) {
+ // update an existing questionAnswerSummary
summary = (SurveyQuestionSummary) results.get(0);
summary.setCount(summary.getCount() + unit);
}
if (summary != null) {
+ // if we have updated or created a surveyQuestionSummary, save it
SurveyQuestionSummaryDao summaryDao = new SurveyQuestionSummaryDao();
if (summary.getCount() > 0) {
summaryDao.save(summary);
} else if (summary.getKey() != null) {
// if count has been decremented to 0 and the object is
- // already
- // persisted, delete it
+ // already persisted, delete it
summaryDao.delete(summary);
}
}
}
}
/**
* this method will list all the summary objects for a given question id
*/
public List<SurveyQuestionSummary> listByQuestion(String qId) {
return listByProperty("questionId", qId, "String");
}
}
| false | true | public static synchronized void incrementCount(QuestionAnswerStore answer,
int unit) {
PersistenceManager pm = PersistenceFilter.getManager();
String answerText = answer.getValue();
String[] answers;
if (answerText != null && answerText.contains("|")) {
answers = answerText.split("\\|");
} else {
answers = new String[] { answerText };
}
for (int i = 0; i < answers.length; i++) {
javax.jdo.Query query = pm.newQuery(SurveyQuestionSummary.class);
query
.setFilter("questionId == questionIdParam && response == answerParam");
query
.declareParameters("String questionIdParam, String answerParam");
List results = (List) query.execute(answer.getQuestionID(),
answers[i]);
SurveyQuestionSummary summary = null;
if ((results == null || results.size() == 0) && unit > 0) {
summary = new SurveyQuestionSummary();
summary.setCount(new Long(unit));
summary.setQuestionId(answer.getQuestionID());
summary.setResponse(answers[i]);
} else if (results != null && results.size() > 0) {
summary = (SurveyQuestionSummary) results.get(0);
summary.setCount(summary.getCount() + unit);
}
if (summary != null) {
SurveyQuestionSummaryDao summaryDao = new SurveyQuestionSummaryDao();
if (summary.getCount() > 0) {
summaryDao.save(summary);
} else if (summary.getKey() != null) {
// if count has been decremented to 0 and the object is
// already
// persisted, delete it
summaryDao.delete(summary);
}
}
}
}
| public static synchronized void incrementCount(QuestionAnswerStore answer,
int unit) {
PersistenceManager pm = PersistenceFilter.getManager();
String answerText = answer.getValue();
String[] answers;
if (answerText != null && answerText.contains("|")) {
answers = answerText.split("\\|");
} else {
answers = new String[] { answerText };
}
for (int i = 0; i < answers.length; i++) {
// find surveyQuestionSummary objects with the right question id and answer text
javax.jdo.Query query = pm.newQuery(SurveyQuestionSummary.class);
query
.setFilter("questionId == questionIdParam && response == answerParam");
query
.declareParameters("String questionIdParam, String answerParam");
List results = (List) query.execute(answer.getQuestionID(),
answers[i]);
SurveyQuestionSummary summary = null;
if ((results == null || results.size() == 0) && unit > 0) {
// no previous surveyQuestionSummary for this answer, make a new one
summary = new SurveyQuestionSummary();
summary.setCount(new Long(unit));
summary.setQuestionId(answer.getQuestionID());
summary.setResponse(answers[i]);
} else if (results != null && results.size() > 0) {
// update an existing questionAnswerSummary
summary = (SurveyQuestionSummary) results.get(0);
summary.setCount(summary.getCount() + unit);
}
if (summary != null) {
// if we have updated or created a surveyQuestionSummary, save it
SurveyQuestionSummaryDao summaryDao = new SurveyQuestionSummaryDao();
if (summary.getCount() > 0) {
summaryDao.save(summary);
} else if (summary.getKey() != null) {
// if count has been decremented to 0 and the object is
// already persisted, delete it
summaryDao.delete(summary);
}
}
}
}
|
diff --git a/src/org/newdawn/slick/util/pathfinding/AStarPathFinder.java b/src/org/newdawn/slick/util/pathfinding/AStarPathFinder.java
index e1442ad..4bbcae0 100644
--- a/src/org/newdawn/slick/util/pathfinding/AStarPathFinder.java
+++ b/src/org/newdawn/slick/util/pathfinding/AStarPathFinder.java
@@ -1,568 +1,568 @@
package org.newdawn.slick.util.pathfinding;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.newdawn.slick.util.pathfinding.heuristics.ClosestHeuristic;
/**
* A path finder implementation that uses the AStar heuristic based algorithm
* to determine a path.
*
* @author Kevin Glass
*/
public class AStarPathFinder implements PathFinder, PathFindingContext {
/** The set of nodes that have been searched through */
private ArrayList closed = new ArrayList();
/** The set of nodes that we do not yet consider fully searched */
private PriorityList open = new PriorityList();
/** The map being searched */
private TileBasedMap map;
/** The maximum depth of search we're willing to accept before giving up */
private int maxSearchDistance;
/** The complete set of nodes across the map */
private Node[][] nodes;
/** True if we allow diaganol movement */
private boolean allowDiagMovement;
/** The heuristic we're applying to determine which nodes to search first */
private AStarHeuristic heuristic;
/** The node we're currently searching from */
private Node current;
/** The mover going through the path */
private Mover mover;
/** The x coordinate of the source tile we're moving from */
private int sourceX;
/** The y coordinate of the source tile we're moving from */
private int sourceY;
/** The distance searched so far */
private int distance;
/**
* Create a path finder with the default heuristic - closest to target.
*
* @param map The map to be searched
* @param maxSearchDistance The maximum depth we'll search before giving up
* @param allowDiagMovement True if the search should try diaganol movement
*/
public AStarPathFinder(TileBasedMap map, int maxSearchDistance, boolean allowDiagMovement) {
this(map, maxSearchDistance, allowDiagMovement, new ClosestHeuristic());
}
/**
* Create a path finder
*
* @param heuristic The heuristic used to determine the search order of the map
* @param map The map to be searched
* @param maxSearchDistance The maximum depth we'll search before giving up
* @param allowDiagMovement True if the search should try diaganol movement
*/
public AStarPathFinder(TileBasedMap map, int maxSearchDistance,
boolean allowDiagMovement, AStarHeuristic heuristic) {
this.heuristic = heuristic;
this.map = map;
this.maxSearchDistance = maxSearchDistance;
this.allowDiagMovement = allowDiagMovement;
nodes = new Node[map.getWidthInTiles()][map.getHeightInTiles()];
for (int x=0;x<map.getWidthInTiles();x++) {
for (int y=0;y<map.getHeightInTiles();y++) {
nodes[x][y] = new Node(x,y);
}
}
}
/**
* @see PathFinder#findPath(Mover, int, int, int, int)
*/
public Path findPath(Mover mover, int sx, int sy, int tx, int ty) {
current = null;
// easy first check, if the destination is blocked, we can't get there
this.mover = mover;
- this.sourceX = sx;
- this.sourceY = sy;
+ this.sourceX = tx;
+ this.sourceY = ty;
this.distance = 0;
if (map.blocked(this, tx, ty)) {
return null;
}
for (int x=0;x<map.getWidthInTiles();x++) {
for (int y=0;y<map.getHeightInTiles();y++) {
nodes[x][y].reset();
}
}
// initial state for A*. The closed group is empty. Only the starting
// tile is in the open list and it's cost is zero, i.e. we're already there
nodes[sx][sy].cost = 0;
nodes[sx][sy].depth = 0;
closed.clear();
open.clear();
addToOpen(nodes[sx][sy]);
nodes[tx][ty].parent = null;
// while we haven't found the goal and haven't exceeded our max search depth
int maxDepth = 0;
while ((maxDepth < maxSearchDistance) && (open.size() != 0)) {
// pull out the first node in our open list, this is determined to
// be the most likely to be the next step based on our heuristic
current = getFirstInOpen();
if (current == nodes[tx][ty]) {
break;
}
distance = current.depth;
removeFromOpen(current);
addToClosed(current);
// search through all the neighbours of the current node evaluating
// them as next steps
for (int x=-1;x<2;x++) {
for (int y=-1;y<2;y++) {
// not a neighbour, its the current tile
if ((x == 0) && (y == 0)) {
continue;
}
// if we're not allowing diaganol movement then only
// one of x or y can be set
if (!allowDiagMovement) {
if ((x != 0) && (y != 0)) {
continue;
}
}
// determine the location of the neighbour and evaluate it
int xp = x + current.x;
int yp = y + current.y;
- if (isValidLocation(mover,sx,sy,xp,yp)) {
+ if (isValidLocation(mover,current.x,current.y,xp,yp)) {
// the cost to get to this node is cost the current plus the movement
// cost to reach this node. Note that the heursitic value is only used
// in the sorted open list
float nextStepCost = current.cost + getMovementCost(mover, current.x, current.y, xp, yp);
Node neighbour = nodes[xp][yp];
map.pathFinderVisited(xp, yp);
// if the new cost we've determined for this node is lower than
// it has been previously makes sure the node hasn't been discarded. We've
// determined that there might have been a better path to get to
// this node so it needs to be re-evaluated
if (nextStepCost < neighbour.cost) {
if (inOpenList(neighbour)) {
removeFromOpen(neighbour);
}
if (inClosedList(neighbour)) {
removeFromClosed(neighbour);
}
}
// if the node hasn't already been processed and discarded then
// reset it's cost to our current cost and add it as a next possible
// step (i.e. to the open list)
if (!inOpenList(neighbour) && !(inClosedList(neighbour))) {
neighbour.cost = nextStepCost;
neighbour.heuristic = getHeuristicCost(mover, xp, yp, tx, ty);
maxDepth = Math.max(maxDepth, neighbour.setParent(current));
addToOpen(neighbour);
}
}
}
}
}
// since we've got an empty open list or we've run out of search
// there was no path. Just return null
if (nodes[tx][ty].parent == null) {
return null;
}
// At this point we've definitely found a path so we can uses the parent
// references of the nodes to find out way from the target location back
// to the start recording the nodes on the way.
Path path = new Path();
Node target = nodes[tx][ty];
while (target != nodes[sx][sy]) {
path.prependStep(target.x, target.y);
target = target.parent;
}
path.prependStep(sx,sy);
// thats it, we have our path
return path;
}
/**
* Get the X coordinate of the node currently being evaluated
*
* @return The X coordinate of the node currently being evaluated
*/
public int getCurrentX() {
if (current == null) {
return -1;
}
return current.x;
}
/**
* Get the Y coordinate of the node currently being evaluated
*
* @return The Y coordinate of the node currently being evaluated
*/
public int getCurrentY() {
if (current == null) {
return -1;
}
return current.y;
}
/**
* Get the first element from the open list. This is the next
* one to be searched.
*
* @return The first element in the open list
*/
protected Node getFirstInOpen() {
return (Node) open.first();
}
/**
* Add a node to the open list
*
* @param node The node to be added to the open list
*/
protected void addToOpen(Node node) {
node.setOpen(true);
open.add(node);
}
/**
* Check if a node is in the open list
*
* @param node The node to check for
* @return True if the node given is in the open list
*/
protected boolean inOpenList(Node node) {
return node.isOpen();
}
/**
* Remove a node from the open list
*
* @param node The node to remove from the open list
*/
protected void removeFromOpen(Node node) {
node.setOpen(false);
open.remove(node);
}
/**
* Add a node to the closed list
*
* @param node The node to add to the closed list
*/
protected void addToClosed(Node node) {
node.setClosed(true);
closed.add(node);
}
/**
* Check if the node supplied is in the closed list
*
* @param node The node to search for
* @return True if the node specified is in the closed list
*/
protected boolean inClosedList(Node node) {
return node.isClosed();
}
/**
* Remove a node from the closed list
*
* @param node The node to remove from the closed list
*/
protected void removeFromClosed(Node node) {
node.setClosed(false);
closed.remove(node);
}
/**
* Check if a given location is valid for the supplied mover
*
* @param mover The mover that would hold a given location
* @param sx The starting x coordinate
* @param sy The starting y coordinate
* @param x The x coordinate of the location to check
* @param y The y coordinate of the location to check
* @return True if the location is valid for the given mover
*/
protected boolean isValidLocation(Mover mover, int sx, int sy, int x, int y) {
boolean invalid = (x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles());
if ((!invalid) && ((sx != x) || (sy != y))) {
this.mover = mover;
this.sourceX = sx;
this.sourceY = sy;
invalid = map.blocked(this, x, y);
}
return !invalid;
}
/**
* Get the cost to move through a given location
*
* @param mover The entity that is being moved
* @param sx The x coordinate of the tile whose cost is being determined
* @param sy The y coordiante of the tile whose cost is being determined
* @param tx The x coordinate of the target location
* @param ty The y coordinate of the target location
* @return The cost of movement through the given tile
*/
public float getMovementCost(Mover mover, int sx, int sy, int tx, int ty) {
this.mover = mover;
this.sourceX = sx;
this.sourceY = sy;
return map.getCost(this, tx, ty);
}
/**
* Get the heuristic cost for the given location. This determines in which
* order the locations are processed.
*
* @param mover The entity that is being moved
* @param x The x coordinate of the tile whose cost is being determined
* @param y The y coordiante of the tile whose cost is being determined
* @param tx The x coordinate of the target location
* @param ty The y coordinate of the target location
* @return The heuristic cost assigned to the tile
*/
public float getHeuristicCost(Mover mover, int x, int y, int tx, int ty) {
return heuristic.getCost(map, mover, x, y, tx, ty);
}
/**
* A list that sorts any element provided into the list
*
* @author kevin
*/
private class PriorityList {
/** The list of elements */
private List list = new LinkedList();
/**
* Retrieve the first element from the list
*
* @return The first element from the list
*/
public Object first() {
return list.get(0);
}
/**
* Empty the list
*/
public void clear() {
list.clear();
}
/**
* Add an element to the list - causes sorting
*
* @param o The element to add
*/
public void add(Object o) {
// float the new entry
for (int i=0;i<list.size();i++) {
if (((Comparable) list.get(i)).compareTo(o) > 0) {
list.add(i, o);
break;
}
}
if (!list.contains(o)) {
list.add(o);
}
//Collections.sort(list);
}
/**
* Remove an element from the list
*
* @param o The element to remove
*/
public void remove(Object o) {
list.remove(o);
}
/**
* Get the number of elements in the list
*
* @return The number of element in the list
*/
public int size() {
return list.size();
}
/**
* Check if an element is in the list
*
* @param o The element to search for
* @return True if the element is in the list
*/
public boolean contains(Object o) {
return list.contains(o);
}
public String toString() {
String temp = "{";
for (int i=0;i<size();i++) {
temp += list.get(i).toString()+",";
}
temp += "}";
return temp;
}
}
/**
* A single node in the search graph
*/
private class Node implements Comparable {
/** The x coordinate of the node */
private int x;
/** The y coordinate of the node */
private int y;
/** The path cost for this node */
private float cost;
/** The parent of this node, how we reached it in the search */
private Node parent;
/** The heuristic cost of this node */
private float heuristic;
/** The search depth of this node */
private int depth;
/** In the open list */
private boolean open;
/** In the closed list */
private boolean closed;
/**
* Create a new node
*
* @param x The x coordinate of the node
* @param y The y coordinate of the node
*/
public Node(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Set the parent of this node
*
* @param parent The parent node which lead us to this node
* @return The depth we have no reached in searching
*/
public int setParent(Node parent) {
depth = parent.depth + 1;
this.parent = parent;
return depth;
}
/**
* @see Comparable#compareTo(Object)
*/
public int compareTo(Object other) {
Node o = (Node) other;
float f = heuristic + cost;
float of = o.heuristic + o.cost;
if (f < of) {
return -1;
} else if (f > of) {
return 1;
} else {
return 0;
}
}
/**
* Indicate whether the node is in the open list
*
* @param open True if the node is in the open list
*/
public void setOpen(boolean open) {
this.open = open;
}
/**
* Check if the node is in the open list
*
* @return True if the node is in the open list
*/
public boolean isOpen() {
return open;
}
/**
* Indicate whether the node is in the closed list
*
* @param closed True if the node is in the closed list
*/
public void setClosed(boolean closed) {
this.closed = closed;
}
/**
* Check if the node is in the closed list
*
* @return True if the node is in the closed list
*/
public boolean isClosed() {
return closed;
}
/**
* Reset the state of this node
*/
public void reset() {
closed = false;
open = false;
cost = 0;
depth = 0;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return "[Node "+x+","+y+"]";
}
}
public Mover getMover() {
return mover;
}
public int getSearchDistance() {
return distance;
}
public int getSourceX() {
return sourceX;
}
public int getSourceY() {
return sourceY;
}
}
| false | true | public Path findPath(Mover mover, int sx, int sy, int tx, int ty) {
current = null;
// easy first check, if the destination is blocked, we can't get there
this.mover = mover;
this.sourceX = sx;
this.sourceY = sy;
this.distance = 0;
if (map.blocked(this, tx, ty)) {
return null;
}
for (int x=0;x<map.getWidthInTiles();x++) {
for (int y=0;y<map.getHeightInTiles();y++) {
nodes[x][y].reset();
}
}
// initial state for A*. The closed group is empty. Only the starting
// tile is in the open list and it's cost is zero, i.e. we're already there
nodes[sx][sy].cost = 0;
nodes[sx][sy].depth = 0;
closed.clear();
open.clear();
addToOpen(nodes[sx][sy]);
nodes[tx][ty].parent = null;
// while we haven't found the goal and haven't exceeded our max search depth
int maxDepth = 0;
while ((maxDepth < maxSearchDistance) && (open.size() != 0)) {
// pull out the first node in our open list, this is determined to
// be the most likely to be the next step based on our heuristic
current = getFirstInOpen();
if (current == nodes[tx][ty]) {
break;
}
distance = current.depth;
removeFromOpen(current);
addToClosed(current);
// search through all the neighbours of the current node evaluating
// them as next steps
for (int x=-1;x<2;x++) {
for (int y=-1;y<2;y++) {
// not a neighbour, its the current tile
if ((x == 0) && (y == 0)) {
continue;
}
// if we're not allowing diaganol movement then only
// one of x or y can be set
if (!allowDiagMovement) {
if ((x != 0) && (y != 0)) {
continue;
}
}
// determine the location of the neighbour and evaluate it
int xp = x + current.x;
int yp = y + current.y;
if (isValidLocation(mover,sx,sy,xp,yp)) {
// the cost to get to this node is cost the current plus the movement
// cost to reach this node. Note that the heursitic value is only used
// in the sorted open list
float nextStepCost = current.cost + getMovementCost(mover, current.x, current.y, xp, yp);
Node neighbour = nodes[xp][yp];
map.pathFinderVisited(xp, yp);
// if the new cost we've determined for this node is lower than
// it has been previously makes sure the node hasn't been discarded. We've
// determined that there might have been a better path to get to
// this node so it needs to be re-evaluated
if (nextStepCost < neighbour.cost) {
if (inOpenList(neighbour)) {
removeFromOpen(neighbour);
}
if (inClosedList(neighbour)) {
removeFromClosed(neighbour);
}
}
// if the node hasn't already been processed and discarded then
// reset it's cost to our current cost and add it as a next possible
// step (i.e. to the open list)
if (!inOpenList(neighbour) && !(inClosedList(neighbour))) {
neighbour.cost = nextStepCost;
neighbour.heuristic = getHeuristicCost(mover, xp, yp, tx, ty);
maxDepth = Math.max(maxDepth, neighbour.setParent(current));
addToOpen(neighbour);
}
}
}
}
}
// since we've got an empty open list or we've run out of search
// there was no path. Just return null
if (nodes[tx][ty].parent == null) {
return null;
}
// At this point we've definitely found a path so we can uses the parent
// references of the nodes to find out way from the target location back
// to the start recording the nodes on the way.
Path path = new Path();
Node target = nodes[tx][ty];
while (target != nodes[sx][sy]) {
path.prependStep(target.x, target.y);
target = target.parent;
}
path.prependStep(sx,sy);
// thats it, we have our path
return path;
}
| public Path findPath(Mover mover, int sx, int sy, int tx, int ty) {
current = null;
// easy first check, if the destination is blocked, we can't get there
this.mover = mover;
this.sourceX = tx;
this.sourceY = ty;
this.distance = 0;
if (map.blocked(this, tx, ty)) {
return null;
}
for (int x=0;x<map.getWidthInTiles();x++) {
for (int y=0;y<map.getHeightInTiles();y++) {
nodes[x][y].reset();
}
}
// initial state for A*. The closed group is empty. Only the starting
// tile is in the open list and it's cost is zero, i.e. we're already there
nodes[sx][sy].cost = 0;
nodes[sx][sy].depth = 0;
closed.clear();
open.clear();
addToOpen(nodes[sx][sy]);
nodes[tx][ty].parent = null;
// while we haven't found the goal and haven't exceeded our max search depth
int maxDepth = 0;
while ((maxDepth < maxSearchDistance) && (open.size() != 0)) {
// pull out the first node in our open list, this is determined to
// be the most likely to be the next step based on our heuristic
current = getFirstInOpen();
if (current == nodes[tx][ty]) {
break;
}
distance = current.depth;
removeFromOpen(current);
addToClosed(current);
// search through all the neighbours of the current node evaluating
// them as next steps
for (int x=-1;x<2;x++) {
for (int y=-1;y<2;y++) {
// not a neighbour, its the current tile
if ((x == 0) && (y == 0)) {
continue;
}
// if we're not allowing diaganol movement then only
// one of x or y can be set
if (!allowDiagMovement) {
if ((x != 0) && (y != 0)) {
continue;
}
}
// determine the location of the neighbour and evaluate it
int xp = x + current.x;
int yp = y + current.y;
if (isValidLocation(mover,current.x,current.y,xp,yp)) {
// the cost to get to this node is cost the current plus the movement
// cost to reach this node. Note that the heursitic value is only used
// in the sorted open list
float nextStepCost = current.cost + getMovementCost(mover, current.x, current.y, xp, yp);
Node neighbour = nodes[xp][yp];
map.pathFinderVisited(xp, yp);
// if the new cost we've determined for this node is lower than
// it has been previously makes sure the node hasn't been discarded. We've
// determined that there might have been a better path to get to
// this node so it needs to be re-evaluated
if (nextStepCost < neighbour.cost) {
if (inOpenList(neighbour)) {
removeFromOpen(neighbour);
}
if (inClosedList(neighbour)) {
removeFromClosed(neighbour);
}
}
// if the node hasn't already been processed and discarded then
// reset it's cost to our current cost and add it as a next possible
// step (i.e. to the open list)
if (!inOpenList(neighbour) && !(inClosedList(neighbour))) {
neighbour.cost = nextStepCost;
neighbour.heuristic = getHeuristicCost(mover, xp, yp, tx, ty);
maxDepth = Math.max(maxDepth, neighbour.setParent(current));
addToOpen(neighbour);
}
}
}
}
}
// since we've got an empty open list or we've run out of search
// there was no path. Just return null
if (nodes[tx][ty].parent == null) {
return null;
}
// At this point we've definitely found a path so we can uses the parent
// references of the nodes to find out way from the target location back
// to the start recording the nodes on the way.
Path path = new Path();
Node target = nodes[tx][ty];
while (target != nodes[sx][sy]) {
path.prependStep(target.x, target.y);
target = target.parent;
}
path.prependStep(sx,sy);
// thats it, we have our path
return path;
}
|
diff --git a/lib/java/src/protocol/TProtocolUtil.java b/lib/java/src/protocol/TProtocolUtil.java
index 0b85d38b..5c665ab0 100644
--- a/lib/java/src/protocol/TProtocolUtil.java
+++ b/lib/java/src/protocol/TProtocolUtil.java
@@ -1,104 +1,104 @@
// Copyright (c) 2006- Facebook
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
package com.facebook.thrift.protocol;
import com.facebook.thrift.TException;
import com.facebook.thrift.transport.TTransport;
/**
* Utility class with static methods for interacting with protocol data
* streams.
*
* @author Mark Slee <[email protected]>
*/
public class TProtocolUtil {
public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
- prot.readString();
+ prot.readBinary();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
}
| true | true | public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readString();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
| public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readBinary();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
|
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index c0ae559a..757c279e 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -1,2294 +1,2294 @@
/*
* Copyright (C) 2007 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.providers.settings;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.media.AudioManager;
import android.media.AudioService;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.content.PackageHelper;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.RILConstants;
import com.android.internal.util.XmlUtils;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockPatternView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
/**
* Database helper class for {@link SettingsProvider}.
* Mostly just has a bit {@link #onCreate} to initialize the database.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "SettingsProvider";
private static final String DATABASE_NAME = "settings.db";
// Please, please please. If you update the database version, check to make sure the
// database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
// is properly propagated through your change. Not doing so will result in a loss of user
// settings.
private static final int DATABASE_VERSION = 95;
private Context mContext;
private int mUserHandle;
private static final HashSet<String> mValidTables = new HashSet<String>();
private static final String TABLE_SYSTEM = "system";
private static final String TABLE_SECURE = "secure";
private static final String TABLE_GLOBAL = "global";
static {
mValidTables.add(TABLE_SYSTEM);
mValidTables.add(TABLE_SECURE);
mValidTables.add(TABLE_GLOBAL);
mValidTables.add("bluetooth_devices");
mValidTables.add("bookmarks");
// These are old.
mValidTables.add("favorites");
mValidTables.add("gservices");
mValidTables.add("old_favorites");
}
static String dbNameForUser(final int userHandle) {
// The owner gets the unadorned db name;
if (userHandle == UserHandle.USER_OWNER) {
return DATABASE_NAME;
} else {
// Place the database in the user-specific data tree so that it's
// cleaned up automatically when the user is deleted.
File databaseFile = new File(
Environment.getUserSystemDirectory(userHandle), DATABASE_NAME);
return databaseFile.getPath();
}
}
public DatabaseHelper(Context context, int userHandle) {
super(context, dbNameForUser(userHandle), null, DATABASE_VERSION);
mContext = context;
mUserHandle = userHandle;
}
public static boolean isValidTable(String name) {
return mValidTables.contains(name);
}
private void createSecureTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE secure (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE ON CONFLICT REPLACE," +
"value TEXT" +
");");
db.execSQL("CREATE INDEX secureIndex1 ON secure (name);");
}
private void createGlobalTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE global (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE ON CONFLICT REPLACE," +
"value TEXT" +
");");
db.execSQL("CREATE INDEX globalIndex1 ON global (name);");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE system (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE ON CONFLICT REPLACE," +
"value TEXT" +
");");
db.execSQL("CREATE INDEX systemIndex1 ON system (name);");
createSecureTable(db);
// Only create the global table for the singleton 'owner' user
if (mUserHandle == UserHandle.USER_OWNER) {
createGlobalTable(db);
}
db.execSQL("CREATE TABLE bluetooth_devices (" +
"_id INTEGER PRIMARY KEY," +
"name TEXT," +
"addr TEXT," +
"channel INTEGER," +
"type INTEGER" +
");");
db.execSQL("CREATE TABLE bookmarks (" +
"_id INTEGER PRIMARY KEY," +
"title TEXT," +
"folder TEXT," +
"intent TEXT," +
"shortcut INTEGER," +
"ordering INTEGER" +
");");
db.execSQL("CREATE INDEX bookmarksIndex1 ON bookmarks (folder);");
db.execSQL("CREATE INDEX bookmarksIndex2 ON bookmarks (shortcut);");
// Populate bookmarks table with initial bookmarks
boolean onlyCore = false;
try {
onlyCore = IPackageManager.Stub.asInterface(ServiceManager.getService(
"package")).isOnlyCoreApps();
} catch (RemoteException e) {
}
if (!onlyCore) {
loadBookmarks(db);
}
// Load initial volume levels into DB
loadVolumeLevels(db);
// Load inital settings values
loadSettings(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
Log.w(TAG, "Upgrading settings database from version " + oldVersion + " to "
+ currentVersion);
int upgradeVersion = oldVersion;
// Pattern for upgrade blocks:
//
// if (upgradeVersion == [the DATABASE_VERSION you set] - 1) {
// .. your upgrade logic..
// upgradeVersion = [the DATABASE_VERSION you set]
// }
if (upgradeVersion == 20) {
/*
* Version 21 is part of the volume control refresh. There is no
* longer a UI-visible for setting notification vibrate on/off (in
* our design), but the functionality still exists. Force the
* notification vibrate to on.
*/
loadVibrateSetting(db, true);
upgradeVersion = 21;
}
if (upgradeVersion < 22) {
upgradeVersion = 22;
// Upgrade the lock gesture storage location and format
upgradeLockPatternLocation(db);
}
if (upgradeVersion < 23) {
db.execSQL("UPDATE favorites SET iconResource=0 WHERE iconType=0");
upgradeVersion = 23;
}
if (upgradeVersion == 23) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD spanX INTEGER");
db.execSQL("ALTER TABLE favorites ADD spanY INTEGER");
// Shortcuts, applications, folders
db.execSQL("UPDATE favorites SET spanX=1, spanY=1 WHERE itemType<=0");
// Photo frames, clocks
db.execSQL(
"UPDATE favorites SET spanX=2, spanY=2 WHERE itemType=1000 or itemType=1002");
// Search boxes
db.execSQL("UPDATE favorites SET spanX=4, spanY=1 WHERE itemType=1001");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 24;
}
if (upgradeVersion == 24) {
db.beginTransaction();
try {
// The value of the constants for preferring wifi or preferring mobile have been
// swapped, so reload the default.
db.execSQL("DELETE FROM system WHERE name='network_preference'");
db.execSQL("INSERT INTO system ('name', 'value') values ('network_preference', '" +
ConnectivityManager.DEFAULT_NETWORK_PREFERENCE + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 25;
}
if (upgradeVersion == 25) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD uri TEXT");
db.execSQL("ALTER TABLE favorites ADD displayMode INTEGER");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 26;
}
if (upgradeVersion == 26) {
// This introduces the new secure settings table.
db.beginTransaction();
try {
createSecureTable(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 27;
}
if (upgradeVersion == 27) {
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.ANDROID_ID,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.HTTP_PROXY,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Settings.Secure.LOGGING_ID,
Settings.Secure.NETWORK_PREFERENCE,
Settings.Secure.PARENTAL_CONTROL_ENABLED,
Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
Settings.Secure.PARENTAL_CONTROL_REDIRECT_URL,
Settings.Secure.SETTINGS_CLASSNAME,
Settings.Secure.USB_MASS_STORAGE_ENABLED,
Settings.Secure.USE_GOOGLE_MAIL,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT,
Settings.Secure.WIFI_ON,
Settings.Secure.WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE,
Settings.Secure.WIFI_WATCHDOG_AP_COUNT,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS,
Settings.Secure.WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_MAX_AP_CHECKS,
Settings.Secure.WIFI_WATCHDOG_ON,
Settings.Secure.WIFI_WATCHDOG_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 28;
}
if (upgradeVersion == 28 || upgradeVersion == 29) {
// Note: The upgrade to 28 was flawed since it didn't delete the old
// setting first before inserting. Combining 28 and 29 with the
// fixed version.
// This upgrade adds the STREAM_NOTIFICATION type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 30;
}
if (upgradeVersion == 30) {
/*
* Upgrade 31 clears the title for all quick launch shortcuts so the
* activities' titles will be resolved at display time. Also, the
* folder is changed to '@quicklaunch'.
*/
db.beginTransaction();
try {
db.execSQL("UPDATE bookmarks SET folder = '@quicklaunch'");
db.execSQL("UPDATE bookmarks SET title = ''");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 31;
}
if (upgradeVersion == 31) {
/*
* Animations are now managed in preferences, and may be
* enabled or disabled based on product resources.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 32;
}
if (upgradeVersion == 32) {
// The Wi-Fi watchdog SSID list is now seeded with the value of
// the property ro.com.android.wifi-watchlist
String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
if (!TextUtils.isEmpty(wifiWatchList)) {
db.beginTransaction();
try {
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Secure.WIFI_WATCHDOG_WATCH_LIST + "','" +
wifiWatchList + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 33;
}
if (upgradeVersion == 33) {
// Set the default zoom controls to: tap-twice to bring up +/-
db.beginTransaction();
try {
db.execSQL("INSERT INTO system(name,value) values('zoom','2');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 34;
}
if (upgradeVersion == 34) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSecure35Settings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 35;
}
// due to a botched merge from donut to eclair, the initialization of ASSISTED_GPS_ENABLED
// was accidentally done out of order here.
// to fix this, ASSISTED_GPS_ENABLED is now initialized while upgrading from 38 to 39,
// and we intentionally do nothing from 35 to 36 now.
if (upgradeVersion == 35) {
upgradeVersion = 36;
}
if (upgradeVersion == 36) {
// This upgrade adds the STREAM_SYSTEM_ENFORCED type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 37;
}
if (upgradeVersion == 37) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 38;
}
if (upgradeVersion == 38) {
db.beginTransaction();
try {
String value =
mContext.getResources().getBoolean(R.bool.assisted_gps_enabled) ? "1" : "0";
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Global.ASSISTED_GPS_ENABLED + "','" + value + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 39;
}
if (upgradeVersion == 39) {
upgradeAutoBrightness(db);
upgradeVersion = 40;
}
if (upgradeVersion == 40) {
/*
* All animations are now turned on by default!
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 41;
}
if (upgradeVersion == 41) {
/*
* Initialize newly public haptic feedback setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.HAPTIC_FEEDBACK_ENABLED + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultHapticSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 42;
}
if (upgradeVersion == 42) {
/*
* Initialize new notification pulse setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
R.bool.def_notification_pulse);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 43;
}
if (upgradeVersion == 43) {
/*
* This upgrade stores bluetooth volume separately from voice volume
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VOLUME_BLUETOOTH_SCO,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 44;
}
if (upgradeVersion == 44) {
/*
* Gservices was moved into vendor/google.
*/
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
upgradeVersion = 45;
}
if (upgradeVersion == 45) {
/*
* New settings for MountService
*/
db.beginTransaction();
try {
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_AUTOSTART + "','0');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_PROMPT + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED + "','1');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 46;
}
if (upgradeVersion == 46) {
/*
* The password mode constants have changed; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 47;
}
if (upgradeVersion == 47) {
/*
* The password mode constants have changed again; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 48;
}
if (upgradeVersion == 48) {
/*
* Default recognition service no longer initialized here,
* moved to RecognitionManagerService.
*/
upgradeVersion = 49;
}
if (upgradeVersion == 49) {
/*
* New settings for new user interface noises.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadUISoundEffectsSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 50;
}
if (upgradeVersion == 50) {
/*
* Install location no longer initiated here.
*/
upgradeVersion = 51;
}
if (upgradeVersion == 51) {
/* Move the lockscreen related settings to Secure, including some private ones. */
String[] settingsToMove = {
Secure.LOCK_PATTERN_ENABLED,
Secure.LOCK_PATTERN_VISIBLE,
Secure.LOCK_SHOW_ERROR_PATH,
Secure.LOCK_DOTS_VISIBLE,
Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED,
"lockscreen.password_type",
"lockscreen.lockoutattemptdeadline",
"lockscreen.patterneverchosen",
"lock_pattern_autolock",
"lockscreen.lockedoutpermanently",
"lockscreen.password_salt"
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 52;
}
if (upgradeVersion == 52) {
// new vibration/silent mode settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 53;
}
if (upgradeVersion == 53) {
/*
* New settings for set install location UI no longer initiated here.
*/
upgradeVersion = 54;
}
if (upgradeVersion == 54) {
/*
* Update the screen timeout value if set to never
*/
db.beginTransaction();
try {
upgradeScreenTimeoutFromNever(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 55;
}
if (upgradeVersion == 55) {
/* Move the install location settings. */
String[] settingsToMove = {
Global.SET_INSTALL_LOCATION,
Global.DEFAULT_INSTALL_LOCATION
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Global.SET_INSTALL_LOCATION, 0);
loadSetting(stmt, Global.DEFAULT_INSTALL_LOCATION,
PackageHelper.APP_INSTALL_AUTO);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 56;
}
if (upgradeVersion == 56) {
/*
* Add Bluetooth to list of toggleable radios in airplane mode
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 57;
}
/************* The following are Honeycomb changes ************/
if (upgradeVersion == 57) {
/*
* New settings to:
* 1. Enable injection of accessibility scripts in WebViews.
* 2. Define the key bindings for traversing web content in WebViews.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION,
R.bool.def_accessibility_script_injection);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_WEB_CONTENT_KEY_BINDINGS,
R.string.def_accessibility_web_content_key_bindings);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 58;
}
if (upgradeVersion == 58) {
/* Add default for new Auto Time Zone */
- int autoTimeValue = getIntValueFromSystem(db, Settings.System.AUTO_TIME, 0);
+ int autoTimeValue = getIntValueFromSystem(db, Settings.Global.AUTO_TIME, 0);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)" + " VALUES(?,?);");
- loadSetting(stmt, Settings.System.AUTO_TIME_ZONE,
+ loadSetting(stmt, Settings.Global.AUTO_TIME_ZONE,
autoTimeValue); // Sync timezone to NITZ if auto_time was enabled
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 59;
}
if (upgradeVersion == 59) {
// Persistence for the rotation lock feature.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.USER_ROTATION,
R.integer.def_user_rotation); // should be zero degrees
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 60;
}
if (upgradeVersion == 60) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 61;
}
if (upgradeVersion == 61) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 62;
}
// Change the default for screen auto-brightness mode
if (upgradeVersion == 62) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeAutoBrightness(db);
upgradeVersion = 63;
}
if (upgradeVersion == 63) {
// This upgrade adds the STREAM_MUSIC type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED)
| (1 << AudioManager.STREAM_MUSIC);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 64;
}
if (upgradeVersion == 64) {
// New setting to configure the long press timeout.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
R.integer.def_long_press_timeout_millis);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 65;
}
/************* The following are Ice Cream Sandwich changes ************/
if (upgradeVersion == 65) {
/*
* Animations are removed from Settings. Turned on by default
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 66;
}
if (upgradeVersion == 66) {
// This upgrade makes sure that MODE_RINGER_STREAMS_AFFECTED is set
// according to device voice capability
db.beginTransaction();
try {
int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM) |
(1 << AudioManager.STREAM_SYSTEM_ENFORCED);
if (!mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable)) {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(ringerModeAffectedStreams) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 67;
}
if (upgradeVersion == 67) {
// New setting to enable touch exploration.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
R.bool.def_touch_exploration_enabled);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 68;
}
if (upgradeVersion == 68) {
// Enable all system sounds by default
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.NOTIFICATIONS_USE_RING_VOLUME + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 69;
}
if (upgradeVersion == 69) {
// Add RADIO_NFC to AIRPLANE_MODE_RADIO and AIRPLANE_MODE_TOGGLEABLE_RADIOS
String airplaneRadios = mContext.getResources().getString(
R.string.def_airplane_mode_radios);
String toggleableRadios = mContext.getResources().getString(
R.string.airplane_mode_toggleable_radios);
db.beginTransaction();
try {
db.execSQL("UPDATE system SET value='" + airplaneRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_RADIOS + "'");
db.execSQL("UPDATE system SET value='" + toggleableRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 70;
}
if (upgradeVersion == 70) {
// Update all built-in bookmarks. Some of the package names have changed.
loadBookmarks(db);
upgradeVersion = 71;
}
if (upgradeVersion == 71) {
// New setting to specify whether to speak passwords in accessibility mode.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
R.bool.def_accessibility_speak_password);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 72;
}
if (upgradeVersion == 72) {
// update vibration settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 73;
}
if (upgradeVersion == 73) {
upgradeVibrateSettingFromNone(db);
upgradeVersion = 74;
}
if (upgradeVersion == 74) {
// URL from which WebView loads a JavaScript based screen-reader.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 75;
}
if (upgradeVersion == 75) {
db.beginTransaction();
SQLiteStatement stmt = null;
Cursor c = null;
try {
c = db.query(TABLE_SECURE, new String[] {"_id", "value"},
"name='lockscreen.disabled'",
null, null, null, null);
// only set default if it has not yet been set
if (c == null || c.getCount() == 0) {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
R.bool.def_lockscreen_disabled);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (c != null) c.close();
if (stmt != null) stmt.close();
}
upgradeVersion = 76;
}
/************* The following are Jelly Bean changes ************/
if (upgradeVersion == 76) {
// Removed VIBRATE_IN_SILENT setting
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.VIBRATE_IN_SILENT + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 77;
}
if (upgradeVersion == 77) {
// Introduce "vibrate when ringing" setting
loadVibrateWhenRingingSetting(db);
upgradeVersion = 78;
}
if (upgradeVersion == 78) {
// The JavaScript based screen-reader URL changes in JellyBean.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 79;
}
if (upgradeVersion == 79) {
// Before touch exploration was a global setting controlled by the user
// via the UI. However, if the enabled accessibility services do not
// handle touch exploration mode, enabling it makes no sense. Therefore,
// now the services request touch exploration mode and the user is
// presented with a dialog to allow that and if she does we store that
// in the database. As a result of this change a user that has enabled
// accessibility, touch exploration, and some accessibility services
// may lose touch exploration state, thus rendering the device useless
// unless sighted help is provided, since the enabled service(s) are
// not in the list of services to which the user granted a permission
// to put the device in touch explore mode. Here we are allowing all
// enabled accessibility services to toggle touch exploration provided
// accessibility and touch exploration are enabled and no services can
// toggle touch exploration. Note that the user has already manually
// enabled the services and touch exploration which means the she has
// given consent to have these services work in touch exploration mode.
final boolean accessibilityEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;
final boolean touchExplorationEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0) == 1;
if (accessibilityEnabled && touchExplorationEnabled) {
String enabledServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
String touchExplorationGrantedServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, "");
if (TextUtils.isEmpty(touchExplorationGrantedServices)
&& !TextUtils.isEmpty(enabledServices)) {
SQLiteStatement stmt = null;
try {
db.beginTransaction();
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
enabledServices);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
}
upgradeVersion = 80;
}
// vvv Jelly Bean MR1 changes begin here vvv
if (upgradeVersion == 80) {
// update screensaver settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
com.android.internal.R.bool.config_dreamsEnabledByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
com.android.internal.R.string.config_dreamsDefaultComponent);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
com.android.internal.R.string.config_dreamsDefaultComponent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 81;
}
if (upgradeVersion == 81) {
// Add package verification setting
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Global.PACKAGE_VERIFIER_ENABLE,
R.bool.def_package_verifier_enable);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 82;
}
if (upgradeVersion == 82) {
// Move to per-user settings dbs
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings. Note that this happens before
// new users can be created.
createGlobalTable(db);
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, false);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, false);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 83;
}
if (upgradeVersion == 83) {
// 1. Setting whether screen magnification is enabled.
// 2. Setting for screen magnification scale.
// 3. Setting for screen magnification auto update.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
R.bool.def_accessibility_display_magnification_enabled);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
R.fraction.def_accessibility_display_magnification_scale, 1);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE,
R.bool.def_accessibility_display_magnification_auto_update);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 84;
}
if (upgradeVersion == 84) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Patch up the slightly-wrong key migration from 82 -> 83 for those
// devices that missed it, ignoring if the move is redundant
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.USB_MASS_STORAGE_ENABLED
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 85;
}
if (upgradeVersion == 85) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Fix up the migration, ignoring already-migrated elements, to snap up to
// date with new changes to the set of global versus system/secure settings
String[] settingsToMove = { Settings.System.STAY_ON_WHILE_PLUGGED_IN };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 86;
}
if (upgradeVersion == 86) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.PACKAGE_VERIFIER_ENABLE,
Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 87;
}
if (upgradeVersion == 87) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.GPRS_REGISTER_CHECK_PERIOD_MS
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 88;
}
if (upgradeVersion == 88) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD,
Settings.Global.BATTERY_DISCHARGE_THRESHOLD,
Settings.Global.SEND_ACTION_APP_ERROR,
Settings.Global.DROPBOX_AGE_SECONDS,
Settings.Global.DROPBOX_MAX_FILES,
Settings.Global.DROPBOX_QUOTA_KB,
Settings.Global.DROPBOX_QUOTA_PERCENT,
Settings.Global.DROPBOX_RESERVE_PERCENT,
Settings.Global.DROPBOX_TAG_PREFIX,
Settings.Global.ERROR_LOGCAT_PREFIX,
Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE,
Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES,
Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED,
Settings.Global.CAPTIVE_PORTAL_SERVER,
Settings.Global.NSD_ON,
Settings.Global.SET_INSTALL_LOCATION,
Settings.Global.DEFAULT_INSTALL_LOCATION,
Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY,
Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY,
Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT,
Settings.Global.HTTP_PROXY,
Settings.Global.GLOBAL_HTTP_PROXY_HOST,
Settings.Global.GLOBAL_HTTP_PROXY_PORT,
Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Settings.Global.SET_GLOBAL_HTTP_PROXY,
Settings.Global.DEFAULT_DNS_SERVER,
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 89;
}
if (upgradeVersion == 89) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] prefixesToMove = {
Settings.Global.BLUETOOTH_HEADSET_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_A2DP_SINK_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_INPUT_DEVICE_PRIORITY_PREFIX,
};
movePrefixedSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, prefixesToMove);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 90;
}
if (upgradeVersion == 90) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] systemToGlobal = {
Settings.Global.WINDOW_ANIMATION_SCALE,
Settings.Global.TRANSITION_ANIMATION_SCALE,
Settings.Global.ANIMATOR_DURATION_SCALE,
Settings.Global.FANCY_IME_ANIMATIONS,
Settings.Global.COMPATIBILITY_MODE,
Settings.Global.EMERGENCY_TONE,
Settings.Global.CALL_AUTO_RETRY,
Settings.Global.DEBUG_APP,
Settings.Global.WAIT_FOR_DEBUGGER,
Settings.Global.SHOW_PROCESSES,
Settings.Global.ALWAYS_FINISH_ACTIVITIES,
};
String[] secureToGlobal = {
Settings.Global.PREFERRED_NETWORK_MODE,
Settings.Global.PREFERRED_CDMA_SUBSCRIPTION,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, systemToGlobal, true);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, secureToGlobal, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 91;
}
if (upgradeVersion == 91) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Move ringer mode from system to global settings
String[] settingsToMove = { Settings.Global.MODE_RINGER };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 92;
}
if (upgradeVersion == 92) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
if (mUserHandle == UserHandle.USER_OWNER) {
// consider existing primary users to have made it through user setup
// if the globally-scoped device-provisioned bit is set
// (indicating they already made it through setup as primary)
int deviceProvisioned = getIntValueFromTable(db, TABLE_GLOBAL,
Settings.Global.DEVICE_PROVISIONED, 0);
loadSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
deviceProvisioned);
} else {
// otherwise use the default
loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
R.bool.def_user_setup_complete);
}
} finally {
if (stmt != null) stmt.close();
}
upgradeVersion = 93;
}
if (upgradeVersion == 93) {
// Redo this step, since somehow it didn't work the first time for some users
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 94;
}
if (upgradeVersion == 94) {
// Add wireless charging started sound setting
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Global.WIRELESS_CHARGING_STARTED_SOUND,
R.string.def_wireless_charging_started_sound);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 95;
}
// *** Remember to update DATABASE_VERSION above!
if (upgradeVersion != currentVersion) {
Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
+ ", must wipe the settings provider");
db.execSQL("DROP TABLE IF EXISTS global");
db.execSQL("DROP TABLE IF EXISTS globalIndex1");
db.execSQL("DROP TABLE IF EXISTS system");
db.execSQL("DROP INDEX IF EXISTS systemIndex1");
db.execSQL("DROP TABLE IF EXISTS secure");
db.execSQL("DROP INDEX IF EXISTS secureIndex1");
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
db.execSQL("DROP TABLE IF EXISTS bluetooth_devices");
db.execSQL("DROP TABLE IF EXISTS bookmarks");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex1");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex2");
db.execSQL("DROP TABLE IF EXISTS favorites");
onCreate(db);
// Added for diagnosing settings.db wipes after the fact
String wipeReason = oldVersion + "/" + upgradeVersion + "/" + currentVersion;
db.execSQL("INSERT INTO secure(name,value) values('" +
"wiped_db_reason" + "','" + wipeReason + "');");
}
}
private String[] hashsetToStringArray(HashSet<String> set) {
String[] array = new String[set.size()];
return set.toArray(array);
}
private void moveSettingsToNewTable(SQLiteDatabase db,
String sourceTable, String destTable,
String[] settingsToMove, boolean doIgnore) {
// Copy settings values from the source table to the dest, and remove from the source
SQLiteStatement insertStmt = null;
SQLiteStatement deleteStmt = null;
db.beginTransaction();
try {
insertStmt = db.compileStatement("INSERT "
+ (doIgnore ? " OR IGNORE " : "")
+ " INTO " + destTable + " (name,value) SELECT name,value FROM "
+ sourceTable + " WHERE name=?");
deleteStmt = db.compileStatement("DELETE FROM " + sourceTable + " WHERE name=?");
for (String setting : settingsToMove) {
insertStmt.bindString(1, setting);
insertStmt.execute();
deleteStmt.bindString(1, setting);
deleteStmt.execute();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (insertStmt != null) {
insertStmt.close();
}
if (deleteStmt != null) {
deleteStmt.close();
}
}
}
/**
* Move any settings with the given prefixes from the source table to the
* destination table.
*/
private void movePrefixedSettingsToNewTable(
SQLiteDatabase db, String sourceTable, String destTable, String[] prefixesToMove) {
SQLiteStatement insertStmt = null;
SQLiteStatement deleteStmt = null;
db.beginTransaction();
try {
insertStmt = db.compileStatement("INSERT INTO " + destTable
+ " (name,value) SELECT name,value FROM " + sourceTable
+ " WHERE substr(name,0,?)=?");
deleteStmt = db.compileStatement(
"DELETE FROM " + sourceTable + " WHERE substr(name,0,?)=?");
for (String prefix : prefixesToMove) {
insertStmt.bindLong(1, prefix.length() + 1);
insertStmt.bindString(2, prefix);
insertStmt.execute();
deleteStmt.bindLong(1, prefix.length() + 1);
deleteStmt.bindString(2, prefix);
deleteStmt.execute();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (insertStmt != null) {
insertStmt.close();
}
if (deleteStmt != null) {
deleteStmt.close();
}
}
}
private void upgradeLockPatternLocation(SQLiteDatabase db) {
Cursor c = db.query(TABLE_SYSTEM, new String[] {"_id", "value"}, "name='lock_pattern'",
null, null, null, null);
if (c.getCount() > 0) {
c.moveToFirst();
String lockPattern = c.getString(1);
if (!TextUtils.isEmpty(lockPattern)) {
// Convert lock pattern
try {
LockPatternUtils lpu = new LockPatternUtils(mContext);
List<LockPatternView.Cell> cellPattern =
lpu.stringToPattern(lockPattern);
lpu.saveLockPattern(cellPattern);
} catch (IllegalArgumentException e) {
// Don't want corrupted lock pattern to hang the reboot process
}
}
c.close();
db.delete(TABLE_SYSTEM, "name='lock_pattern'", null);
} else {
c.close();
}
}
private void upgradeScreenTimeoutFromNever(SQLiteDatabase db) {
// See if the timeout is -1 (for "Never").
Cursor c = db.query(TABLE_SYSTEM, new String[] { "_id", "value" }, "name=? AND value=?",
new String[] { Settings.System.SCREEN_OFF_TIMEOUT, "-1" },
null, null, null);
SQLiteStatement stmt = null;
if (c.getCount() > 0) {
c.close();
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
// Set the timeout to 30 minutes in milliseconds
loadSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
Integer.toString(30 * 60 * 1000));
} finally {
if (stmt != null) stmt.close();
}
} else {
c.close();
}
}
private void upgradeVibrateSettingFromNone(SQLiteDatabase db) {
int vibrateSetting = getIntValueFromSystem(db, Settings.System.VIBRATE_ON, 0);
// If the ringer vibrate value is invalid, set it to the default
if ((vibrateSetting & 3) == AudioManager.VIBRATE_SETTING_OFF) {
vibrateSetting = AudioService.getValueForVibrateSetting(0,
AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ONLY_SILENT);
}
// Apply the same setting to the notification vibrate value
vibrateSetting = AudioService.getValueForVibrateSetting(vibrateSetting,
AudioManager.VIBRATE_TYPE_NOTIFICATION, vibrateSetting);
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VIBRATE_ON, vibrateSetting);
} finally {
if (stmt != null)
stmt.close();
}
}
private void upgradeScreenTimeout(SQLiteDatabase db) {
// Change screen timeout to current default
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
R.integer.def_screen_off_timeout);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null)
stmt.close();
}
}
private void upgradeAutoBrightness(SQLiteDatabase db) {
db.beginTransaction();
try {
String value =
mContext.getResources().getBoolean(
R.bool.def_screen_brightness_automatic_mode) ? "1" : "0";
db.execSQL("INSERT OR REPLACE INTO system(name,value) values('" +
Settings.System.SCREEN_BRIGHTNESS_MODE + "','" + value + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* Loads the default set of bookmarked shortcuts from an xml file.
*
* @param db The database to write the values into
*/
private void loadBookmarks(SQLiteDatabase db) {
ContentValues values = new ContentValues();
PackageManager packageManager = mContext.getPackageManager();
try {
XmlResourceParser parser = mContext.getResources().getXml(R.xml.bookmarks);
XmlUtils.beginDocument(parser, "bookmarks");
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (!"bookmark".equals(name)) {
break;
}
String pkg = parser.getAttributeValue(null, "package");
String cls = parser.getAttributeValue(null, "class");
String shortcutStr = parser.getAttributeValue(null, "shortcut");
String category = parser.getAttributeValue(null, "category");
int shortcutValue = shortcutStr.charAt(0);
if (TextUtils.isEmpty(shortcutStr)) {
Log.w(TAG, "Unable to get shortcut for: " + pkg + "/" + cls);
continue;
}
final Intent intent;
final String title;
if (pkg != null && cls != null) {
ActivityInfo info = null;
ComponentName cn = new ComponentName(pkg, cls);
try {
info = packageManager.getActivityInfo(cn, 0);
} catch (PackageManager.NameNotFoundException e) {
String[] packages = packageManager.canonicalToCurrentPackageNames(
new String[] { pkg });
cn = new ComponentName(packages[0], cls);
try {
info = packageManager.getActivityInfo(cn, 0);
} catch (PackageManager.NameNotFoundException e1) {
Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
continue;
}
}
intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(cn);
title = info.loadLabel(packageManager).toString();
} else if (category != null) {
intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
title = "";
} else {
Log.w(TAG, "Unable to add bookmark for shortcut " + shortcutStr
+ ": missing package/class or category attributes");
continue;
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
values.put(Settings.Bookmarks.INTENT, intent.toUri(0));
values.put(Settings.Bookmarks.TITLE, title);
values.put(Settings.Bookmarks.SHORTCUT, shortcutValue);
db.delete("bookmarks", "shortcut = ?",
new String[] { Integer.toString(shortcutValue) });
db.insert("bookmarks", null, values);
}
} catch (XmlPullParserException e) {
Log.w(TAG, "Got execption parsing bookmarks.", e);
} catch (IOException e) {
Log.w(TAG, "Got execption parsing bookmarks.", e);
}
}
/**
* Loads the default volume levels. It is actually inserting the index of
* the volume array for each of the volume controls.
*
* @param db the database to insert the volume levels into
*/
private void loadVolumeLevels(SQLiteDatabase db) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VOLUME_MUSIC,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_MUSIC]);
loadSetting(stmt, Settings.System.VOLUME_RING,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_RING]);
loadSetting(stmt, Settings.System.VOLUME_SYSTEM,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_SYSTEM]);
loadSetting(
stmt,
Settings.System.VOLUME_VOICE,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_VOICE_CALL]);
loadSetting(stmt, Settings.System.VOLUME_ALARM,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_ALARM]);
loadSetting(
stmt,
Settings.System.VOLUME_NOTIFICATION,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_NOTIFICATION]);
loadSetting(
stmt,
Settings.System.VOLUME_BLUETOOTH_SCO,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);
// By default:
// - ringtones, notification, system and music streams are affected by ringer mode
// on non voice capable devices (tablets)
// - ringtones, notification and system streams are affected by ringer mode
// on voice capable devices (phones)
int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM) |
(1 << AudioManager.STREAM_SYSTEM_ENFORCED);
if (!mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable)) {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
loadSetting(stmt, Settings.System.MODE_RINGER_STREAMS_AFFECTED,
ringerModeAffectedStreams);
loadSetting(stmt, Settings.System.MUTE_STREAMS_AFFECTED,
((1 << AudioManager.STREAM_MUSIC) |
(1 << AudioManager.STREAM_RING) |
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM)));
} finally {
if (stmt != null) stmt.close();
}
loadVibrateWhenRingingSetting(db);
}
private void loadVibrateSetting(SQLiteDatabase db, boolean deleteOld) {
if (deleteOld) {
db.execSQL("DELETE FROM system WHERE name='" + Settings.System.VIBRATE_ON + "'");
}
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
// Vibrate on by default for ringer, on for notification
int vibrate = 0;
vibrate = AudioService.getValueForVibrateSetting(vibrate,
AudioManager.VIBRATE_TYPE_NOTIFICATION,
AudioManager.VIBRATE_SETTING_ONLY_SILENT);
vibrate |= AudioService.getValueForVibrateSetting(vibrate,
AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ONLY_SILENT);
loadSetting(stmt, Settings.System.VIBRATE_ON, vibrate);
} finally {
if (stmt != null) stmt.close();
}
}
private void loadVibrateWhenRingingSetting(SQLiteDatabase db) {
// The default should be off. VIBRATE_SETTING_ONLY_SILENT should also be ignored here.
// Phone app should separately check whether AudioManager#getRingerMode() returns
// RINGER_MODE_VIBRATE, with which the device should vibrate anyway.
int vibrateSetting = getIntValueFromSystem(db, Settings.System.VIBRATE_ON,
AudioManager.VIBRATE_SETTING_OFF);
boolean vibrateWhenRinging = ((vibrateSetting & 3) == AudioManager.VIBRATE_SETTING_ON);
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VIBRATE_WHEN_RINGING, vibrateWhenRinging ? 1 : 0);
} finally {
if (stmt != null) stmt.close();
}
}
private void loadSettings(SQLiteDatabase db) {
loadSystemSettings(db);
loadSecureSettings(db);
// The global table only exists for the 'owner' user
if (mUserHandle == UserHandle.USER_OWNER) {
loadGlobalSettings(db);
}
}
private void loadSystemSettings(SQLiteDatabase db) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
R.bool.def_dim_screen);
loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
R.integer.def_screen_off_timeout);
// Set default cdma DTMF type
loadSetting(stmt, Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 0);
// Set default hearing aid
loadSetting(stmt, Settings.System.HEARING_AID, 0);
// Set default tty mode
loadSetting(stmt, Settings.System.TTY_MODE, 0);
// Set default noise suppression value
loadSetting(stmt, Settings.System.NOISE_SUPPRESSION, 0);
loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,
R.integer.def_screen_brightness);
loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE,
R.bool.def_screen_brightness_automatic_mode);
loadDefaultAnimationSettings(stmt);
loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,
R.bool.def_accelerometer_rotation);
loadDefaultHapticSettings(stmt);
loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
R.bool.def_notification_pulse);
loadUISoundEffectsSettings(stmt);
loadIntegerSetting(stmt, Settings.System.POINTER_SPEED,
R.integer.def_pointer_speed);
loadIntegerSetting(stmt, Settings.System.STATUS_BAR_BATTERY,
R.integer.def_battery_style);
} finally {
if (stmt != null) stmt.close();
}
}
private void loadUISoundEffectsSettings(SQLiteStatement stmt) {
loadBooleanSetting(stmt, Settings.System.DTMF_TONE_WHEN_DIALING,
R.bool.def_dtmf_tones_enabled);
loadBooleanSetting(stmt, Settings.System.SOUND_EFFECTS_ENABLED,
R.bool.def_sound_effects_enabled);
loadBooleanSetting(stmt, Settings.System.HAPTIC_FEEDBACK_ENABLED,
R.bool.def_haptic_feedback);
loadIntegerSetting(stmt, Settings.System.LOCKSCREEN_SOUNDS_ENABLED,
R.integer.def_lockscreen_sounds_enabled);
}
private void loadDefaultAnimationSettings(SQLiteStatement stmt) {
loadFractionSetting(stmt, Settings.System.WINDOW_ANIMATION_SCALE,
R.fraction.def_window_animation_scale, 1);
loadFractionSetting(stmt, Settings.System.TRANSITION_ANIMATION_SCALE,
R.fraction.def_window_transition_scale, 1);
}
private void loadDefaultHapticSettings(SQLiteStatement stmt) {
loadBooleanSetting(stmt, Settings.System.HAPTIC_FEEDBACK_ENABLED,
R.bool.def_haptic_feedback);
}
private void loadSecureSettings(SQLiteDatabase db) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
R.string.def_location_providers_allowed);
String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
if (!TextUtils.isEmpty(wifiWatchList)) {
loadSetting(stmt, Settings.Secure.WIFI_WATCHDOG_WATCH_LIST, wifiWatchList);
}
// Don't do this. The SystemServer will initialize ADB_ENABLED from a
// persistent system property instead.
//loadSetting(stmt, Settings.Secure.ADB_ENABLED, 0);
// Allow mock locations default, based on build
loadSetting(stmt, Settings.Secure.ALLOW_MOCK_LOCATION,
"1".equals(SystemProperties.get("ro.allow.mock.location")) ? 1 : 0);
loadSecure35Settings(stmt);
loadBooleanSetting(stmt, Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND,
R.bool.def_mount_play_notification_snd);
loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_AUTOSTART,
R.bool.def_mount_ums_autostart);
loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_PROMPT,
R.bool.def_mount_ums_prompt);
loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED,
R.bool.def_mount_ums_notify_enabled);
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION,
R.bool.def_accessibility_script_injection);
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_WEB_CONTENT_KEY_BINDINGS,
R.string.def_accessibility_web_content_key_bindings);
loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
R.integer.def_long_press_timeout_millis);
loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
R.bool.def_touch_exploration_enabled);
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
R.bool.def_accessibility_speak_password);
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
if (SystemProperties.getBoolean("ro.lockscreen.disable.default", false) == true) {
loadSetting(stmt, Settings.System.LOCKSCREEN_DISABLED, "1");
} else {
loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
R.bool.def_lockscreen_disabled);
}
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
com.android.internal.R.bool.config_dreamsEnabledByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
com.android.internal.R.string.config_dreamsDefaultComponent);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
com.android.internal.R.string.config_dreamsDefaultComponent);
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
R.bool.def_accessibility_display_magnification_enabled);
loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
R.fraction.def_accessibility_display_magnification_scale, 1);
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE,
R.bool.def_accessibility_display_magnification_auto_update);
loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
R.bool.def_user_setup_complete);
} finally {
if (stmt != null) stmt.close();
}
}
private void loadSecure35Settings(SQLiteStatement stmt) {
loadBooleanSetting(stmt, Settings.Secure.BACKUP_ENABLED,
R.bool.def_backup_enabled);
loadStringSetting(stmt, Settings.Secure.BACKUP_TRANSPORT,
R.string.def_backup_transport);
}
private void loadGlobalSettings(SQLiteDatabase db) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO global(name,value)"
+ " VALUES(?,?);");
// --- Previously in 'system'
loadBooleanSetting(stmt, Settings.Global.AIRPLANE_MODE_ON,
R.bool.def_airplane_mode_on);
loadStringSetting(stmt, Settings.Global.AIRPLANE_MODE_RADIOS,
R.string.def_airplane_mode_radios);
loadStringSetting(stmt, Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
loadBooleanSetting(stmt, Settings.Global.ASSISTED_GPS_ENABLED,
R.bool.assisted_gps_enabled);
loadBooleanSetting(stmt, Settings.Global.AUTO_TIME,
R.bool.def_auto_time); // Sync time to NITZ
loadBooleanSetting(stmt, Settings.Global.AUTO_TIME_ZONE,
R.bool.def_auto_time_zone); // Sync timezone to NITZ
loadSetting(stmt, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
("1".equals(SystemProperties.get("ro.kernel.qemu")) ||
mContext.getResources().getBoolean(R.bool.def_stay_on_while_plugged_in))
? 1 : 0);
loadIntegerSetting(stmt, Settings.Global.WIFI_SLEEP_POLICY,
R.integer.def_wifi_sleep_policy);
loadSetting(stmt, Settings.Global.MODE_RINGER,
AudioManager.RINGER_MODE_NORMAL);
// --- Previously in 'secure'
loadBooleanSetting(stmt, Settings.Global.PACKAGE_VERIFIER_ENABLE,
R.bool.def_package_verifier_enable);
loadBooleanSetting(stmt, Settings.Global.WIFI_ON,
R.bool.def_wifi_on);
loadBooleanSetting(stmt, Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
R.bool.def_networks_available_notification_on);
loadBooleanSetting(stmt, Settings.Global.BLUETOOTH_ON,
R.bool.def_bluetooth_on);
// Enable or disable Cell Broadcast SMS
loadSetting(stmt, Settings.Global.CDMA_CELL_BROADCAST_SMS,
RILConstants.CDMA_CELL_BROADCAST_SMS_DISABLED);
// Data roaming default, based on build
loadSetting(stmt, Settings.Global.DATA_ROAMING,
"true".equalsIgnoreCase(
SystemProperties.get("ro.com.android.dataroaming",
"false")) ? 1 : 0);
loadBooleanSetting(stmt, Settings.Global.DEVICE_PROVISIONED,
R.bool.def_device_provisioned);
final int maxBytes = mContext.getResources().getInteger(
R.integer.def_download_manager_max_bytes_over_mobile);
if (maxBytes > 0) {
loadSetting(stmt, Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE,
Integer.toString(maxBytes));
}
final int recommendedMaxBytes = mContext.getResources().getInteger(
R.integer.def_download_manager_recommended_max_bytes_over_mobile);
if (recommendedMaxBytes > 0) {
loadSetting(stmt, Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE,
Integer.toString(recommendedMaxBytes));
}
// Mobile Data default, based on build
loadSetting(stmt, Settings.Global.MOBILE_DATA,
"true".equalsIgnoreCase(
SystemProperties.get("ro.com.android.mobiledata",
"true")) ? 1 : 0);
loadBooleanSetting(stmt, Settings.Global.NETSTATS_ENABLED,
R.bool.def_netstats_enabled);
loadBooleanSetting(stmt, Settings.Global.INSTALL_NON_MARKET_APPS,
R.bool.def_install_non_market_apps);
loadIntegerSetting(stmt, Settings.Global.NETWORK_PREFERENCE,
R.integer.def_network_preference);
loadBooleanSetting(stmt, Settings.Global.USB_MASS_STORAGE_ENABLED,
R.bool.def_usb_mass_storage_enabled);
loadIntegerSetting(stmt, Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT,
R.integer.def_max_dhcp_retries);
loadBooleanSetting(stmt, Settings.Global.WIFI_DISPLAY_ON,
R.bool.def_wifi_display_on);
loadStringSetting(stmt, Settings.Global.LOCK_SOUND,
R.string.def_lock_sound);
loadStringSetting(stmt, Settings.Global.UNLOCK_SOUND,
R.string.def_unlock_sound);
loadIntegerSetting(stmt, Settings.Global.POWER_SOUNDS_ENABLED,
R.integer.def_power_sounds_enabled);
loadStringSetting(stmt, Settings.Global.LOW_BATTERY_SOUND,
R.string.def_low_battery_sound);
loadIntegerSetting(stmt, Settings.Global.DOCK_SOUNDS_ENABLED,
R.integer.def_dock_sounds_enabled);
loadStringSetting(stmt, Settings.Global.DESK_DOCK_SOUND,
R.string.def_desk_dock_sound);
loadStringSetting(stmt, Settings.Global.DESK_UNDOCK_SOUND,
R.string.def_desk_undock_sound);
loadStringSetting(stmt, Settings.Global.CAR_DOCK_SOUND,
R.string.def_car_dock_sound);
loadStringSetting(stmt, Settings.Global.CAR_UNDOCK_SOUND,
R.string.def_car_undock_sound);
loadStringSetting(stmt, Settings.Global.WIRELESS_CHARGING_STARTED_SOUND,
R.string.def_wireless_charging_started_sound);
loadSetting(stmt, Settings.Global.SET_INSTALL_LOCATION, 0);
loadSetting(stmt, Settings.Global.DEFAULT_INSTALL_LOCATION,
PackageHelper.APP_INSTALL_AUTO);
// Set default cdma emergency tone
loadSetting(stmt, Settings.Global.EMERGENCY_TONE, 0);
// Set default cdma call auto retry
loadSetting(stmt, Settings.Global.CALL_AUTO_RETRY, 0);
// Set the preferred network mode to 0 = Global, CDMA default
int type;
type = SystemProperties.getInt("ro.telephony.default_network",
RILConstants.PREFERRED_NETWORK_MODE);
loadSetting(stmt, Settings.Global.PREFERRED_NETWORK_MODE, type);
// --- New global settings start here
} finally {
if (stmt != null) stmt.close();
}
}
private void loadSetting(SQLiteStatement stmt, String key, Object value) {
stmt.bindString(1, key);
stmt.bindString(2, value.toString());
stmt.execute();
}
private void loadStringSetting(SQLiteStatement stmt, String key, int resid) {
loadSetting(stmt, key, mContext.getResources().getString(resid));
}
private void loadBooleanSetting(SQLiteStatement stmt, String key, int resid) {
loadSetting(stmt, key,
mContext.getResources().getBoolean(resid) ? "1" : "0");
}
private void loadIntegerSetting(SQLiteStatement stmt, String key, int resid) {
loadSetting(stmt, key,
Integer.toString(mContext.getResources().getInteger(resid)));
}
private void loadFractionSetting(SQLiteStatement stmt, String key, int resid, int base) {
loadSetting(stmt, key,
Float.toString(mContext.getResources().getFraction(resid, base, base)));
}
private int getIntValueFromSystem(SQLiteDatabase db, String name, int defaultValue) {
return getIntValueFromTable(db, TABLE_SYSTEM, name, defaultValue);
}
private int getIntValueFromTable(SQLiteDatabase db, String table, String name,
int defaultValue) {
String value = getStringValueFromTable(db, table, name, null);
return (value != null) ? Integer.parseInt(value) : defaultValue;
}
private String getStringValueFromTable(SQLiteDatabase db, String table, String name,
String defaultValue) {
Cursor c = null;
try {
c = db.query(table, new String[] { Settings.System.VALUE }, "name='" + name + "'",
null, null, null, null);
if (c != null && c.moveToFirst()) {
String val = c.getString(0);
return val == null ? defaultValue : val;
}
} finally {
if (c != null) c.close();
}
return defaultValue;
}
}
| false | true | public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
Log.w(TAG, "Upgrading settings database from version " + oldVersion + " to "
+ currentVersion);
int upgradeVersion = oldVersion;
// Pattern for upgrade blocks:
//
// if (upgradeVersion == [the DATABASE_VERSION you set] - 1) {
// .. your upgrade logic..
// upgradeVersion = [the DATABASE_VERSION you set]
// }
if (upgradeVersion == 20) {
/*
* Version 21 is part of the volume control refresh. There is no
* longer a UI-visible for setting notification vibrate on/off (in
* our design), but the functionality still exists. Force the
* notification vibrate to on.
*/
loadVibrateSetting(db, true);
upgradeVersion = 21;
}
if (upgradeVersion < 22) {
upgradeVersion = 22;
// Upgrade the lock gesture storage location and format
upgradeLockPatternLocation(db);
}
if (upgradeVersion < 23) {
db.execSQL("UPDATE favorites SET iconResource=0 WHERE iconType=0");
upgradeVersion = 23;
}
if (upgradeVersion == 23) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD spanX INTEGER");
db.execSQL("ALTER TABLE favorites ADD spanY INTEGER");
// Shortcuts, applications, folders
db.execSQL("UPDATE favorites SET spanX=1, spanY=1 WHERE itemType<=0");
// Photo frames, clocks
db.execSQL(
"UPDATE favorites SET spanX=2, spanY=2 WHERE itemType=1000 or itemType=1002");
// Search boxes
db.execSQL("UPDATE favorites SET spanX=4, spanY=1 WHERE itemType=1001");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 24;
}
if (upgradeVersion == 24) {
db.beginTransaction();
try {
// The value of the constants for preferring wifi or preferring mobile have been
// swapped, so reload the default.
db.execSQL("DELETE FROM system WHERE name='network_preference'");
db.execSQL("INSERT INTO system ('name', 'value') values ('network_preference', '" +
ConnectivityManager.DEFAULT_NETWORK_PREFERENCE + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 25;
}
if (upgradeVersion == 25) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD uri TEXT");
db.execSQL("ALTER TABLE favorites ADD displayMode INTEGER");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 26;
}
if (upgradeVersion == 26) {
// This introduces the new secure settings table.
db.beginTransaction();
try {
createSecureTable(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 27;
}
if (upgradeVersion == 27) {
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.ANDROID_ID,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.HTTP_PROXY,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Settings.Secure.LOGGING_ID,
Settings.Secure.NETWORK_PREFERENCE,
Settings.Secure.PARENTAL_CONTROL_ENABLED,
Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
Settings.Secure.PARENTAL_CONTROL_REDIRECT_URL,
Settings.Secure.SETTINGS_CLASSNAME,
Settings.Secure.USB_MASS_STORAGE_ENABLED,
Settings.Secure.USE_GOOGLE_MAIL,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT,
Settings.Secure.WIFI_ON,
Settings.Secure.WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE,
Settings.Secure.WIFI_WATCHDOG_AP_COUNT,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS,
Settings.Secure.WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_MAX_AP_CHECKS,
Settings.Secure.WIFI_WATCHDOG_ON,
Settings.Secure.WIFI_WATCHDOG_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 28;
}
if (upgradeVersion == 28 || upgradeVersion == 29) {
// Note: The upgrade to 28 was flawed since it didn't delete the old
// setting first before inserting. Combining 28 and 29 with the
// fixed version.
// This upgrade adds the STREAM_NOTIFICATION type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 30;
}
if (upgradeVersion == 30) {
/*
* Upgrade 31 clears the title for all quick launch shortcuts so the
* activities' titles will be resolved at display time. Also, the
* folder is changed to '@quicklaunch'.
*/
db.beginTransaction();
try {
db.execSQL("UPDATE bookmarks SET folder = '@quicklaunch'");
db.execSQL("UPDATE bookmarks SET title = ''");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 31;
}
if (upgradeVersion == 31) {
/*
* Animations are now managed in preferences, and may be
* enabled or disabled based on product resources.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 32;
}
if (upgradeVersion == 32) {
// The Wi-Fi watchdog SSID list is now seeded with the value of
// the property ro.com.android.wifi-watchlist
String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
if (!TextUtils.isEmpty(wifiWatchList)) {
db.beginTransaction();
try {
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Secure.WIFI_WATCHDOG_WATCH_LIST + "','" +
wifiWatchList + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 33;
}
if (upgradeVersion == 33) {
// Set the default zoom controls to: tap-twice to bring up +/-
db.beginTransaction();
try {
db.execSQL("INSERT INTO system(name,value) values('zoom','2');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 34;
}
if (upgradeVersion == 34) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSecure35Settings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 35;
}
// due to a botched merge from donut to eclair, the initialization of ASSISTED_GPS_ENABLED
// was accidentally done out of order here.
// to fix this, ASSISTED_GPS_ENABLED is now initialized while upgrading from 38 to 39,
// and we intentionally do nothing from 35 to 36 now.
if (upgradeVersion == 35) {
upgradeVersion = 36;
}
if (upgradeVersion == 36) {
// This upgrade adds the STREAM_SYSTEM_ENFORCED type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 37;
}
if (upgradeVersion == 37) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 38;
}
if (upgradeVersion == 38) {
db.beginTransaction();
try {
String value =
mContext.getResources().getBoolean(R.bool.assisted_gps_enabled) ? "1" : "0";
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Global.ASSISTED_GPS_ENABLED + "','" + value + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 39;
}
if (upgradeVersion == 39) {
upgradeAutoBrightness(db);
upgradeVersion = 40;
}
if (upgradeVersion == 40) {
/*
* All animations are now turned on by default!
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 41;
}
if (upgradeVersion == 41) {
/*
* Initialize newly public haptic feedback setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.HAPTIC_FEEDBACK_ENABLED + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultHapticSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 42;
}
if (upgradeVersion == 42) {
/*
* Initialize new notification pulse setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
R.bool.def_notification_pulse);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 43;
}
if (upgradeVersion == 43) {
/*
* This upgrade stores bluetooth volume separately from voice volume
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VOLUME_BLUETOOTH_SCO,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 44;
}
if (upgradeVersion == 44) {
/*
* Gservices was moved into vendor/google.
*/
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
upgradeVersion = 45;
}
if (upgradeVersion == 45) {
/*
* New settings for MountService
*/
db.beginTransaction();
try {
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_AUTOSTART + "','0');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_PROMPT + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED + "','1');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 46;
}
if (upgradeVersion == 46) {
/*
* The password mode constants have changed; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 47;
}
if (upgradeVersion == 47) {
/*
* The password mode constants have changed again; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 48;
}
if (upgradeVersion == 48) {
/*
* Default recognition service no longer initialized here,
* moved to RecognitionManagerService.
*/
upgradeVersion = 49;
}
if (upgradeVersion == 49) {
/*
* New settings for new user interface noises.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadUISoundEffectsSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 50;
}
if (upgradeVersion == 50) {
/*
* Install location no longer initiated here.
*/
upgradeVersion = 51;
}
if (upgradeVersion == 51) {
/* Move the lockscreen related settings to Secure, including some private ones. */
String[] settingsToMove = {
Secure.LOCK_PATTERN_ENABLED,
Secure.LOCK_PATTERN_VISIBLE,
Secure.LOCK_SHOW_ERROR_PATH,
Secure.LOCK_DOTS_VISIBLE,
Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED,
"lockscreen.password_type",
"lockscreen.lockoutattemptdeadline",
"lockscreen.patterneverchosen",
"lock_pattern_autolock",
"lockscreen.lockedoutpermanently",
"lockscreen.password_salt"
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 52;
}
if (upgradeVersion == 52) {
// new vibration/silent mode settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 53;
}
if (upgradeVersion == 53) {
/*
* New settings for set install location UI no longer initiated here.
*/
upgradeVersion = 54;
}
if (upgradeVersion == 54) {
/*
* Update the screen timeout value if set to never
*/
db.beginTransaction();
try {
upgradeScreenTimeoutFromNever(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 55;
}
if (upgradeVersion == 55) {
/* Move the install location settings. */
String[] settingsToMove = {
Global.SET_INSTALL_LOCATION,
Global.DEFAULT_INSTALL_LOCATION
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Global.SET_INSTALL_LOCATION, 0);
loadSetting(stmt, Global.DEFAULT_INSTALL_LOCATION,
PackageHelper.APP_INSTALL_AUTO);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 56;
}
if (upgradeVersion == 56) {
/*
* Add Bluetooth to list of toggleable radios in airplane mode
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 57;
}
/************* The following are Honeycomb changes ************/
if (upgradeVersion == 57) {
/*
* New settings to:
* 1. Enable injection of accessibility scripts in WebViews.
* 2. Define the key bindings for traversing web content in WebViews.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION,
R.bool.def_accessibility_script_injection);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_WEB_CONTENT_KEY_BINDINGS,
R.string.def_accessibility_web_content_key_bindings);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 58;
}
if (upgradeVersion == 58) {
/* Add default for new Auto Time Zone */
int autoTimeValue = getIntValueFromSystem(db, Settings.System.AUTO_TIME, 0);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)" + " VALUES(?,?);");
loadSetting(stmt, Settings.System.AUTO_TIME_ZONE,
autoTimeValue); // Sync timezone to NITZ if auto_time was enabled
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 59;
}
if (upgradeVersion == 59) {
// Persistence for the rotation lock feature.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.USER_ROTATION,
R.integer.def_user_rotation); // should be zero degrees
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 60;
}
if (upgradeVersion == 60) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 61;
}
if (upgradeVersion == 61) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 62;
}
// Change the default for screen auto-brightness mode
if (upgradeVersion == 62) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeAutoBrightness(db);
upgradeVersion = 63;
}
if (upgradeVersion == 63) {
// This upgrade adds the STREAM_MUSIC type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED)
| (1 << AudioManager.STREAM_MUSIC);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 64;
}
if (upgradeVersion == 64) {
// New setting to configure the long press timeout.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
R.integer.def_long_press_timeout_millis);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 65;
}
/************* The following are Ice Cream Sandwich changes ************/
if (upgradeVersion == 65) {
/*
* Animations are removed from Settings. Turned on by default
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 66;
}
if (upgradeVersion == 66) {
// This upgrade makes sure that MODE_RINGER_STREAMS_AFFECTED is set
// according to device voice capability
db.beginTransaction();
try {
int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM) |
(1 << AudioManager.STREAM_SYSTEM_ENFORCED);
if (!mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable)) {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(ringerModeAffectedStreams) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 67;
}
if (upgradeVersion == 67) {
// New setting to enable touch exploration.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
R.bool.def_touch_exploration_enabled);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 68;
}
if (upgradeVersion == 68) {
// Enable all system sounds by default
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.NOTIFICATIONS_USE_RING_VOLUME + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 69;
}
if (upgradeVersion == 69) {
// Add RADIO_NFC to AIRPLANE_MODE_RADIO and AIRPLANE_MODE_TOGGLEABLE_RADIOS
String airplaneRadios = mContext.getResources().getString(
R.string.def_airplane_mode_radios);
String toggleableRadios = mContext.getResources().getString(
R.string.airplane_mode_toggleable_radios);
db.beginTransaction();
try {
db.execSQL("UPDATE system SET value='" + airplaneRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_RADIOS + "'");
db.execSQL("UPDATE system SET value='" + toggleableRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 70;
}
if (upgradeVersion == 70) {
// Update all built-in bookmarks. Some of the package names have changed.
loadBookmarks(db);
upgradeVersion = 71;
}
if (upgradeVersion == 71) {
// New setting to specify whether to speak passwords in accessibility mode.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
R.bool.def_accessibility_speak_password);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 72;
}
if (upgradeVersion == 72) {
// update vibration settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 73;
}
if (upgradeVersion == 73) {
upgradeVibrateSettingFromNone(db);
upgradeVersion = 74;
}
if (upgradeVersion == 74) {
// URL from which WebView loads a JavaScript based screen-reader.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 75;
}
if (upgradeVersion == 75) {
db.beginTransaction();
SQLiteStatement stmt = null;
Cursor c = null;
try {
c = db.query(TABLE_SECURE, new String[] {"_id", "value"},
"name='lockscreen.disabled'",
null, null, null, null);
// only set default if it has not yet been set
if (c == null || c.getCount() == 0) {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
R.bool.def_lockscreen_disabled);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (c != null) c.close();
if (stmt != null) stmt.close();
}
upgradeVersion = 76;
}
/************* The following are Jelly Bean changes ************/
if (upgradeVersion == 76) {
// Removed VIBRATE_IN_SILENT setting
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.VIBRATE_IN_SILENT + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 77;
}
if (upgradeVersion == 77) {
// Introduce "vibrate when ringing" setting
loadVibrateWhenRingingSetting(db);
upgradeVersion = 78;
}
if (upgradeVersion == 78) {
// The JavaScript based screen-reader URL changes in JellyBean.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 79;
}
if (upgradeVersion == 79) {
// Before touch exploration was a global setting controlled by the user
// via the UI. However, if the enabled accessibility services do not
// handle touch exploration mode, enabling it makes no sense. Therefore,
// now the services request touch exploration mode and the user is
// presented with a dialog to allow that and if she does we store that
// in the database. As a result of this change a user that has enabled
// accessibility, touch exploration, and some accessibility services
// may lose touch exploration state, thus rendering the device useless
// unless sighted help is provided, since the enabled service(s) are
// not in the list of services to which the user granted a permission
// to put the device in touch explore mode. Here we are allowing all
// enabled accessibility services to toggle touch exploration provided
// accessibility and touch exploration are enabled and no services can
// toggle touch exploration. Note that the user has already manually
// enabled the services and touch exploration which means the she has
// given consent to have these services work in touch exploration mode.
final boolean accessibilityEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;
final boolean touchExplorationEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0) == 1;
if (accessibilityEnabled && touchExplorationEnabled) {
String enabledServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
String touchExplorationGrantedServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, "");
if (TextUtils.isEmpty(touchExplorationGrantedServices)
&& !TextUtils.isEmpty(enabledServices)) {
SQLiteStatement stmt = null;
try {
db.beginTransaction();
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
enabledServices);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
}
upgradeVersion = 80;
}
// vvv Jelly Bean MR1 changes begin here vvv
if (upgradeVersion == 80) {
// update screensaver settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
com.android.internal.R.bool.config_dreamsEnabledByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
com.android.internal.R.string.config_dreamsDefaultComponent);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
com.android.internal.R.string.config_dreamsDefaultComponent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 81;
}
if (upgradeVersion == 81) {
// Add package verification setting
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Global.PACKAGE_VERIFIER_ENABLE,
R.bool.def_package_verifier_enable);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 82;
}
if (upgradeVersion == 82) {
// Move to per-user settings dbs
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings. Note that this happens before
// new users can be created.
createGlobalTable(db);
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, false);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, false);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 83;
}
if (upgradeVersion == 83) {
// 1. Setting whether screen magnification is enabled.
// 2. Setting for screen magnification scale.
// 3. Setting for screen magnification auto update.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
R.bool.def_accessibility_display_magnification_enabled);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
R.fraction.def_accessibility_display_magnification_scale, 1);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE,
R.bool.def_accessibility_display_magnification_auto_update);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 84;
}
if (upgradeVersion == 84) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Patch up the slightly-wrong key migration from 82 -> 83 for those
// devices that missed it, ignoring if the move is redundant
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.USB_MASS_STORAGE_ENABLED
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 85;
}
if (upgradeVersion == 85) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Fix up the migration, ignoring already-migrated elements, to snap up to
// date with new changes to the set of global versus system/secure settings
String[] settingsToMove = { Settings.System.STAY_ON_WHILE_PLUGGED_IN };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 86;
}
if (upgradeVersion == 86) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.PACKAGE_VERIFIER_ENABLE,
Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 87;
}
if (upgradeVersion == 87) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.GPRS_REGISTER_CHECK_PERIOD_MS
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 88;
}
if (upgradeVersion == 88) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD,
Settings.Global.BATTERY_DISCHARGE_THRESHOLD,
Settings.Global.SEND_ACTION_APP_ERROR,
Settings.Global.DROPBOX_AGE_SECONDS,
Settings.Global.DROPBOX_MAX_FILES,
Settings.Global.DROPBOX_QUOTA_KB,
Settings.Global.DROPBOX_QUOTA_PERCENT,
Settings.Global.DROPBOX_RESERVE_PERCENT,
Settings.Global.DROPBOX_TAG_PREFIX,
Settings.Global.ERROR_LOGCAT_PREFIX,
Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE,
Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES,
Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED,
Settings.Global.CAPTIVE_PORTAL_SERVER,
Settings.Global.NSD_ON,
Settings.Global.SET_INSTALL_LOCATION,
Settings.Global.DEFAULT_INSTALL_LOCATION,
Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY,
Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY,
Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT,
Settings.Global.HTTP_PROXY,
Settings.Global.GLOBAL_HTTP_PROXY_HOST,
Settings.Global.GLOBAL_HTTP_PROXY_PORT,
Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Settings.Global.SET_GLOBAL_HTTP_PROXY,
Settings.Global.DEFAULT_DNS_SERVER,
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 89;
}
if (upgradeVersion == 89) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] prefixesToMove = {
Settings.Global.BLUETOOTH_HEADSET_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_A2DP_SINK_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_INPUT_DEVICE_PRIORITY_PREFIX,
};
movePrefixedSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, prefixesToMove);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 90;
}
if (upgradeVersion == 90) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] systemToGlobal = {
Settings.Global.WINDOW_ANIMATION_SCALE,
Settings.Global.TRANSITION_ANIMATION_SCALE,
Settings.Global.ANIMATOR_DURATION_SCALE,
Settings.Global.FANCY_IME_ANIMATIONS,
Settings.Global.COMPATIBILITY_MODE,
Settings.Global.EMERGENCY_TONE,
Settings.Global.CALL_AUTO_RETRY,
Settings.Global.DEBUG_APP,
Settings.Global.WAIT_FOR_DEBUGGER,
Settings.Global.SHOW_PROCESSES,
Settings.Global.ALWAYS_FINISH_ACTIVITIES,
};
String[] secureToGlobal = {
Settings.Global.PREFERRED_NETWORK_MODE,
Settings.Global.PREFERRED_CDMA_SUBSCRIPTION,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, systemToGlobal, true);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, secureToGlobal, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 91;
}
if (upgradeVersion == 91) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Move ringer mode from system to global settings
String[] settingsToMove = { Settings.Global.MODE_RINGER };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 92;
}
if (upgradeVersion == 92) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
if (mUserHandle == UserHandle.USER_OWNER) {
// consider existing primary users to have made it through user setup
// if the globally-scoped device-provisioned bit is set
// (indicating they already made it through setup as primary)
int deviceProvisioned = getIntValueFromTable(db, TABLE_GLOBAL,
Settings.Global.DEVICE_PROVISIONED, 0);
loadSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
deviceProvisioned);
} else {
// otherwise use the default
loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
R.bool.def_user_setup_complete);
}
} finally {
if (stmt != null) stmt.close();
}
upgradeVersion = 93;
}
if (upgradeVersion == 93) {
// Redo this step, since somehow it didn't work the first time for some users
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 94;
}
if (upgradeVersion == 94) {
// Add wireless charging started sound setting
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Global.WIRELESS_CHARGING_STARTED_SOUND,
R.string.def_wireless_charging_started_sound);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 95;
}
// *** Remember to update DATABASE_VERSION above!
if (upgradeVersion != currentVersion) {
Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
+ ", must wipe the settings provider");
db.execSQL("DROP TABLE IF EXISTS global");
db.execSQL("DROP TABLE IF EXISTS globalIndex1");
db.execSQL("DROP TABLE IF EXISTS system");
db.execSQL("DROP INDEX IF EXISTS systemIndex1");
db.execSQL("DROP TABLE IF EXISTS secure");
db.execSQL("DROP INDEX IF EXISTS secureIndex1");
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
db.execSQL("DROP TABLE IF EXISTS bluetooth_devices");
db.execSQL("DROP TABLE IF EXISTS bookmarks");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex1");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex2");
db.execSQL("DROP TABLE IF EXISTS favorites");
onCreate(db);
// Added for diagnosing settings.db wipes after the fact
String wipeReason = oldVersion + "/" + upgradeVersion + "/" + currentVersion;
db.execSQL("INSERT INTO secure(name,value) values('" +
"wiped_db_reason" + "','" + wipeReason + "');");
}
}
| public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
Log.w(TAG, "Upgrading settings database from version " + oldVersion + " to "
+ currentVersion);
int upgradeVersion = oldVersion;
// Pattern for upgrade blocks:
//
// if (upgradeVersion == [the DATABASE_VERSION you set] - 1) {
// .. your upgrade logic..
// upgradeVersion = [the DATABASE_VERSION you set]
// }
if (upgradeVersion == 20) {
/*
* Version 21 is part of the volume control refresh. There is no
* longer a UI-visible for setting notification vibrate on/off (in
* our design), but the functionality still exists. Force the
* notification vibrate to on.
*/
loadVibrateSetting(db, true);
upgradeVersion = 21;
}
if (upgradeVersion < 22) {
upgradeVersion = 22;
// Upgrade the lock gesture storage location and format
upgradeLockPatternLocation(db);
}
if (upgradeVersion < 23) {
db.execSQL("UPDATE favorites SET iconResource=0 WHERE iconType=0");
upgradeVersion = 23;
}
if (upgradeVersion == 23) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD spanX INTEGER");
db.execSQL("ALTER TABLE favorites ADD spanY INTEGER");
// Shortcuts, applications, folders
db.execSQL("UPDATE favorites SET spanX=1, spanY=1 WHERE itemType<=0");
// Photo frames, clocks
db.execSQL(
"UPDATE favorites SET spanX=2, spanY=2 WHERE itemType=1000 or itemType=1002");
// Search boxes
db.execSQL("UPDATE favorites SET spanX=4, spanY=1 WHERE itemType=1001");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 24;
}
if (upgradeVersion == 24) {
db.beginTransaction();
try {
// The value of the constants for preferring wifi or preferring mobile have been
// swapped, so reload the default.
db.execSQL("DELETE FROM system WHERE name='network_preference'");
db.execSQL("INSERT INTO system ('name', 'value') values ('network_preference', '" +
ConnectivityManager.DEFAULT_NETWORK_PREFERENCE + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 25;
}
if (upgradeVersion == 25) {
db.beginTransaction();
try {
db.execSQL("ALTER TABLE favorites ADD uri TEXT");
db.execSQL("ALTER TABLE favorites ADD displayMode INTEGER");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 26;
}
if (upgradeVersion == 26) {
// This introduces the new secure settings table.
db.beginTransaction();
try {
createSecureTable(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 27;
}
if (upgradeVersion == 27) {
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.ANDROID_ID,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.HTTP_PROXY,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Settings.Secure.LOGGING_ID,
Settings.Secure.NETWORK_PREFERENCE,
Settings.Secure.PARENTAL_CONTROL_ENABLED,
Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
Settings.Secure.PARENTAL_CONTROL_REDIRECT_URL,
Settings.Secure.SETTINGS_CLASSNAME,
Settings.Secure.USB_MASS_STORAGE_ENABLED,
Settings.Secure.USE_GOOGLE_MAIL,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT,
Settings.Secure.WIFI_ON,
Settings.Secure.WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE,
Settings.Secure.WIFI_WATCHDOG_AP_COUNT,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED,
Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS,
Settings.Secure.WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_MAX_AP_CHECKS,
Settings.Secure.WIFI_WATCHDOG_ON,
Settings.Secure.WIFI_WATCHDOG_PING_COUNT,
Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS,
Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 28;
}
if (upgradeVersion == 28 || upgradeVersion == 29) {
// Note: The upgrade to 28 was flawed since it didn't delete the old
// setting first before inserting. Combining 28 and 29 with the
// fixed version.
// This upgrade adds the STREAM_NOTIFICATION type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 30;
}
if (upgradeVersion == 30) {
/*
* Upgrade 31 clears the title for all quick launch shortcuts so the
* activities' titles will be resolved at display time. Also, the
* folder is changed to '@quicklaunch'.
*/
db.beginTransaction();
try {
db.execSQL("UPDATE bookmarks SET folder = '@quicklaunch'");
db.execSQL("UPDATE bookmarks SET title = ''");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 31;
}
if (upgradeVersion == 31) {
/*
* Animations are now managed in preferences, and may be
* enabled or disabled based on product resources.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 32;
}
if (upgradeVersion == 32) {
// The Wi-Fi watchdog SSID list is now seeded with the value of
// the property ro.com.android.wifi-watchlist
String wifiWatchList = SystemProperties.get("ro.com.android.wifi-watchlist");
if (!TextUtils.isEmpty(wifiWatchList)) {
db.beginTransaction();
try {
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Secure.WIFI_WATCHDOG_WATCH_LIST + "','" +
wifiWatchList + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 33;
}
if (upgradeVersion == 33) {
// Set the default zoom controls to: tap-twice to bring up +/-
db.beginTransaction();
try {
db.execSQL("INSERT INTO system(name,value) values('zoom','2');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 34;
}
if (upgradeVersion == 34) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSecure35Settings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 35;
}
// due to a botched merge from donut to eclair, the initialization of ASSISTED_GPS_ENABLED
// was accidentally done out of order here.
// to fix this, ASSISTED_GPS_ENABLED is now initialized while upgrading from 38 to 39,
// and we intentionally do nothing from 35 to 36 now.
if (upgradeVersion == 35) {
upgradeVersion = 36;
}
if (upgradeVersion == 36) {
// This upgrade adds the STREAM_SYSTEM_ENFORCED type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 37;
}
if (upgradeVersion == 37) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 38;
}
if (upgradeVersion == 38) {
db.beginTransaction();
try {
String value =
mContext.getResources().getBoolean(R.bool.assisted_gps_enabled) ? "1" : "0";
db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
Settings.Global.ASSISTED_GPS_ENABLED + "','" + value + "');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 39;
}
if (upgradeVersion == 39) {
upgradeAutoBrightness(db);
upgradeVersion = 40;
}
if (upgradeVersion == 40) {
/*
* All animations are now turned on by default!
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 41;
}
if (upgradeVersion == 41) {
/*
* Initialize newly public haptic feedback setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.HAPTIC_FEEDBACK_ENABLED + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultHapticSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 42;
}
if (upgradeVersion == 42) {
/*
* Initialize new notification pulse setting
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
R.bool.def_notification_pulse);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 43;
}
if (upgradeVersion == 43) {
/*
* This upgrade stores bluetooth volume separately from voice volume
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Settings.System.VOLUME_BLUETOOTH_SCO,
AudioManager.DEFAULT_STREAM_VOLUME[AudioManager.STREAM_BLUETOOTH_SCO]);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 44;
}
if (upgradeVersion == 44) {
/*
* Gservices was moved into vendor/google.
*/
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
upgradeVersion = 45;
}
if (upgradeVersion == 45) {
/*
* New settings for MountService
*/
db.beginTransaction();
try {
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_AUTOSTART + "','0');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_PROMPT + "','1');");
db.execSQL("INSERT INTO secure(name,value) values('" +
Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED + "','1');");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 46;
}
if (upgradeVersion == 46) {
/*
* The password mode constants have changed; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 47;
}
if (upgradeVersion == 47) {
/*
* The password mode constants have changed again; reset back to no
* password.
*/
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 48;
}
if (upgradeVersion == 48) {
/*
* Default recognition service no longer initialized here,
* moved to RecognitionManagerService.
*/
upgradeVersion = 49;
}
if (upgradeVersion == 49) {
/*
* New settings for new user interface noises.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadUISoundEffectsSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 50;
}
if (upgradeVersion == 50) {
/*
* Install location no longer initiated here.
*/
upgradeVersion = 51;
}
if (upgradeVersion == 51) {
/* Move the lockscreen related settings to Secure, including some private ones. */
String[] settingsToMove = {
Secure.LOCK_PATTERN_ENABLED,
Secure.LOCK_PATTERN_VISIBLE,
Secure.LOCK_SHOW_ERROR_PATH,
Secure.LOCK_DOTS_VISIBLE,
Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED,
"lockscreen.password_type",
"lockscreen.lockoutattemptdeadline",
"lockscreen.patterneverchosen",
"lock_pattern_autolock",
"lockscreen.lockedoutpermanently",
"lockscreen.password_salt"
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
upgradeVersion = 52;
}
if (upgradeVersion == 52) {
// new vibration/silent mode settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 53;
}
if (upgradeVersion == 53) {
/*
* New settings for set install location UI no longer initiated here.
*/
upgradeVersion = 54;
}
if (upgradeVersion == 54) {
/*
* Update the screen timeout value if set to never
*/
db.beginTransaction();
try {
upgradeScreenTimeoutFromNever(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 55;
}
if (upgradeVersion == 55) {
/* Move the install location settings. */
String[] settingsToMove = {
Global.SET_INSTALL_LOCATION,
Global.DEFAULT_INSTALL_LOCATION
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt, Global.SET_INSTALL_LOCATION, 0);
loadSetting(stmt, Global.DEFAULT_INSTALL_LOCATION,
PackageHelper.APP_INSTALL_AUTO);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 56;
}
if (upgradeVersion == 56) {
/*
* Add Bluetooth to list of toggleable radios in airplane mode
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
R.string.airplane_mode_toggleable_radios);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 57;
}
/************* The following are Honeycomb changes ************/
if (upgradeVersion == 57) {
/*
* New settings to:
* 1. Enable injection of accessibility scripts in WebViews.
* 2. Define the key bindings for traversing web content in WebViews.
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION,
R.bool.def_accessibility_script_injection);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_WEB_CONTENT_KEY_BINDINGS,
R.string.def_accessibility_web_content_key_bindings);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 58;
}
if (upgradeVersion == 58) {
/* Add default for new Auto Time Zone */
int autoTimeValue = getIntValueFromSystem(db, Settings.Global.AUTO_TIME, 0);
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)" + " VALUES(?,?);");
loadSetting(stmt, Settings.Global.AUTO_TIME_ZONE,
autoTimeValue); // Sync timezone to NITZ if auto_time was enabled
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 59;
}
if (upgradeVersion == 59) {
// Persistence for the rotation lock feature.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.USER_ROTATION,
R.integer.def_user_rotation); // should be zero degrees
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 60;
}
if (upgradeVersion == 60) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 61;
}
if (upgradeVersion == 61) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeScreenTimeout(db);
upgradeVersion = 62;
}
// Change the default for screen auto-brightness mode
if (upgradeVersion == 62) {
// Don't do this for upgrades from Gingerbread
// Were only required for intra-Honeycomb upgrades for testing
// upgradeAutoBrightness(db);
upgradeVersion = 63;
}
if (upgradeVersion == 63) {
// This upgrade adds the STREAM_MUSIC type to the list of
// types affected by ringer modes (silent, vibrate, etc.)
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
int newValue = (1 << AudioManager.STREAM_RING)
| (1 << AudioManager.STREAM_NOTIFICATION)
| (1 << AudioManager.STREAM_SYSTEM)
| (1 << AudioManager.STREAM_SYSTEM_ENFORCED)
| (1 << AudioManager.STREAM_MUSIC);
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(newValue) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 64;
}
if (upgradeVersion == 64) {
// New setting to configure the long press timeout.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
R.integer.def_long_press_timeout_millis);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 65;
}
/************* The following are Ice Cream Sandwich changes ************/
if (upgradeVersion == 65) {
/*
* Animations are removed from Settings. Turned on by default
*/
db.beginTransaction();
SQLiteStatement stmt = null;
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.WINDOW_ANIMATION_SCALE + "'");
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.TRANSITION_ANIMATION_SCALE + "'");
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadDefaultAnimationSettings(stmt);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 66;
}
if (upgradeVersion == 66) {
// This upgrade makes sure that MODE_RINGER_STREAMS_AFFECTED is set
// according to device voice capability
db.beginTransaction();
try {
int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM) |
(1 << AudioManager.STREAM_SYSTEM_ENFORCED);
if (!mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable)) {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
db.execSQL("INSERT INTO system ('name', 'value') values ('"
+ Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
+ String.valueOf(ringerModeAffectedStreams) + "')");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 67;
}
if (upgradeVersion == 67) {
// New setting to enable touch exploration.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
R.bool.def_touch_exploration_enabled);
stmt.close();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 68;
}
if (upgradeVersion == 68) {
// Enable all system sounds by default
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.NOTIFICATIONS_USE_RING_VOLUME + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 69;
}
if (upgradeVersion == 69) {
// Add RADIO_NFC to AIRPLANE_MODE_RADIO and AIRPLANE_MODE_TOGGLEABLE_RADIOS
String airplaneRadios = mContext.getResources().getString(
R.string.def_airplane_mode_radios);
String toggleableRadios = mContext.getResources().getString(
R.string.airplane_mode_toggleable_radios);
db.beginTransaction();
try {
db.execSQL("UPDATE system SET value='" + airplaneRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_RADIOS + "'");
db.execSQL("UPDATE system SET value='" + toggleableRadios + "' " +
"WHERE name='" + Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 70;
}
if (upgradeVersion == 70) {
// Update all built-in bookmarks. Some of the package names have changed.
loadBookmarks(db);
upgradeVersion = 71;
}
if (upgradeVersion == 71) {
// New setting to specify whether to speak passwords in accessibility mode.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
R.bool.def_accessibility_speak_password);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 72;
}
if (upgradeVersion == 72) {
// update vibration settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
R.bool.def_vibrate_in_silent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 73;
}
if (upgradeVersion == 73) {
upgradeVibrateSettingFromNone(db);
upgradeVersion = 74;
}
if (upgradeVersion == 74) {
// URL from which WebView loads a JavaScript based screen-reader.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 75;
}
if (upgradeVersion == 75) {
db.beginTransaction();
SQLiteStatement stmt = null;
Cursor c = null;
try {
c = db.query(TABLE_SECURE, new String[] {"_id", "value"},
"name='lockscreen.disabled'",
null, null, null, null);
// only set default if it has not yet been set
if (c == null || c.getCount() == 0) {
stmt = db.compileStatement("INSERT INTO system(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
R.bool.def_lockscreen_disabled);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (c != null) c.close();
if (stmt != null) stmt.close();
}
upgradeVersion = 76;
}
/************* The following are Jelly Bean changes ************/
if (upgradeVersion == 76) {
// Removed VIBRATE_IN_SILENT setting
db.beginTransaction();
try {
db.execSQL("DELETE FROM system WHERE name='"
+ Settings.System.VIBRATE_IN_SILENT + "'");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
upgradeVersion = 77;
}
if (upgradeVersion == 77) {
// Introduce "vibrate when ringing" setting
loadVibrateWhenRingingSetting(db);
upgradeVersion = 78;
}
if (upgradeVersion == 78) {
// The JavaScript based screen-reader URL changes in JellyBean.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Secure.ACCESSIBILITY_SCREEN_READER_URL,
R.string.def_accessibility_screen_reader_url);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 79;
}
if (upgradeVersion == 79) {
// Before touch exploration was a global setting controlled by the user
// via the UI. However, if the enabled accessibility services do not
// handle touch exploration mode, enabling it makes no sense. Therefore,
// now the services request touch exploration mode and the user is
// presented with a dialog to allow that and if she does we store that
// in the database. As a result of this change a user that has enabled
// accessibility, touch exploration, and some accessibility services
// may lose touch exploration state, thus rendering the device useless
// unless sighted help is provided, since the enabled service(s) are
// not in the list of services to which the user granted a permission
// to put the device in touch explore mode. Here we are allowing all
// enabled accessibility services to toggle touch exploration provided
// accessibility and touch exploration are enabled and no services can
// toggle touch exploration. Note that the user has already manually
// enabled the services and touch exploration which means the she has
// given consent to have these services work in touch exploration mode.
final boolean accessibilityEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;
final boolean touchExplorationEnabled = getIntValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0) == 1;
if (accessibilityEnabled && touchExplorationEnabled) {
String enabledServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
String touchExplorationGrantedServices = getStringValueFromTable(db, TABLE_SECURE,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, "");
if (TextUtils.isEmpty(touchExplorationGrantedServices)
&& !TextUtils.isEmpty(enabledServices)) {
SQLiteStatement stmt = null;
try {
db.beginTransaction();
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadSetting(stmt,
Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
enabledServices);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
}
upgradeVersion = 80;
}
// vvv Jelly Bean MR1 changes begin here vvv
if (upgradeVersion == 80) {
// update screensaver settings
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
com.android.internal.R.bool.config_dreamsEnabledByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
com.android.internal.R.string.config_dreamsDefaultComponent);
loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
com.android.internal.R.string.config_dreamsDefaultComponent);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 81;
}
if (upgradeVersion == 81) {
// Add package verification setting
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
+ " VALUES(?,?);");
loadBooleanSetting(stmt, Settings.Global.PACKAGE_VERIFIER_ENABLE,
R.bool.def_package_verifier_enable);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 82;
}
if (upgradeVersion == 82) {
// Move to per-user settings dbs
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings. Note that this happens before
// new users can be created.
createGlobalTable(db);
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, false);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, false);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 83;
}
if (upgradeVersion == 83) {
// 1. Setting whether screen magnification is enabled.
// 2. Setting for screen magnification scale.
// 3. Setting for screen magnification auto update.
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
R.bool.def_accessibility_display_magnification_enabled);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
R.fraction.def_accessibility_display_magnification_scale, 1);
stmt.close();
stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
loadBooleanSetting(stmt,
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE,
R.bool.def_accessibility_display_magnification_auto_update);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
upgradeVersion = 84;
}
if (upgradeVersion == 84) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Patch up the slightly-wrong key migration from 82 -> 83 for those
// devices that missed it, ignoring if the move is redundant
String[] settingsToMove = {
Settings.Secure.ADB_ENABLED,
Settings.Secure.BLUETOOTH_ON,
Settings.Secure.DATA_ROAMING,
Settings.Secure.DEVICE_PROVISIONED,
Settings.Secure.INSTALL_NON_MARKET_APPS,
Settings.Secure.USB_MASS_STORAGE_ENABLED
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 85;
}
if (upgradeVersion == 85) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Fix up the migration, ignoring already-migrated elements, to snap up to
// date with new changes to the set of global versus system/secure settings
String[] settingsToMove = { Settings.System.STAY_ON_WHILE_PLUGGED_IN };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 86;
}
if (upgradeVersion == 86) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.PACKAGE_VERIFIER_ENABLE,
Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 87;
}
if (upgradeVersion == 87) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
Settings.Global.GPRS_REGISTER_CHECK_PERIOD_MS
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 88;
}
if (upgradeVersion == 88) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] settingsToMove = {
Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD,
Settings.Global.BATTERY_DISCHARGE_THRESHOLD,
Settings.Global.SEND_ACTION_APP_ERROR,
Settings.Global.DROPBOX_AGE_SECONDS,
Settings.Global.DROPBOX_MAX_FILES,
Settings.Global.DROPBOX_QUOTA_KB,
Settings.Global.DROPBOX_QUOTA_PERCENT,
Settings.Global.DROPBOX_RESERVE_PERCENT,
Settings.Global.DROPBOX_TAG_PREFIX,
Settings.Global.ERROR_LOGCAT_PREFIX,
Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE,
Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES,
Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED,
Settings.Global.CAPTIVE_PORTAL_SERVER,
Settings.Global.NSD_ON,
Settings.Global.SET_INSTALL_LOCATION,
Settings.Global.DEFAULT_INSTALL_LOCATION,
Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY,
Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY,
Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT,
Settings.Global.HTTP_PROXY,
Settings.Global.GLOBAL_HTTP_PROXY_HOST,
Settings.Global.GLOBAL_HTTP_PROXY_PORT,
Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Settings.Global.SET_GLOBAL_HTTP_PROXY,
Settings.Global.DEFAULT_DNS_SERVER,
};
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 89;
}
if (upgradeVersion == 89) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] prefixesToMove = {
Settings.Global.BLUETOOTH_HEADSET_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_A2DP_SINK_PRIORITY_PREFIX,
Settings.Global.BLUETOOTH_INPUT_DEVICE_PRIORITY_PREFIX,
};
movePrefixedSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, prefixesToMove);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 90;
}
if (upgradeVersion == 90) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
String[] systemToGlobal = {
Settings.Global.WINDOW_ANIMATION_SCALE,
Settings.Global.TRANSITION_ANIMATION_SCALE,
Settings.Global.ANIMATOR_DURATION_SCALE,
Settings.Global.FANCY_IME_ANIMATIONS,
Settings.Global.COMPATIBILITY_MODE,
Settings.Global.EMERGENCY_TONE,
Settings.Global.CALL_AUTO_RETRY,
Settings.Global.DEBUG_APP,
Settings.Global.WAIT_FOR_DEBUGGER,
Settings.Global.SHOW_PROCESSES,
Settings.Global.ALWAYS_FINISH_ACTIVITIES,
};
String[] secureToGlobal = {
Settings.Global.PREFERRED_NETWORK_MODE,
Settings.Global.PREFERRED_CDMA_SUBSCRIPTION,
};
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, systemToGlobal, true);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, secureToGlobal, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 91;
}
if (upgradeVersion == 91) {
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
try {
// Move ringer mode from system to global settings
String[] settingsToMove = { Settings.Global.MODE_RINGER };
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
upgradeVersion = 92;
}
if (upgradeVersion == 92) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
+ " VALUES(?,?);");
if (mUserHandle == UserHandle.USER_OWNER) {
// consider existing primary users to have made it through user setup
// if the globally-scoped device-provisioned bit is set
// (indicating they already made it through setup as primary)
int deviceProvisioned = getIntValueFromTable(db, TABLE_GLOBAL,
Settings.Global.DEVICE_PROVISIONED, 0);
loadSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
deviceProvisioned);
} else {
// otherwise use the default
loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
R.bool.def_user_setup_complete);
}
} finally {
if (stmt != null) stmt.close();
}
upgradeVersion = 93;
}
if (upgradeVersion == 93) {
// Redo this step, since somehow it didn't work the first time for some users
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
// Migrate now-global settings
String[] settingsToMove = hashsetToStringArray(SettingsProvider.sSystemGlobalKeys);
moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
settingsToMove = hashsetToStringArray(SettingsProvider.sSecureGlobalKeys);
moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 94;
}
if (upgradeVersion == 94) {
// Add wireless charging started sound setting
if (mUserHandle == UserHandle.USER_OWNER) {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
+ " VALUES(?,?);");
loadStringSetting(stmt, Settings.Global.WIRELESS_CHARGING_STARTED_SOUND,
R.string.def_wireless_charging_started_sound);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
}
upgradeVersion = 95;
}
// *** Remember to update DATABASE_VERSION above!
if (upgradeVersion != currentVersion) {
Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
+ ", must wipe the settings provider");
db.execSQL("DROP TABLE IF EXISTS global");
db.execSQL("DROP TABLE IF EXISTS globalIndex1");
db.execSQL("DROP TABLE IF EXISTS system");
db.execSQL("DROP INDEX IF EXISTS systemIndex1");
db.execSQL("DROP TABLE IF EXISTS secure");
db.execSQL("DROP INDEX IF EXISTS secureIndex1");
db.execSQL("DROP TABLE IF EXISTS gservices");
db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
db.execSQL("DROP TABLE IF EXISTS bluetooth_devices");
db.execSQL("DROP TABLE IF EXISTS bookmarks");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex1");
db.execSQL("DROP INDEX IF EXISTS bookmarksIndex2");
db.execSQL("DROP TABLE IF EXISTS favorites");
onCreate(db);
// Added for diagnosing settings.db wipes after the fact
String wipeReason = oldVersion + "/" + upgradeVersion + "/" + currentVersion;
db.execSQL("INSERT INTO secure(name,value) values('" +
"wiped_db_reason" + "','" + wipeReason + "');");
}
}
|
diff --git a/Projet_GL_2012/src/bebetes/Bebete.java b/Projet_GL_2012/src/bebetes/Bebete.java
index 41647e4..a6e0180 100644
--- a/Projet_GL_2012/src/bebetes/Bebete.java
+++ b/Projet_GL_2012/src/bebetes/Bebete.java
@@ -1,214 +1,215 @@
package bebetes;
/*
* Bebete.java
*
*/
/**
*
* @author collet (d'apr�s L. O'Brien, C. Reynolds & B. Eckel)
* @version 3.0
*/
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Observable;
import java.util.Random;
import Panel.BebteControl;
import Panel.PanelCustom;
import comportement.*;
import fr.unice.plugin.Plugin;
import simu.Actionnable;
import util.DistancesEtDirections;
import visu.Dessinable;
import visu.PerceptionAble;
import visu.Positionnable;
/**
* @author collet
*/
public class Bebete extends Observable implements Dessinable,
Actionnable, PerceptionAble, Plugin {
// il y a 1 chance sur CHANSE_HASARD pour que la bebete soit hasard sinon elle sera Emergente
private static int CHANCE_HASARD = 20;
private BebeteAvecComportement currentState;
public Bebete(BebeteAvecComportement bebete) {
this.currentState = bebete;
}
/* D�finition plus pr�cise de l'action de la bebete */
public boolean isDead() {
return currentState.isDead();
}
public void setDead(boolean dead) {
currentState.setDead(dead);
}
public void calculeDeplacementAFaire() {
currentState.calculeDeplacementAFaire();
}
public void effectueDeplacement() {
currentState.effectueDeplacement();
}
// modifie l'energie en fonction du type de la bebete et de son
// environnement
public void changeEnergie() {
currentState.changeEnergie();
}
public int getEnergie() {
return currentState.getEnergie();
}
// Impl�mentation de Actionnable */
public void agit() {
currentState.agit();
// si on a un changement d'état voulue
if(currentState.getPendingState() != null){
//public BebeteHasard(ChampDeBebetes c, int x, int y, float dC, float vC, Color col) {
try {
int energy = currentState.getEnergie();
currentState = (BebeteAvecComportement) currentState.getPendingState()
.getConstructors()[0].newInstance(currentState.getChamp(),currentState.getX(),currentState.getY()
,currentState.getDirectionCourante(),currentState.getVitesseCourante(),currentState.getCouleur());
currentState.setEnergie(energy);
+ currentState.setPendingState(null);
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/* Impl�mentation de Dessinable */
public Color getCouleur() {
return currentState.getCouleur();
}
public void setCouleur(Color couleur) {
currentState.setCouleur(couleur);
}
public void seDessine(Graphics g) {
currentState.seDessine(g);
}
public void calculerDeplacemementSensible() {
currentState.calculerDeplacemementSensible();
}
/* Impl�mentation de Positionnable */
public int getX() {
return currentState.getX();
}
public void setX(int x) {
currentState.setX(x);
}
public int getY() {
return currentState.getY();
}
public void setY(int y) {
currentState.setY(y);
}
public ChampDeBebetes getChamp() {
return currentState.getChamp();
}
/* Impl�mentation de Dirigeable */
public float getVitesseCourante() {
return currentState.getVitesseCourante();
}
public void setVitesseCourante(float vitesseCourante) {
currentState.setVitesseCourante(vitesseCourante);
}
public float getDirectionCourante() {
return currentState.getDirectionCourante();
}
public void setDirectionCourante(float directionCourante) {
currentState.setDirectionCourante(directionCourante);
}
/* Impl�mentation de PerceptionAble */
public int getLongueurDeVue() {
return currentState.getLongueurDeVue();
}
public float getChampDeVue() {
return currentState.getChampDeVue();
}
public List<Positionnable> getChosesVues() { // utilisation de l'utilitaire
return currentState.getChosesVues();
}
/*
* changer la longueur et le champ de vue est "static", alors que les
* consulter se fait par des fonctions membres
*/
public static void setLongueurDeVue(int lDV) {
BebeteAvecComportement.setLongueurDeVue(lDV);
}
public static void setChampDeVue(float cv) {
BebeteAvecComportement.setChampDeVue(cv);
}
// partie propre � la transformation en Plugin
public String getName() {
return currentState.getName();
}
public Deplacement getDeplacement() {
return currentState.getDeplacement();
}
public void setDeplacement(Deplacement move) {
currentState.setDeplacement(move);
}
public float getDistancePlusProche() {
return currentState.getDistancePlusProche();
}
public void setDistancePlusProche(float distancePlusProche) {
setDistancePlusProche(distancePlusProche);
}
public BebeteAvecComportement getCurrentState(){
return currentState;
}
}
| true | true | public void agit() {
currentState.agit();
// si on a un changement d'état voulue
if(currentState.getPendingState() != null){
//public BebeteHasard(ChampDeBebetes c, int x, int y, float dC, float vC, Color col) {
try {
int energy = currentState.getEnergie();
currentState = (BebeteAvecComportement) currentState.getPendingState()
.getConstructors()[0].newInstance(currentState.getChamp(),currentState.getX(),currentState.getY()
,currentState.getDirectionCourante(),currentState.getVitesseCourante(),currentState.getCouleur());
currentState.setEnergie(energy);
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| public void agit() {
currentState.agit();
// si on a un changement d'état voulue
if(currentState.getPendingState() != null){
//public BebeteHasard(ChampDeBebetes c, int x, int y, float dC, float vC, Color col) {
try {
int energy = currentState.getEnergie();
currentState = (BebeteAvecComportement) currentState.getPendingState()
.getConstructors()[0].newInstance(currentState.getChamp(),currentState.getX(),currentState.getY()
,currentState.getDirectionCourante(),currentState.getVitesseCourante(),currentState.getCouleur());
currentState.setEnergie(energy);
currentState.setPendingState(null);
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
|
diff --git a/mes-plugins/mes-plugins-cost-norms-for-operation/src/main/java/com/qcadoo/mes/costNormsForOperation/OperationsCostCalculationService.java b/mes-plugins/mes-plugins-cost-norms-for-operation/src/main/java/com/qcadoo/mes/costNormsForOperation/OperationsCostCalculationService.java
index d04b8b1f9a..c989551192 100644
--- a/mes-plugins/mes-plugins-cost-norms-for-operation/src/main/java/com/qcadoo/mes/costNormsForOperation/OperationsCostCalculationService.java
+++ b/mes-plugins/mes-plugins-cost-norms-for-operation/src/main/java/com/qcadoo/mes/costNormsForOperation/OperationsCostCalculationService.java
@@ -1,44 +1,44 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.1.3
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.costNormsForOperation;
import java.math.BigDecimal;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.EntityTreeNode;
@Service
public interface OperationsCostCalculationService {
void calculateOperationsCost(final Entity costCalculation);
- Map<String, BigDecimal> calculateOperationCostWithoutSaving(final EntityTreeNode operationComponent, final BigDecimal margin,
- final BigDecimal plannedQuantity, final Map<Entity, Integer> realizationTimes);
+ Map<String, BigDecimal> estimateCostCalculationForHourlyWitoutSaving(final EntityTreeNode operationComponent,
+ final BigDecimal margin, final BigDecimal plannedQuantity, final Map<Entity, Integer> realizationTimes);
BigDecimal estimateCostCalculationForPieceWorkWithoutSaving(final EntityTreeNode operationComponent,
final Map<Entity, BigDecimal> productComponentQuantities, final BigDecimal margin, final BigDecimal plannedQuantity);
}
| true | true | Map<String, BigDecimal> calculateOperationCostWithoutSaving(final EntityTreeNode operationComponent, final BigDecimal margin,
final BigDecimal plannedQuantity, final Map<Entity, Integer> realizationTimes);
| Map<String, BigDecimal> estimateCostCalculationForHourlyWitoutSaving(final EntityTreeNode operationComponent,
final BigDecimal margin, final BigDecimal plannedQuantity, final Map<Entity, Integer> realizationTimes);
|
diff --git a/src/com/android/gallery3d/filtershow/PanelController.java b/src/com/android/gallery3d/filtershow/PanelController.java
index 6694e37f6..2a97e7e53 100644
--- a/src/com/android/gallery3d/filtershow/PanelController.java
+++ b/src/com/android/gallery3d/filtershow/PanelController.java
@@ -1,588 +1,588 @@
/*
* Copyright (C) 2012 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.gallery3d.filtershow;
import android.content.Context;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewPropertyAnimator;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.gallery3d.R;
import com.android.gallery3d.filtershow.editors.Editor;
import com.android.gallery3d.filtershow.filters.ImageFilter;
import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet;
import com.android.gallery3d.filtershow.imageshow.ImageCrop;
import com.android.gallery3d.filtershow.imageshow.ImageShow;
import com.android.gallery3d.filtershow.imageshow.MasterImage;
import com.android.gallery3d.filtershow.presets.ImagePreset;
import com.android.gallery3d.filtershow.ui.FilterIconButton;
import com.android.gallery3d.filtershow.ui.FramedTextButton;
import java.util.HashMap;
import java.util.Vector;
public class PanelController implements OnClickListener {
private static int PANEL = 0;
private static int COMPONENT = 1;
private static int VERTICAL_MOVE = 0;
private static int HORIZONTAL_MOVE = 1;
private static final int ANIM_DURATION = 200;
private static final String LOGTAG = "PanelController";
private boolean mDisableFilterButtons = false;
private boolean mFixedAspect = false;
public void setFixedAspect(boolean t) {
mFixedAspect = t;
}
class Panel {
private final View mView;
private final View mContainer;
private int mPosition = 0;
private final Vector<View> mSubviews = new Vector<View>();
public Panel(View view, View container, int position) {
mView = view;
mContainer = container;
mPosition = position;
}
public void addView(View view) {
mSubviews.add(view);
}
public int getPosition() {
return mPosition;
}
public ViewPropertyAnimator unselect(int newPos, int move) {
ViewPropertyAnimator anim = mContainer.animate();
mView.setSelected(false);
mContainer.setX(0);
mContainer.setY(0);
int delta = 0;
int w = mRowPanel.getWidth();
int h = mRowPanel.getHeight();
if (move == HORIZONTAL_MOVE) {
if (newPos > mPosition) {
delta = -w;
} else {
delta = w;
}
anim.x(delta);
} else if (move == VERTICAL_MOVE) {
anim.y(h);
}
anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() {
@Override
public void run() {
mContainer.setVisibility(View.GONE);
}
});
return anim;
}
public ViewPropertyAnimator select(int oldPos, int move) {
mView.setSelected(true);
mContainer.setVisibility(View.VISIBLE);
mContainer.setX(0);
mContainer.setY(0);
ViewPropertyAnimator anim = mContainer.animate();
int w = mRowPanel.getWidth();
int h = mRowPanel.getHeight();
if (move == HORIZONTAL_MOVE) {
if (oldPos < mPosition) {
mContainer.setX(w);
} else {
mContainer.setX(-w);
}
anim.x(0);
} else if (move == VERTICAL_MOVE) {
mContainer.setY(h);
anim.y(0);
}
anim.setDuration(ANIM_DURATION).withLayer();
return anim;
}
}
class UtilityPanel {
private final Context mContext;
private final View mView;
private final LinearLayout mAccessoryViewList;
private Vector<View> mAccessoryViews = new Vector<View>();
private final TextView mTextView;
private boolean mSelected = false;
private String mEffectName = null;
private int mParameterValue = 0;
private boolean mShowParameterValue = false;
boolean firstTimeCropDisplayed = true;
public UtilityPanel(Context context, View view, View accessoryViewList,
View textView) {
mContext = context;
mView = view;
mAccessoryViewList = (LinearLayout) accessoryViewList;
mTextView = (TextView) textView;
}
public boolean selected() {
return mSelected;
}
public void hideAccessoryViews() {
int childCount = mAccessoryViewList.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mAccessoryViewList.getChildAt(i);
child.setVisibility(View.GONE);
}
}
public void onNewValue(int value) {
mParameterValue = value;
updateText();
}
public void setEffectName(String effectName) {
mEffectName = effectName;
setShowParameter(true);
}
public void setShowParameter(boolean s) {
mShowParameterValue = s;
updateText();
}
public void updateText() {
String apply = mContext.getString(R.string.apply_effect);
if (mShowParameterValue) {
mTextView.setText(Html.fromHtml(apply + " " + mEffectName + " "
+ mParameterValue));
} else {
mTextView.setText(Html.fromHtml(apply + " " + mEffectName));
}
}
public ViewPropertyAnimator unselect() {
ViewPropertyAnimator anim = mView.animate();
mView.setX(0);
mView.setY(0);
int h = mRowPanel.getHeight();
anim.y(-h);
anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() {
@Override
public void run() {
mView.setVisibility(View.GONE);
}
});
mSelected = false;
return anim;
}
public ViewPropertyAnimator select() {
mView.setVisibility(View.VISIBLE);
int h = mRowPanel.getHeight();
mView.setX(0);
mView.setY(-h);
updateText();
ViewPropertyAnimator anim = mView.animate();
anim.y(0);
anim.setDuration(ANIM_DURATION).withLayer();
mSelected = true;
return anim;
}
}
class ViewType {
private final int mType;
private final View mView;
public ViewType(View view, int type) {
mView = view;
mType = type;
}
public int type() {
return mType;
}
}
private final HashMap<View, Panel> mPanels = new HashMap<View, Panel>();
private final HashMap<View, ViewType> mViews = new HashMap<View, ViewType>();
private final HashMap<String, ImageFilter> mFilters = new HashMap<String, ImageFilter>();
private final Vector<View> mImageViews = new Vector<View>();
private View mCurrentPanel = null;
private View mRowPanel = null;
private UtilityPanel mUtilityPanel = null;
private MasterImage mMasterImage = MasterImage.getImage();
private ImageShow mCurrentImage = null;
private Editor mCurrentEditor = null;
private FilterShowActivity mActivity = null;
private EditorPlaceHolder mEditorPlaceHolder = null;
public void setActivity(FilterShowActivity activity) {
mActivity = activity;
}
public void addView(View view) {
view.setOnClickListener(this);
mViews.put(view, new ViewType(view, COMPONENT));
}
public void addPanel(View view, View container, int position) {
mPanels.put(view, new Panel(view, container, position));
view.setOnClickListener(this);
mViews.put(view, new ViewType(view, PANEL));
}
public void addComponent(View aPanel, View component) {
Panel panel = mPanels.get(aPanel);
if (panel == null) {
return;
}
panel.addView(component);
component.setOnClickListener(this);
mViews.put(component, new ViewType(component, COMPONENT));
}
public void addFilter(ImageFilter filter) {
mFilters.put(filter.getName(), filter);
}
public void addImageView(View view) {
mImageViews.add(view);
ImageShow imageShow = (ImageShow) view;
imageShow.setPanelController(this);
}
public void resetParameters() {
showPanel(mCurrentPanel);
if (mCurrentImage != null) {
mCurrentImage.resetParameter();
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
}
}
if (mDisableFilterButtons) {
mActivity.enableFilterButtons();
mDisableFilterButtons = false;
}
}
public boolean onBackPressed() {
if (mUtilityPanel == null || !mUtilityPanel.selected()) {
return true;
}
HistoryAdapter adapter = mMasterImage.getHistory();
int position = adapter.undo();
mMasterImage.onHistoryItemClick(position);
showPanel(mCurrentPanel);
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
}
if (mDisableFilterButtons) {
mActivity.enableFilterButtons();
mActivity.resetHistory();
mDisableFilterButtons = false;
}
return false;
}
public void onNewValue(int value) {
mUtilityPanel.onNewValue(value);
}
public void showParameter(boolean s) {
mUtilityPanel.setShowParameter(s);
}
public void setCurrentPanel(View panel) {
showPanel(panel);
}
public void setRowPanel(View rowPanel) {
mRowPanel = rowPanel;
}
public void setUtilityPanel(Context context, View utilityPanel,
View accessoryViewList, View textView) {
mUtilityPanel = new UtilityPanel(context, utilityPanel,
accessoryViewList, textView);
}
@Override
public void onClick(View view) {
ViewType type = mViews.get(view);
if (type.type() == PANEL) {
showPanel(view);
} else if (type.type() == COMPONENT) {
showComponent(view);
}
}
public ImageShow showImageView(int id) {
ImageShow image = null;
mActivity.hideImageViews();
for (View view : mImageViews) {
if (view.getId() == id) {
view.setVisibility(View.VISIBLE);
image = (ImageShow) view;
} else {
view.setVisibility(View.GONE);
}
}
return image;
}
public void showDefaultImageView() {
showImageView(R.id.imageShow).setShowControls(false);
mMasterImage.setCurrentFilter(null);
mMasterImage.setCurrentFilterRepresentation(null);
}
public void showPanel(View view) {
view.setVisibility(View.VISIBLE);
boolean removedUtilityPanel = false;
Panel current = mPanels.get(mCurrentPanel);
if (mUtilityPanel != null && mUtilityPanel.selected()) {
ViewPropertyAnimator anim1 = mUtilityPanel.unselect();
removedUtilityPanel = true;
anim1.start();
if (mCurrentPanel == view) {
ViewPropertyAnimator anim2 = current.select(-1, VERTICAL_MOVE);
anim2.start();
showDefaultImageView();
}
}
if (mCurrentPanel == view) {
return;
}
Panel panel = mPanels.get(view);
if (!removedUtilityPanel) {
int currentPos = -1;
if (current != null) {
currentPos = current.getPosition();
}
ViewPropertyAnimator anim1 = panel.select(currentPos, HORIZONTAL_MOVE);
anim1.start();
if (current != null) {
ViewPropertyAnimator anim2 = current.unselect(panel.getPosition(), HORIZONTAL_MOVE);
anim2.start();
}
} else {
ViewPropertyAnimator anim = panel.select(-1, VERTICAL_MOVE);
anim.start();
}
showDefaultImageView();
mCurrentPanel = view;
}
public ImagePreset getImagePreset() {
return mMasterImage.getPreset();
}
/**
public ImageFilter setImagePreset(ImageFilter filter, String name) {
ImagePreset copy = new ImagePreset(getImagePreset());
copy.add(filter);
copy.setHistoryName(name);
copy.setIsFx(false);
mMasterImage.setPreset(copy, true);
return filter;
}
*/
// TODO: remove this.
public void ensureFilter(String name) {
/*
ImagePreset preset = getImagePreset();
ImageFilter filter = preset.getFilter(name);
if (filter != null) {
// If we already have a filter, we might still want
// to push it onto the history stack.
ImagePreset copy = new ImagePreset(getImagePreset());
copy.setHistoryName(name);
mMasterImage.setPreset(copy, true);
filter = copy.getFilter(name);
}
if (filter == null) {
ImageFilter filterInstance = mFilters.get(name);
if (filterInstance != null) {
try {
ImageFilter newFilter = filterInstance.clone();
newFilter.reset();
filter = setImagePreset(newFilter, name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
if (filter != null) {
mMasterImage.setCurrentFilter(filter);
}
*/
}
public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
if (f != null) {
// FIXME: this check shouldn't be necessary
doPanelTransition = f.showUtilityPanel();
}
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
- if (filter.getEditingViewId() != 0) {
+ if (filter != null && filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
if (filter.getTextId() != 0) {
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
}
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
MasterImage.getImage().invalidateFiltersOnly();
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
public void setEditorPlaceHolder(EditorPlaceHolder editorPlaceHolder) {
mEditorPlaceHolder = editorPlaceHolder;
}
}
| true | true | public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
if (f != null) {
// FIXME: this check shouldn't be necessary
doPanelTransition = f.showUtilityPanel();
}
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
if (filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
if (filter.getTextId() != 0) {
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
}
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
MasterImage.getImage().invalidateFiltersOnly();
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
| public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
if (f != null) {
// FIXME: this check shouldn't be necessary
doPanelTransition = f.showUtilityPanel();
}
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
if (filter != null && filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
if (filter.getTextId() != 0) {
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
}
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
MasterImage.getImage().invalidateFiltersOnly();
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
|
diff --git a/src/main/java/org/rzo/yajsw/wrapper/FileUtils.java b/src/main/java/org/rzo/yajsw/wrapper/FileUtils.java
index 286e803..3f1e02f 100644
--- a/src/main/java/org/rzo/yajsw/wrapper/FileUtils.java
+++ b/src/main/java/org/rzo/yajsw/wrapper/FileUtils.java
@@ -1,223 +1,223 @@
/* This library 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.
* <p/>
* This library 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.
*/
package org.rzo.yajsw.wrapper;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Logger;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.configuration.EnvironmentConfiguration;
import org.apache.commons.io.filefilter.WildcardFileFilter;
// TODO: Auto-generated Javadoc
/**
* The Class FileUtils.
*/
public class FileUtils
{
/** The log. */
static Logger log = Logger.getLogger(FileUtils.class.getName());
/**
* Gets the files.
*
* @param workingDir
* the working dir
* @param pattern
* the pattern
*
* @return the files
*/
public static Collection getFiles(String workingDir, String pattern)
{
ArrayList result = new ArrayList();
// check if we have a non patterned file name
File res = new File(pattern);
if (res.exists() && res.isAbsolute())
{
result.add(res);
return result;
}
// pk-20080626: added working dir
// res = new File(workingDir, pattern);
File workingDirectory = new File(workingDir);
res = new File(workingDirectory.getAbsolutePath(), pattern);
// System.out.println("FileUtils: filename="+res+", exists:"+res.exists());
if (res.exists())
{
result.add(res);
return result;
}
// so this must be a pattern try to figure out the files
// does not work -> without separator
//String[] s = pattern.split("[" + File.separator + "|/]");
String[] s = pattern.split("[\\\\|/]");
String[] sh;
if (s.length == 1)
{
sh = new String[2];
sh[0] = ".";
sh[1] = s[0];
}
else
sh = s;
Collection paths = new HashSet();
paths.add(sh[0]);
for (int i = 1; i < sh.length; i++)
{
String file = sh[i];
if (file.trim().length() == 0)
continue;
Collection newPaths = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();)
{
String pathStr = (String) it.next();
- if (pathStr.endsWith(":"))
+ if (pathStr.endsWith(":") || pathStr.isEmpty())
pathStr += "/";
File path = new File(pathStr);
if ((!path.isDirectory()) || (!path.exists()) || (!(path.isAbsolute())))
path = new File(workingDir, pathStr);
Collection files = getWildcardFiles(path.getAbsolutePath(), file);
for (Iterator it2 = files.iterator(); it2.hasNext();)
{
File f = (File) it2.next();
if (f.isDirectory())
newPaths.add(f.getPath());
else if (f.isFile())
result.add(f);
}
}
paths = newPaths;
}
/*
* String file = s[s.length-1]; String path = pattern.substring(0,
* pattern.lastIndexOf(file));
*
* if (path == null || path.equals("")) path = "."; File fPath = null;
* try { fPath = new File(path); if (!fPath.isDirectory()) {
* log.warning(
* "classpath directory "+fPath.getCanonicalPath()+" not found"); return
* result; } } catch (Exception ex) {
* log.warning("classpath directory "+path+" error" + ex.getMessage());
* return result; } FileFilter fileFilter = new
* WildcardFileFilter(file); File[] thisFiles =
* fPath.listFiles(fileFilter); for (int i=0; i< thisFiles.length; i++)
* { File f = thisFiles[i]; if (f.exists()) result.add(f); else
* log.warning("classpath file "+f.getName() +"not found"); }
*/
if (result.size() == 0)
log.warning("No files found for " + pattern);
return result;
}
/**
* Gets the wildcard files.
*
* @param path
* the path
* @param file
* the file
*
* @return the wildcard files
*/
private static Collection getWildcardFiles(String path, String file)
{
ArrayList result = new ArrayList();
file = file.trim();
if (file.equals(".") || file.equals(".."))
{
result.add(new File(path+"/"+file));
return result;
}
File fPath = new File(path);
try
{
if (!fPath.isDirectory())
{
log.warning("classpath directory " + fPath.getCanonicalPath() + " not found");
return result;
}
}
catch (Exception ex)
{
log.warning("classpath directory " + path + " error" + ex.getMessage());
return result;
}
FileFilter fileFilter = new WildcardFileFilter(file);
File[] thisFiles = fPath.listFiles(fileFilter);
for (int i = 0; i < thisFiles.length; i++)
{
File f = thisFiles[i];
if (f.exists())
result.add(f);
else
log.warning("classpath file " + f.getName() + "not found");
}
return result;
}
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args)
{
System.out.println(getFiles(".", "z:\\dev\\yajsw\\..\\yajsw\\*.jar").size());
try
{
// String
// fileName=FilenameUtils.separatorsToSystem("C:\\init\\MOBILEguard\\yajsw/lib/jvmstat/*.jar");
// System.out.println("FileName: "+fileName);
CompositeConfiguration compConfig = new CompositeConfiguration();
AbstractConfiguration configuraton = new BaseConfiguration();
compConfig.addConfiguration(new EnvironmentConfiguration());
configuraton.setProperty("wrapper.java.classpath.1", "${VERSANT_ROOT}/lib/jvi.*jar");
configuraton.setProperty("wrapper.java.classpath.2", "${GROOVY_HOME}/lib/*.jar");
compConfig.addConfiguration(configuraton);
System.out.println("Configuration: " + ConfigurationConverter.getProperties(compConfig));
System.out.println("subset: " + ConfigurationConverter.getProperties(compConfig.subset("wrapper.java")));
// Collection files=FileUtils.getFiles("../..",
// "C:/versant/7_0_1/lib/jvi*.jar");
// Collection collection=
// org.apache.commons.io.FileUtils.listFiles(new File("C:/"),
// new WildcardFileFilter("jvi*.jar"), new
// WildcardFileFilter("*jar"));
// File[] files= new
// File("C:").listFiles((FilenameFilter)FileFilterUtils.nameFileFilter("C:/versant/7_0_1/lib/jvi*.jar"));
//
// FileUtils.getFiles("C:/versant/7_0_1/lib/", "jvi*.jar");
// System.out.println("FileList="+
// FileUtils.getFiles("C:/versant/7_0_1/lib/", "jvi*.jar"));
// java.util.Arrays.asList(files));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
| true | true | public static Collection getFiles(String workingDir, String pattern)
{
ArrayList result = new ArrayList();
// check if we have a non patterned file name
File res = new File(pattern);
if (res.exists() && res.isAbsolute())
{
result.add(res);
return result;
}
// pk-20080626: added working dir
// res = new File(workingDir, pattern);
File workingDirectory = new File(workingDir);
res = new File(workingDirectory.getAbsolutePath(), pattern);
// System.out.println("FileUtils: filename="+res+", exists:"+res.exists());
if (res.exists())
{
result.add(res);
return result;
}
// so this must be a pattern try to figure out the files
// does not work -> without separator
//String[] s = pattern.split("[" + File.separator + "|/]");
String[] s = pattern.split("[\\\\|/]");
String[] sh;
if (s.length == 1)
{
sh = new String[2];
sh[0] = ".";
sh[1] = s[0];
}
else
sh = s;
Collection paths = new HashSet();
paths.add(sh[0]);
for (int i = 1; i < sh.length; i++)
{
String file = sh[i];
if (file.trim().length() == 0)
continue;
Collection newPaths = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();)
{
String pathStr = (String) it.next();
if (pathStr.endsWith(":"))
pathStr += "/";
File path = new File(pathStr);
if ((!path.isDirectory()) || (!path.exists()) || (!(path.isAbsolute())))
path = new File(workingDir, pathStr);
Collection files = getWildcardFiles(path.getAbsolutePath(), file);
for (Iterator it2 = files.iterator(); it2.hasNext();)
{
File f = (File) it2.next();
if (f.isDirectory())
newPaths.add(f.getPath());
else if (f.isFile())
result.add(f);
}
}
paths = newPaths;
}
/*
* String file = s[s.length-1]; String path = pattern.substring(0,
* pattern.lastIndexOf(file));
*
* if (path == null || path.equals("")) path = "."; File fPath = null;
* try { fPath = new File(path); if (!fPath.isDirectory()) {
* log.warning(
* "classpath directory "+fPath.getCanonicalPath()+" not found"); return
* result; } } catch (Exception ex) {
* log.warning("classpath directory "+path+" error" + ex.getMessage());
* return result; } FileFilter fileFilter = new
* WildcardFileFilter(file); File[] thisFiles =
* fPath.listFiles(fileFilter); for (int i=0; i< thisFiles.length; i++)
* { File f = thisFiles[i]; if (f.exists()) result.add(f); else
* log.warning("classpath file "+f.getName() +"not found"); }
*/
if (result.size() == 0)
log.warning("No files found for " + pattern);
return result;
}
| public static Collection getFiles(String workingDir, String pattern)
{
ArrayList result = new ArrayList();
// check if we have a non patterned file name
File res = new File(pattern);
if (res.exists() && res.isAbsolute())
{
result.add(res);
return result;
}
// pk-20080626: added working dir
// res = new File(workingDir, pattern);
File workingDirectory = new File(workingDir);
res = new File(workingDirectory.getAbsolutePath(), pattern);
// System.out.println("FileUtils: filename="+res+", exists:"+res.exists());
if (res.exists())
{
result.add(res);
return result;
}
// so this must be a pattern try to figure out the files
// does not work -> without separator
//String[] s = pattern.split("[" + File.separator + "|/]");
String[] s = pattern.split("[\\\\|/]");
String[] sh;
if (s.length == 1)
{
sh = new String[2];
sh[0] = ".";
sh[1] = s[0];
}
else
sh = s;
Collection paths = new HashSet();
paths.add(sh[0]);
for (int i = 1; i < sh.length; i++)
{
String file = sh[i];
if (file.trim().length() == 0)
continue;
Collection newPaths = new HashSet();
for (Iterator it = paths.iterator(); it.hasNext();)
{
String pathStr = (String) it.next();
if (pathStr.endsWith(":") || pathStr.isEmpty())
pathStr += "/";
File path = new File(pathStr);
if ((!path.isDirectory()) || (!path.exists()) || (!(path.isAbsolute())))
path = new File(workingDir, pathStr);
Collection files = getWildcardFiles(path.getAbsolutePath(), file);
for (Iterator it2 = files.iterator(); it2.hasNext();)
{
File f = (File) it2.next();
if (f.isDirectory())
newPaths.add(f.getPath());
else if (f.isFile())
result.add(f);
}
}
paths = newPaths;
}
/*
* String file = s[s.length-1]; String path = pattern.substring(0,
* pattern.lastIndexOf(file));
*
* if (path == null || path.equals("")) path = "."; File fPath = null;
* try { fPath = new File(path); if (!fPath.isDirectory()) {
* log.warning(
* "classpath directory "+fPath.getCanonicalPath()+" not found"); return
* result; } } catch (Exception ex) {
* log.warning("classpath directory "+path+" error" + ex.getMessage());
* return result; } FileFilter fileFilter = new
* WildcardFileFilter(file); File[] thisFiles =
* fPath.listFiles(fileFilter); for (int i=0; i< thisFiles.length; i++)
* { File f = thisFiles[i]; if (f.exists()) result.add(f); else
* log.warning("classpath file "+f.getName() +"not found"); }
*/
if (result.size() == 0)
log.warning("No files found for " + pattern);
return result;
}
|
diff --git a/apps/ibis/benchmarks/pingPong/PollingPingPong.java b/apps/ibis/benchmarks/pingPong/PollingPingPong.java
index 3c7c4ed9..742f2f05 100644
--- a/apps/ibis/benchmarks/pingPong/PollingPingPong.java
+++ b/apps/ibis/benchmarks/pingPong/PollingPingPong.java
@@ -1,179 +1,179 @@
/* $Id$ */
import ibis.ipl.*;
import java.util.Properties;
import java.util.Random;
import java.io.IOException;
class PollingPingPong {
static class Sender {
SendPort sport;
ReceivePort rport;
Sender(ReceivePort rport, SendPort sport) {
this.rport = rport;
this.sport = sport;
}
void send(int count, int repeat) throws Exception {
for (int r = 0; r < repeat; r++) {
long time = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
WriteMessage writeMessage = sport.newMessage();
writeMessage.finish();
ReadMessage readMessage = null;
while(readMessage == null) {
readMessage = rport.poll();
}
readMessage.finish();
// System.err.print(".");
}
time = System.currentTimeMillis() - time;
double speed = (time * 1000.0) / (double) count;
System.err.println("Latency: " + count + " calls took "
+ (time / 1000.0) + " seconds, time/call = " + speed
+ " micros");
}
}
}
static class ExplicitReceiver {
SendPort sport;
ReceivePort rport;
ExplicitReceiver(ReceivePort rport, SendPort sport) {
this.rport = rport;
this.sport = sport;
}
void receive(int count, int repeat) throws IOException {
for (int r = 0; r < repeat; r++) {
for (int i = 0; i < count; i++) {
ReadMessage readMessage = null;
while(readMessage == null) {
readMessage = rport.poll();
}
readMessage.finish();
WriteMessage writeMessage = sport.newMessage();
writeMessage.finish();
}
}
}
}
static Ibis ibis;
static Registry registry;
public static void connect(SendPort s, ReceivePortIdentifier ident) {
boolean success = false;
do {
try {
s.connect(ident);
success = true;
} catch (Exception e) {
try {
Thread.sleep(500);
} catch (Exception e2) {
// ignore
}
}
} while (!success);
}
public static ReceivePortIdentifier lookup(String name) throws Exception {
ReceivePortIdentifier temp = null;
do {
temp = registry.lookupReceivePort(name);
if (temp == null) {
try {
Thread.sleep(500);
} catch (Exception e) {
// ignore
}
}
} while (temp == null);
return temp;
}
public static void main(String[] args) {
int count = 100;
int repeat = 10;
int rank = 0, remoteRank = 1;
try {
StaticProperties s = new StaticProperties();
s.add("Serialization", "ibis");
s.add("Communication",
- "OneToOne, Reliable, ExplicitReceipt");
+ "Poll, OneToOne, Reliable, ExplicitReceipt");
s.add("worldmodel", "closed");
ibis = Ibis.createIbis(s, null);
registry = ibis.registry();
PortType t = ibis.createPortType("test type", s);
SendPort sport = t.createSendPort("send port");
ReceivePort rport;
// Latency lat = null;
IbisIdentifier master = registry.elect("latency");
if (master.equals(ibis.identifier())) {
rank = 0;
remoteRank = 1;
} else {
rank = 1;
remoteRank = 0;
}
if (rank == 0) {
rport = t.createReceivePort("test port 0");
rport.enableConnections();
ReceivePortIdentifier ident = lookup("test port 1");
connect(sport, ident);
Sender sender = new Sender(rport, sport);
sender.send(count, repeat);
} else {
ReceivePortIdentifier ident = lookup("test port 0");
connect(sport, ident);
rport = t.createReceivePort("test port 1");
rport.enableConnections();
ExplicitReceiver receiver = new ExplicitReceiver(rport,
sport);
receiver.receive(count, repeat);
}
/* free the send ports first */
sport.close();
rport.close();
ibis.end();
} catch (Exception e) {
System.err.println("Got exception " + e);
System.err.println("StackTrace:");
e.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
int count = 100;
int repeat = 10;
int rank = 0, remoteRank = 1;
try {
StaticProperties s = new StaticProperties();
s.add("Serialization", "ibis");
s.add("Communication",
"OneToOne, Reliable, ExplicitReceipt");
s.add("worldmodel", "closed");
ibis = Ibis.createIbis(s, null);
registry = ibis.registry();
PortType t = ibis.createPortType("test type", s);
SendPort sport = t.createSendPort("send port");
ReceivePort rport;
// Latency lat = null;
IbisIdentifier master = registry.elect("latency");
if (master.equals(ibis.identifier())) {
rank = 0;
remoteRank = 1;
} else {
rank = 1;
remoteRank = 0;
}
if (rank == 0) {
rport = t.createReceivePort("test port 0");
rport.enableConnections();
ReceivePortIdentifier ident = lookup("test port 1");
connect(sport, ident);
Sender sender = new Sender(rport, sport);
sender.send(count, repeat);
} else {
ReceivePortIdentifier ident = lookup("test port 0");
connect(sport, ident);
rport = t.createReceivePort("test port 1");
rport.enableConnections();
ExplicitReceiver receiver = new ExplicitReceiver(rport,
sport);
receiver.receive(count, repeat);
}
/* free the send ports first */
sport.close();
rport.close();
ibis.end();
} catch (Exception e) {
System.err.println("Got exception " + e);
System.err.println("StackTrace:");
e.printStackTrace();
}
}
| public static void main(String[] args) {
int count = 100;
int repeat = 10;
int rank = 0, remoteRank = 1;
try {
StaticProperties s = new StaticProperties();
s.add("Serialization", "ibis");
s.add("Communication",
"Poll, OneToOne, Reliable, ExplicitReceipt");
s.add("worldmodel", "closed");
ibis = Ibis.createIbis(s, null);
registry = ibis.registry();
PortType t = ibis.createPortType("test type", s);
SendPort sport = t.createSendPort("send port");
ReceivePort rport;
// Latency lat = null;
IbisIdentifier master = registry.elect("latency");
if (master.equals(ibis.identifier())) {
rank = 0;
remoteRank = 1;
} else {
rank = 1;
remoteRank = 0;
}
if (rank == 0) {
rport = t.createReceivePort("test port 0");
rport.enableConnections();
ReceivePortIdentifier ident = lookup("test port 1");
connect(sport, ident);
Sender sender = new Sender(rport, sport);
sender.send(count, repeat);
} else {
ReceivePortIdentifier ident = lookup("test port 0");
connect(sport, ident);
rport = t.createReceivePort("test port 1");
rport.enableConnections();
ExplicitReceiver receiver = new ExplicitReceiver(rport,
sport);
receiver.receive(count, repeat);
}
/* free the send ports first */
sport.close();
rport.close();
ibis.end();
} catch (Exception e) {
System.err.println("Got exception " + e);
System.err.println("StackTrace:");
e.printStackTrace();
}
}
|
diff --git a/src/com/librelio/activity/BillingActivity.java b/src/com/librelio/activity/BillingActivity.java
index a4c59c0..2e48672 100644
--- a/src/com/librelio/activity/BillingActivity.java
+++ b/src/com/librelio/activity/BillingActivity.java
@@ -1,525 +1,527 @@
/*
* 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 com.librelio.activity;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.android.vending.billing.IInAppBillingService;
import com.librelio.LibrelioApplication;
import com.librelio.base.BaseActivity;
import com.librelio.view.InputTextDialog;
import com.librelio.view.InputTextDialog.OnEnterValueListener;
import com.niveales.wind.R;
/**
* The class for purchases via Google Play
*
* @author Nikolay Moskvin <[email protected]>
*
*/
public class BillingActivity extends BaseActivity {
private static final String TAG = "BillingActivity";
// Only for test. Must always be FALSE!
private static final boolean TEST_MODE = false;
/*
* productId can be the following values:
* android.test.purchased
* android.test.canceled
* android.test.refunded
* android.test.item_unavailable
*/
private static final String TEST_PRODUCT_ID = "android.test.purchased";
private static final String PARAM_PRODUCT_ID = "@product_id";
private static final String PARAM_DATA = "@data";
private static final String PARAM_SIGNATURE = "@signature";
private static final String PARAM_URLSTRING = "@urlstring";
private static final String PARAM_CODE = "@code";
private static final String PARAM_CLIENT = "@client";
private static final String PARAM_APP = "@app";
private static final int CALLBACK_CODE = 101;
private static final int BILLING_RESPONSE_RESULT_OK = 0;
private static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1;
private static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
private static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 5;
private static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
private String fileName;
private String title;
private String subtitle;
private String productId;
private String productPrice;
private String productTitle;
private Button buy;
private Button cancel;
private Button subsYear;
private Button subsMonthly;
private Button subsCode;
private IInAppBillingService billingService;
private String ownedItemSignature = "";
private String ownedItemPurshaseData = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wait_bar);
if(!isNetworkConnected()){
showAlertDialog(CONNECTION_ALERT);
} else {
bindService(
new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn,
Context.BIND_AUTO_CREATE);
fileName = getIntent().getExtras().getString(DownloadActivity.FILE_NAME_KEY);
title = getIntent().getExtras().getString(DownloadActivity.TITLE_KEY);
subtitle = getIntent().getExtras().getString(DownloadActivity.SUBTITLE_KEY);
int finId = fileName.indexOf("/");
productId = fileName.substring(0, finId);
}
}
private void initViews() {
setContentView(R.layout.billing_activity);
buy = (Button)findViewById(R.id.billing_buy_button);
subsMonthly = (Button)findViewById(R.id.billing_subs_monthly);
subsYear = (Button)findViewById(R.id.billing_subs_year);
subsCode = (Button)findViewById(R.id.billing_subs_code_button);
cancel = (Button)findViewById(R.id.billing_cancel_button);
//
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//
if(productPrice == null){
buy.setVisibility(View.GONE);
} else {
buy.setText(productTitle + ": "+ productPrice);
buy.setOnClickListener(getBuyOnClick());
}
//
String abonnement = getResources().getString(R.string.abonnement_wind);
String year = getResources().getString(R.string.year);
String month = getResources().getString(R.string.month);
if(LibrelioApplication.isEnableYearlySubs(getContext())){
subsYear.setText(" " + abonnement + " 1 " + year + " ");
subsYear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainMagazineActivity.REQUEST_SUBS);
sendBroadcast(intent);
finish();
}
});
} else {
subsYear.setVisibility(View.GONE);
}
if(LibrelioApplication.isEnableMonthlySubs(getContext())){
subsMonthly.setText(" " + abonnement + " 1 " + month + " ");
subsMonthly.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainMagazineActivity.REQUEST_SUBS);
sendBroadcast(intent);
finish();
}
});
} else {
subsMonthly.setVisibility(View.GONE);
}
if (LibrelioApplication.isEnableCodeSubs(getContext())){
subsCode.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
InputTextDialog dialog = new InputTextDialog(getContext(),
getString(R.string.please_enter_your_code));
dialog.setOnEnterValueListener(onEnterValueListener);
dialog.show();
}
});
}else{
subsCode.setVisibility(View.GONE);
}
}
private ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
billingService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
billingService = IInAppBillingService.Stub.asInterface(service);
new AsyncTask<String, String, Bundle>() {
private Bundle ownedItems = null;
@Override
protected Bundle doInBackground(String... params) {
Bundle skuDetails = null;
try {
ArrayList<String> skuList = new ArrayList<String>();
skuList.add(productId);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
skuDetails = billingService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
ownedItems = billingService.getPurchases(3, getPackageName(), "inapp", null);
} catch (RemoteException e) {
Log.d(TAG, "InAppBillingService failed", e);
return null;
}
return skuDetails;
}
@Override
protected void onPostExecute(Bundle skuDetails) {
//If item was purchase then download begin without open billing activity
int getPurchaseResponse = ownedItems.getInt("RESPONSE_CODE");
if (TEST_MODE) {
getPurchaseResponse = -1;
}
if(getPurchaseResponse == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
for(String s : ownedSkus){
Log.d(TAG, productId + " already purchased? " + s);
}
if(ownedSkus.contains(productId)){
int idx = ownedSkus.indexOf(productId);
ArrayList<String> purchaseDataList =
ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList =
- ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
+ ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
+ Log.d(TAG,"[getPurchases] purchaseDataList: "+purchaseDataList);
+ Log.d(TAG,"[getPurchases] signatureList: "+signatureList);
if(purchaseDataList!=null){
ownedItemPurshaseData = purchaseDataList.get(idx);
}
if(signatureList!=null){
ownedItemSignature = signatureList.get(idx);
}
onDownloadAction(ownedItemPurshaseData,ownedItemSignature);
return;
}
}
//
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
Log.d(TAG, "response code was success");
ArrayList<String> details = skuDetails.getStringArrayList("DETAILS_LIST");
for (String detail : details) {
Log.d(TAG, "response = " + detail);
JSONObject object = null;
String sku = "";
String price = "";
try {
object = new JSONObject(detail);
sku = object.getString("productId");
price = object.getString("price");
productTitle = object.getString("title");
} catch (JSONException e) {
Log.e(TAG, "getSKU details failed", e);
}
if (sku.equals(productId)) {
productPrice = price;
}
}
}
initViews();
super.onPostExecute(skuDetails);
}
}.execute();
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, requestCode + " " + resultCode);
Log.d(TAG, "data = " + data.getExtras().getString("INAPP_PURCHASE_DATA"));
Log.d(TAG, "signature = " + data.getExtras().getString("INAPP_DATA_SIGNATURE"));
if (requestCode == CALLBACK_CODE) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK && purchaseData != null) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("productId");
String dataResponse = data.getExtras().getString("INAPP_PURCHASE_DATA");
String signatureResponse = data.getExtras().getString("INAPP_DATA_SIGNATURE");
Log.d(TAG, "You have bought the " + sku + ". Excellent choice, adventurer!");
onDownloadAction(dataResponse, signatureResponse);
} catch (JSONException e) {
Log.e(TAG, "Failed to parse purchase data.", e);
}
} else {
finish();
}
} else {
finish();
}
}
@Override
protected void onDestroy() {
if (isNetworkConnected()) {
unbindService(mServiceConn);
}
super.onDestroy();
}
protected void onDownloadAction(String dataResponse, String signatureResponse) {
new DownloadFromTempURLTask().execute(buildVerifyQuery(dataResponse, signatureResponse));
}
private OnClickListener getBuyOnClick(){
return new OnClickListener() {
@Override
public void onClick(View v) {
new PurchaseTask().execute();
}
};
}
private boolean isNetworkConnected() {
return LibrelioApplication.thereIsConnection(this);
}
private Context getContext(){
return this;
}
private String buildVerifyQuery(String dataResponse, String signatureResponse) {
StringBuilder query = new StringBuilder(
LibrelioApplication.getServerUrl(getContext()));
String comand = getString(R.string.command_android_verify)
.replace(";", "&")
.replace(PARAM_PRODUCT_ID, productId)
.replace(PARAM_DATA, Uri.encode(dataResponse))
.replace(PARAM_SIGNATURE, signatureResponse)
.replace(PARAM_URLSTRING,
LibrelioApplication.getUrlString(getContext(), fileName));
return query.append(comand).toString();
}
private String buildPswdQuery() {
StringBuilder query = new StringBuilder(
LibrelioApplication.getServerUrl(getContext()));
String comand = getString(R.string.command_pswd)
.replace(";", "&")
//TODO @Roman need insert code value
.replace(PARAM_CODE, "")
.replace(PARAM_URLSTRING,
LibrelioApplication.getUrlString(getContext(), fileName))
//TODO @Roman need check correct values
.replace(PARAM_CLIENT, LibrelioApplication.getClientName(getContext()))
.replace(PARAM_APP, LibrelioApplication.getMagazineName(getContext()));
return query.append(comand).toString();
}
private class DownloadFromTempURLTask extends AsyncTask<String, Void, HttpResponse>{
@Override
protected HttpResponse doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
String verifyQuery = params[0];
Log.d(TAG, "Verify query = " + verifyQuery);
try {
HttpGet httpget = new HttpGet(verifyQuery);
HttpClientParams.setRedirecting(httpclient.getParams(), false);
return httpclient.execute(httpget);
} catch (IllegalArgumentException e) {
Log.e(TAG, "URI is malformed", e);
} catch (ClientProtocolException e) {
Log.e(TAG, "Download failed", e);
} catch (IOException e) {
Log.e(TAG, "Download failed", e);
}
return null;
}
protected void onPostExecute(HttpResponse response) {
String tempURL = null;
if (null == response) {
//TODO: @Niko need check for this situation
showAlertDialog(DOWNLOAD_ALERT);
Log.w(TAG, "download response was null");
return;
}
Log.d(TAG, "status line: " + response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
DataInputStream bodyStream = null;
if (entity != null) {
try {
bodyStream = new DataInputStream(entity.getContent());
StringBuilder content = new StringBuilder();
if (null != bodyStream) {
String line = null;
while((line = bodyStream.readLine()) != null) {
content.append(line).append("\n");
}
}
Log.d(TAG, "body: " + content.toString());
} catch (Exception e) {
Log.e(TAG, "get content failed", e);
} finally {
try { bodyStream.close(); } catch (Exception e) {}
}
}
if (null != response.getAllHeaders()) {
for(Header h : response.getAllHeaders()){
if(h.getName().equalsIgnoreCase("location")){
tempURL = h.getValue();
}
Log.d(TAG, "header: " + h.getName() + " => " + h.getValue());
}
}
if(tempURL == null){
//Toast.makeText(getContext(), "Download failed", Toast.LENGTH_SHORT).show();
showAlertDialog(DOWNLOAD_ALERT);
return;
}
Intent intent = new Intent(getContext(), DownloadActivity.class);
intent.putExtra(DownloadActivity.FILE_NAME_KEY, fileName);
intent.putExtra(DownloadActivity.SUBTITLE_KEY, subtitle);
intent.putExtra(DownloadActivity.TITLE_KEY, title);
intent.putExtra(DownloadActivity.IS_TEMP_KEY, true);
intent.putExtra(DownloadActivity.IS_SAMPLE_KEY, false);
intent.putExtra(DownloadActivity.TEMP_URL_KEY, tempURL);
startActivity(intent);
};
}
private class PurchaseTask extends AsyncTask<String, String, Bundle>{
private Bundle ownedItems;
@Override
protected Bundle doInBackground(String... params) {
try {
ownedItems = billingService.getPurchases(3, getPackageName(), "inapp", null);
if (TEST_MODE) {
productId = TEST_PRODUCT_ID;
}
return billingService.getBuyIntent(3, getPackageName(), productId, "inapp", null);
} catch (RemoteException e) {
Log.e(TAG, "Problem with getBuyIntent", e);
}
return null;
}
protected void onPostExecute(Bundle result) {
super.onPostExecute(result);
if (null == result) {
//TODO: @Niko need check for this situation
return;
}
int response = result.getInt("RESPONSE_CODE");
Log.d(TAG, "Purchase response = " + response);
switch (response) {
case BILLING_RESPONSE_RESULT_USER_CANCELED:
case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE:
case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
Toast.makeText(getContext(), "Error!", Toast.LENGTH_LONG).show();
return;
}
if(response == BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED){
Log.d(TAG, productId + " ITEM_ALREADY_OWNED ");
if(ownedItemPurshaseData!=null&ownedItemSignature!=null){
if((!ownedItemPurshaseData.equals(""))&(!ownedItemSignature.equals(""))){
onDownloadAction(ownedItemPurshaseData,ownedItemSignature);
}
}
return;
} else if(response == BILLING_RESPONSE_RESULT_OK){
PendingIntent pendingIntent = result.getParcelable("BUY_INTENT");
Log.d(TAG, "pendingIntent = " + pendingIntent);
if (pendingIntent == null) {
Toast.makeText(getContext(), "Error!", Toast.LENGTH_LONG).show();
return;
}
try {
startIntentSenderForResult(pendingIntent.getIntentSender(), CALLBACK_CODE, new Intent(), 0, 0, 0);
} catch (SendIntentException e) {
Log.e(TAG, "Problem with startIntentSenderForResult", e);
}
}
}
}
private OnEnterValueListener onEnterValueListener = new OnEnterValueListener() {
@Override
public void onEnterValue(String value) {
Log.d(TAG, value);
}
};
}
| true | true | public void onServiceConnected(ComponentName name, IBinder service) {
billingService = IInAppBillingService.Stub.asInterface(service);
new AsyncTask<String, String, Bundle>() {
private Bundle ownedItems = null;
@Override
protected Bundle doInBackground(String... params) {
Bundle skuDetails = null;
try {
ArrayList<String> skuList = new ArrayList<String>();
skuList.add(productId);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
skuDetails = billingService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
ownedItems = billingService.getPurchases(3, getPackageName(), "inapp", null);
} catch (RemoteException e) {
Log.d(TAG, "InAppBillingService failed", e);
return null;
}
return skuDetails;
}
@Override
protected void onPostExecute(Bundle skuDetails) {
//If item was purchase then download begin without open billing activity
int getPurchaseResponse = ownedItems.getInt("RESPONSE_CODE");
if (TEST_MODE) {
getPurchaseResponse = -1;
}
if(getPurchaseResponse == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
for(String s : ownedSkus){
Log.d(TAG, productId + " already purchased? " + s);
}
if(ownedSkus.contains(productId)){
int idx = ownedSkus.indexOf(productId);
ArrayList<String> purchaseDataList =
ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList =
ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
if(purchaseDataList!=null){
ownedItemPurshaseData = purchaseDataList.get(idx);
}
if(signatureList!=null){
ownedItemSignature = signatureList.get(idx);
}
onDownloadAction(ownedItemPurshaseData,ownedItemSignature);
return;
}
}
//
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
Log.d(TAG, "response code was success");
ArrayList<String> details = skuDetails.getStringArrayList("DETAILS_LIST");
for (String detail : details) {
Log.d(TAG, "response = " + detail);
JSONObject object = null;
String sku = "";
String price = "";
try {
object = new JSONObject(detail);
sku = object.getString("productId");
price = object.getString("price");
productTitle = object.getString("title");
} catch (JSONException e) {
Log.e(TAG, "getSKU details failed", e);
}
if (sku.equals(productId)) {
productPrice = price;
}
}
}
initViews();
super.onPostExecute(skuDetails);
}
}.execute();
}
| public void onServiceConnected(ComponentName name, IBinder service) {
billingService = IInAppBillingService.Stub.asInterface(service);
new AsyncTask<String, String, Bundle>() {
private Bundle ownedItems = null;
@Override
protected Bundle doInBackground(String... params) {
Bundle skuDetails = null;
try {
ArrayList<String> skuList = new ArrayList<String>();
skuList.add(productId);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
skuDetails = billingService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
ownedItems = billingService.getPurchases(3, getPackageName(), "inapp", null);
} catch (RemoteException e) {
Log.d(TAG, "InAppBillingService failed", e);
return null;
}
return skuDetails;
}
@Override
protected void onPostExecute(Bundle skuDetails) {
//If item was purchase then download begin without open billing activity
int getPurchaseResponse = ownedItems.getInt("RESPONSE_CODE");
if (TEST_MODE) {
getPurchaseResponse = -1;
}
if(getPurchaseResponse == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
for(String s : ownedSkus){
Log.d(TAG, productId + " already purchased? " + s);
}
if(ownedSkus.contains(productId)){
int idx = ownedSkus.indexOf(productId);
ArrayList<String> purchaseDataList =
ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList =
ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
Log.d(TAG,"[getPurchases] purchaseDataList: "+purchaseDataList);
Log.d(TAG,"[getPurchases] signatureList: "+signatureList);
if(purchaseDataList!=null){
ownedItemPurshaseData = purchaseDataList.get(idx);
}
if(signatureList!=null){
ownedItemSignature = signatureList.get(idx);
}
onDownloadAction(ownedItemPurshaseData,ownedItemSignature);
return;
}
}
//
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
Log.d(TAG, "response code was success");
ArrayList<String> details = skuDetails.getStringArrayList("DETAILS_LIST");
for (String detail : details) {
Log.d(TAG, "response = " + detail);
JSONObject object = null;
String sku = "";
String price = "";
try {
object = new JSONObject(detail);
sku = object.getString("productId");
price = object.getString("price");
productTitle = object.getString("title");
} catch (JSONException e) {
Log.e(TAG, "getSKU details failed", e);
}
if (sku.equals(productId)) {
productPrice = price;
}
}
}
initViews();
super.onPostExecute(skuDetails);
}
}.execute();
}
|
diff --git a/src/frontend/org/voltdb/planner/QueryPlanner.java b/src/frontend/org/voltdb/planner/QueryPlanner.java
index c7792ab6c..024d156d6 100644
--- a/src/frontend/org/voltdb/planner/QueryPlanner.java
+++ b/src/frontend/org/voltdb/planner/QueryPlanner.java
@@ -1,315 +1,315 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2010 VoltDB L.L.C.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.planner;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.hsqldb.HSQLInterface;
import org.hsqldb.HSQLInterface.HSQLParseException;
import org.json.JSONException;
import org.json.JSONObject;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.compiler.DatabaseEstimates;
import org.voltdb.compiler.ScalarValueHints;
import org.voltdb.planner.microoptimizations.MicroOptimizationRunner;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.plannodes.PlanNodeList;
import org.voltdb.utils.BuildDirectoryUtils;
/**
* The query planner accepts catalog data, SQL statements from the catalog, then
* outputs the plan with the lowest cost according to the cost model.
*
*/
public class QueryPlanner {
PlanAssembler m_assembler;
HSQLInterface m_HSQL;
DatabaseEstimates m_estimates;
Cluster m_cluster;
Database m_db;
String m_recentErrorMsg;
boolean m_useGlobalIds;
boolean m_quietPlanner;
final PlannerContext m_context;
/**
* Initialize planner with physical schema info and a reference to HSQLDB parser.
*
* @param catalogCluster Catalog info about the physical layout of the cluster.
* @param catalogDb Catalog info about schema, metadata and procedures.
* @param HSQL HSQLInterface pointer used for parsing SQL into XML.
* @param useGlobalIds
*/
public QueryPlanner(Cluster catalogCluster, Database catalogDb,
HSQLInterface HSQL, DatabaseEstimates estimates,
boolean useGlobalIds, boolean suppressDebugOutput) {
assert(HSQL != null);
assert(catalogCluster != null);
assert(catalogDb != null);
m_HSQL = HSQL;
m_context = new PlannerContext();
m_assembler = new PlanAssembler(m_context, catalogCluster, catalogDb);
m_db = catalogDb;
m_cluster = catalogCluster;
m_estimates = estimates;
m_useGlobalIds = useGlobalIds;
m_quietPlanner = suppressDebugOutput;
}
/**
* Get the best plan for the SQL statement given, assuming the given costModel.
*
* @param costModel The current cost model to evaluate plans with.
* @param sql SQL stmt text to be planned.
* @param stmtName The name of the sql statement to be planned.
* @param procName The name of the procedure containing the sql statement to be planned.
* @param singlePartition Is the stmt single-partition?
* @param paramHints
* @return The best plan found for the SQL statement or null if none can be found.
*/
public CompiledPlan compilePlan(AbstractCostModel costModel, String sql, String stmtName, String procName, boolean singlePartition, ScalarValueHints[] paramHints) {
assert(costModel != null);
assert(sql != null);
assert(stmtName != null);
assert(procName != null);
// reset any error message
m_recentErrorMsg = null;
// set the usage of global ids in the plan assembler
PlanAssembler.setUseGlobalIds(m_useGlobalIds);
// use HSQLDB to get XML that describes the semantics of the statement
// this is much easier to parse than SQL and is checked against the catalog
String xmlSQL = null;
try {
xmlSQL = m_HSQL.getXMLCompiledStatement(sql);
} catch (HSQLParseException e) {
// XXXLOG probably want a real log message here
m_recentErrorMsg = e.getMessage();
return null;
}
if (!m_quietPlanner)
{
// output the xml from hsql to disk for debugging
PrintStream xmlDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-hsql-xml", procName + "_" + stmtName + ".xml");
xmlDebugOut.println(xmlSQL);
xmlDebugOut.close();
}
// get a parsed statement from the xml
AbstractParsedStmt initialParsedStmt = null;
try {
initialParsedStmt = AbstractParsedStmt.parse(sql, xmlSQL, m_db);
}
catch (Exception e) {
m_recentErrorMsg = e.getMessage();
return null;
}
if (initialParsedStmt == null)
{
m_recentErrorMsg = "Failed to parse SQL statement: " + sql;
return null;
}
if (!m_quietPlanner)
{
// output a description of the parsed stmt
PrintStream parsedDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-parsed", procName + "_" + stmtName + ".txt");
parsedDebugOut.println(initialParsedStmt.toString());
parsedDebugOut.close();
}
// get ready to find the plan with minimal cost
CompiledPlan rawplan = null;
CompiledPlan bestPlan = null;
double minCost = Double.MAX_VALUE;
HashMap<String, String> planOutputs = new HashMap<String, String>();
HashMap<String, String> dotPlanOutputs = new HashMap<String, String>();
String winnerName = "";
// index of the currently being "costed" plan
int i = 0;
PlanStatistics stats = null;
// iterate though all the variations on the abstract parsed stmts
for (AbstractParsedStmt parsedStmt : ExpressionEquivalenceProcessor.getEquivalentStmts(initialParsedStmt)) {
// set up the plan assembler for this particular plan
m_assembler.setupForNewPlans(parsedStmt, singlePartition);
// loop over all possible plans
while (true) {
try {
rawplan = m_assembler.getNextPlan();
}
// on exception, set the error message and bail...
catch (PlanningErrorException e) {
m_recentErrorMsg = e.getMessage();
return null;
}
// stop this while loop when no more plans are generated
if (rawplan == null)
break;
// run the set of microptimizations, which may return many plans (or not)
List<CompiledPlan> optimizedPlans = MicroOptimizationRunner.applyAll(rawplan);
// iterate through the subset of plans
for (CompiledPlan plan : optimizedPlans) {
// compute resource usage using the single stats collector
stats = new PlanStatistics();
AbstractPlanNode planGraph = plan.fragments.get(0).planGraph;
// compute statistics about a plan
boolean result = planGraph.computeEstimatesRecursively(stats, m_cluster, m_db, m_estimates, paramHints);
assert(result);
// GENERATE JSON DEBUGGING OUTPUT BEFORE WE CLEAN UP THE
// PlanColumns
// convert a tree into an execution list
PlanNodeList nodeList = new PlanNodeList(planGraph);
// get the json serialized version of the plan
String json = null;
try {
String crunchJson = nodeList.toJSONString();
//System.out.println(crunchJson);
//System.out.flush();
JSONObject jobj = new JSONObject(crunchJson);
json = jobj.toString(4);
} catch (JSONException e2) {
// Any plan that can't be serialized to JSON to
// write to debugging output is also going to fail
// to get written to the catalog, to sysprocs, etc.
// Just bail.
m_recentErrorMsg = "Plan for sql: '" + sql +
"' can't be serialized to JSON";
return null;
}
// compute the cost based on the resources using the current cost model
double cost = costModel.getPlanCost(stats);
// find the minimum cost plan
if (cost < minCost) {
minCost = cost;
// free the PlanColumns held by the previous best plan
if (bestPlan != null)
{
bestPlan.freePlan(m_context);
}
bestPlan = plan;
}
else
{
plan.freePlan(m_context);
}
// output a description of the parsed stmt
String filename = String.valueOf(i++);
if (bestPlan == plan) winnerName = filename;
json = "COST: " + String.valueOf(cost) + "\n" + json;
planOutputs.put(filename, json);
// create a graph friendly version
dotPlanOutputs.put(filename, nodeList.toDOTString("name"));
}
}
}
// make sure we got a winner
if (bestPlan == null) {
m_recentErrorMsg = "Unable to plan for statement. Error unknown.";
return null;
}
// reset all the plan node ids for a given plan
bestPlan.resetPlanNodeIds();
if (!m_quietPlanner)
{
// print all the plans to disk for debugging
for (Entry<String, String> output : planOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".txt");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
for (Entry<String, String> output : dotPlanOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".dot");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
// output the plan statistics to disk for debugging
PrintStream plansOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-stats", procName + "_" + stmtName + ".txt");
plansOut.println(stats.toString());
plansOut.close();
}
// split up the plan everywhere we see send/recieve into multiple plan fragments
bestPlan = Fragmentizer.fragmentize(bestPlan, m_db);
// DTXN/EE can't handle plans that have more than 2 fragments yet.
if (bestPlan.fragments.size() > 2) {
m_recentErrorMsg = "Unable to plan for statement. Likely statement is "+
- "joining two partitioned tables in a multi-partition stamtent. " +
+ "joining two partitioned tables in a multi-partition statement. " +
"This is not supported at this time.";
return null;
}
return bestPlan;
}
public PlannerContext getPlannerContext() {
return m_context;
}
public String getErrorMessage() {
return m_recentErrorMsg;
}
}
| true | true | public CompiledPlan compilePlan(AbstractCostModel costModel, String sql, String stmtName, String procName, boolean singlePartition, ScalarValueHints[] paramHints) {
assert(costModel != null);
assert(sql != null);
assert(stmtName != null);
assert(procName != null);
// reset any error message
m_recentErrorMsg = null;
// set the usage of global ids in the plan assembler
PlanAssembler.setUseGlobalIds(m_useGlobalIds);
// use HSQLDB to get XML that describes the semantics of the statement
// this is much easier to parse than SQL and is checked against the catalog
String xmlSQL = null;
try {
xmlSQL = m_HSQL.getXMLCompiledStatement(sql);
} catch (HSQLParseException e) {
// XXXLOG probably want a real log message here
m_recentErrorMsg = e.getMessage();
return null;
}
if (!m_quietPlanner)
{
// output the xml from hsql to disk for debugging
PrintStream xmlDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-hsql-xml", procName + "_" + stmtName + ".xml");
xmlDebugOut.println(xmlSQL);
xmlDebugOut.close();
}
// get a parsed statement from the xml
AbstractParsedStmt initialParsedStmt = null;
try {
initialParsedStmt = AbstractParsedStmt.parse(sql, xmlSQL, m_db);
}
catch (Exception e) {
m_recentErrorMsg = e.getMessage();
return null;
}
if (initialParsedStmt == null)
{
m_recentErrorMsg = "Failed to parse SQL statement: " + sql;
return null;
}
if (!m_quietPlanner)
{
// output a description of the parsed stmt
PrintStream parsedDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-parsed", procName + "_" + stmtName + ".txt");
parsedDebugOut.println(initialParsedStmt.toString());
parsedDebugOut.close();
}
// get ready to find the plan with minimal cost
CompiledPlan rawplan = null;
CompiledPlan bestPlan = null;
double minCost = Double.MAX_VALUE;
HashMap<String, String> planOutputs = new HashMap<String, String>();
HashMap<String, String> dotPlanOutputs = new HashMap<String, String>();
String winnerName = "";
// index of the currently being "costed" plan
int i = 0;
PlanStatistics stats = null;
// iterate though all the variations on the abstract parsed stmts
for (AbstractParsedStmt parsedStmt : ExpressionEquivalenceProcessor.getEquivalentStmts(initialParsedStmt)) {
// set up the plan assembler for this particular plan
m_assembler.setupForNewPlans(parsedStmt, singlePartition);
// loop over all possible plans
while (true) {
try {
rawplan = m_assembler.getNextPlan();
}
// on exception, set the error message and bail...
catch (PlanningErrorException e) {
m_recentErrorMsg = e.getMessage();
return null;
}
// stop this while loop when no more plans are generated
if (rawplan == null)
break;
// run the set of microptimizations, which may return many plans (or not)
List<CompiledPlan> optimizedPlans = MicroOptimizationRunner.applyAll(rawplan);
// iterate through the subset of plans
for (CompiledPlan plan : optimizedPlans) {
// compute resource usage using the single stats collector
stats = new PlanStatistics();
AbstractPlanNode planGraph = plan.fragments.get(0).planGraph;
// compute statistics about a plan
boolean result = planGraph.computeEstimatesRecursively(stats, m_cluster, m_db, m_estimates, paramHints);
assert(result);
// GENERATE JSON DEBUGGING OUTPUT BEFORE WE CLEAN UP THE
// PlanColumns
// convert a tree into an execution list
PlanNodeList nodeList = new PlanNodeList(planGraph);
// get the json serialized version of the plan
String json = null;
try {
String crunchJson = nodeList.toJSONString();
//System.out.println(crunchJson);
//System.out.flush();
JSONObject jobj = new JSONObject(crunchJson);
json = jobj.toString(4);
} catch (JSONException e2) {
// Any plan that can't be serialized to JSON to
// write to debugging output is also going to fail
// to get written to the catalog, to sysprocs, etc.
// Just bail.
m_recentErrorMsg = "Plan for sql: '" + sql +
"' can't be serialized to JSON";
return null;
}
// compute the cost based on the resources using the current cost model
double cost = costModel.getPlanCost(stats);
// find the minimum cost plan
if (cost < minCost) {
minCost = cost;
// free the PlanColumns held by the previous best plan
if (bestPlan != null)
{
bestPlan.freePlan(m_context);
}
bestPlan = plan;
}
else
{
plan.freePlan(m_context);
}
// output a description of the parsed stmt
String filename = String.valueOf(i++);
if (bestPlan == plan) winnerName = filename;
json = "COST: " + String.valueOf(cost) + "\n" + json;
planOutputs.put(filename, json);
// create a graph friendly version
dotPlanOutputs.put(filename, nodeList.toDOTString("name"));
}
}
}
// make sure we got a winner
if (bestPlan == null) {
m_recentErrorMsg = "Unable to plan for statement. Error unknown.";
return null;
}
// reset all the plan node ids for a given plan
bestPlan.resetPlanNodeIds();
if (!m_quietPlanner)
{
// print all the plans to disk for debugging
for (Entry<String, String> output : planOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".txt");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
for (Entry<String, String> output : dotPlanOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".dot");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
// output the plan statistics to disk for debugging
PrintStream plansOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-stats", procName + "_" + stmtName + ".txt");
plansOut.println(stats.toString());
plansOut.close();
}
// split up the plan everywhere we see send/recieve into multiple plan fragments
bestPlan = Fragmentizer.fragmentize(bestPlan, m_db);
// DTXN/EE can't handle plans that have more than 2 fragments yet.
if (bestPlan.fragments.size() > 2) {
m_recentErrorMsg = "Unable to plan for statement. Likely statement is "+
"joining two partitioned tables in a multi-partition stamtent. " +
"This is not supported at this time.";
return null;
}
return bestPlan;
}
| public CompiledPlan compilePlan(AbstractCostModel costModel, String sql, String stmtName, String procName, boolean singlePartition, ScalarValueHints[] paramHints) {
assert(costModel != null);
assert(sql != null);
assert(stmtName != null);
assert(procName != null);
// reset any error message
m_recentErrorMsg = null;
// set the usage of global ids in the plan assembler
PlanAssembler.setUseGlobalIds(m_useGlobalIds);
// use HSQLDB to get XML that describes the semantics of the statement
// this is much easier to parse than SQL and is checked against the catalog
String xmlSQL = null;
try {
xmlSQL = m_HSQL.getXMLCompiledStatement(sql);
} catch (HSQLParseException e) {
// XXXLOG probably want a real log message here
m_recentErrorMsg = e.getMessage();
return null;
}
if (!m_quietPlanner)
{
// output the xml from hsql to disk for debugging
PrintStream xmlDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-hsql-xml", procName + "_" + stmtName + ".xml");
xmlDebugOut.println(xmlSQL);
xmlDebugOut.close();
}
// get a parsed statement from the xml
AbstractParsedStmt initialParsedStmt = null;
try {
initialParsedStmt = AbstractParsedStmt.parse(sql, xmlSQL, m_db);
}
catch (Exception e) {
m_recentErrorMsg = e.getMessage();
return null;
}
if (initialParsedStmt == null)
{
m_recentErrorMsg = "Failed to parse SQL statement: " + sql;
return null;
}
if (!m_quietPlanner)
{
// output a description of the parsed stmt
PrintStream parsedDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-parsed", procName + "_" + stmtName + ".txt");
parsedDebugOut.println(initialParsedStmt.toString());
parsedDebugOut.close();
}
// get ready to find the plan with minimal cost
CompiledPlan rawplan = null;
CompiledPlan bestPlan = null;
double minCost = Double.MAX_VALUE;
HashMap<String, String> planOutputs = new HashMap<String, String>();
HashMap<String, String> dotPlanOutputs = new HashMap<String, String>();
String winnerName = "";
// index of the currently being "costed" plan
int i = 0;
PlanStatistics stats = null;
// iterate though all the variations on the abstract parsed stmts
for (AbstractParsedStmt parsedStmt : ExpressionEquivalenceProcessor.getEquivalentStmts(initialParsedStmt)) {
// set up the plan assembler for this particular plan
m_assembler.setupForNewPlans(parsedStmt, singlePartition);
// loop over all possible plans
while (true) {
try {
rawplan = m_assembler.getNextPlan();
}
// on exception, set the error message and bail...
catch (PlanningErrorException e) {
m_recentErrorMsg = e.getMessage();
return null;
}
// stop this while loop when no more plans are generated
if (rawplan == null)
break;
// run the set of microptimizations, which may return many plans (or not)
List<CompiledPlan> optimizedPlans = MicroOptimizationRunner.applyAll(rawplan);
// iterate through the subset of plans
for (CompiledPlan plan : optimizedPlans) {
// compute resource usage using the single stats collector
stats = new PlanStatistics();
AbstractPlanNode planGraph = plan.fragments.get(0).planGraph;
// compute statistics about a plan
boolean result = planGraph.computeEstimatesRecursively(stats, m_cluster, m_db, m_estimates, paramHints);
assert(result);
// GENERATE JSON DEBUGGING OUTPUT BEFORE WE CLEAN UP THE
// PlanColumns
// convert a tree into an execution list
PlanNodeList nodeList = new PlanNodeList(planGraph);
// get the json serialized version of the plan
String json = null;
try {
String crunchJson = nodeList.toJSONString();
//System.out.println(crunchJson);
//System.out.flush();
JSONObject jobj = new JSONObject(crunchJson);
json = jobj.toString(4);
} catch (JSONException e2) {
// Any plan that can't be serialized to JSON to
// write to debugging output is also going to fail
// to get written to the catalog, to sysprocs, etc.
// Just bail.
m_recentErrorMsg = "Plan for sql: '" + sql +
"' can't be serialized to JSON";
return null;
}
// compute the cost based on the resources using the current cost model
double cost = costModel.getPlanCost(stats);
// find the minimum cost plan
if (cost < minCost) {
minCost = cost;
// free the PlanColumns held by the previous best plan
if (bestPlan != null)
{
bestPlan.freePlan(m_context);
}
bestPlan = plan;
}
else
{
plan.freePlan(m_context);
}
// output a description of the parsed stmt
String filename = String.valueOf(i++);
if (bestPlan == plan) winnerName = filename;
json = "COST: " + String.valueOf(cost) + "\n" + json;
planOutputs.put(filename, json);
// create a graph friendly version
dotPlanOutputs.put(filename, nodeList.toDOTString("name"));
}
}
}
// make sure we got a winner
if (bestPlan == null) {
m_recentErrorMsg = "Unable to plan for statement. Error unknown.";
return null;
}
// reset all the plan node ids for a given plan
bestPlan.resetPlanNodeIds();
if (!m_quietPlanner)
{
// print all the plans to disk for debugging
for (Entry<String, String> output : planOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".txt");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
for (Entry<String, String> output : dotPlanOutputs.entrySet()) {
String filename = output.getKey();
if (winnerName.equals(filename)) {
filename = "WINNER " + filename;
}
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".dot");
candidatePlanOut.println(output.getValue());
candidatePlanOut.close();
}
// output the plan statistics to disk for debugging
PrintStream plansOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-stats", procName + "_" + stmtName + ".txt");
plansOut.println(stats.toString());
plansOut.close();
}
// split up the plan everywhere we see send/recieve into multiple plan fragments
bestPlan = Fragmentizer.fragmentize(bestPlan, m_db);
// DTXN/EE can't handle plans that have more than 2 fragments yet.
if (bestPlan.fragments.size() > 2) {
m_recentErrorMsg = "Unable to plan for statement. Likely statement is "+
"joining two partitioned tables in a multi-partition statement. " +
"This is not supported at this time.";
return null;
}
return bestPlan;
}
|
diff --git a/wings2/demo/wingset/src/java/wingset/WingSetPane.java b/wings2/demo/wingset/src/java/wingset/WingSetPane.java
index 5bb9fb8d..b93e46f9 100644
--- a/wings2/demo/wingset/src/java/wingset/WingSetPane.java
+++ b/wings2/demo/wingset/src/java/wingset/WingSetPane.java
@@ -1,68 +1,68 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package wingset;
import org.wings.*;
import org.wings.event.SComponentAdapter;
import org.wings.event.SComponentEvent;
import org.wings.session.SessionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A basic WingSet Pane, which implements some often needed functions.
*
* @author <a href="mailto:[email protected]">Armin Haaf</a>
* @version $Revision$
*/
abstract public class WingSetPane extends SPanel implements SConstants {
protected final static transient Log log = LogFactory.getLog(WingSetPane.class);
private static final SResourceIcon SOURCE_LABEL_ICON = new SResourceIcon("org/wings/icons/File.gif");
private boolean initialized = false;
public WingSetPane() {
setLayout(createResourceTemplate("/templates/ContentLayout.thtml"));
- SAnchor anchor = new SAnchor("/wingset/" + getClass().getName().substring(getClass().getName().indexOf('.') + 1) + ".java");
+ SAnchor anchor = new SAnchor("../" + getClass().getName().substring(getClass().getName().indexOf('.') + 1) + ".java");
anchor.setTarget("sourceWindow");
anchor.add(new SLabel("view java source code", SOURCE_LABEL_ICON));
add(anchor, "viewSource");
addComponentListener(new SComponentAdapter() {
public void componentShown(SComponentEvent e) {
if (!initialized) {
SComponent exampleComponent = createExample();
exampleComponent.setHorizontalAlignment(SComponent.CENTER);
add(exampleComponent, "content"); // content generated by example
initialized = true;
}
}
});
}
/**
* Override this.
*/
protected abstract SComponent createExample();
protected static SLayoutManager createResourceTemplate(String name) {
try {
return new STemplateLayout(SessionManager.getSession().getServletContext().getRealPath(name));
} catch (Exception ex) {
log.error("Ex",ex);
}
return null;
}
}
| true | true | public WingSetPane() {
setLayout(createResourceTemplate("/templates/ContentLayout.thtml"));
SAnchor anchor = new SAnchor("/wingset/" + getClass().getName().substring(getClass().getName().indexOf('.') + 1) + ".java");
anchor.setTarget("sourceWindow");
anchor.add(new SLabel("view java source code", SOURCE_LABEL_ICON));
add(anchor, "viewSource");
addComponentListener(new SComponentAdapter() {
public void componentShown(SComponentEvent e) {
if (!initialized) {
SComponent exampleComponent = createExample();
exampleComponent.setHorizontalAlignment(SComponent.CENTER);
add(exampleComponent, "content"); // content generated by example
initialized = true;
}
}
});
}
| public WingSetPane() {
setLayout(createResourceTemplate("/templates/ContentLayout.thtml"));
SAnchor anchor = new SAnchor("../" + getClass().getName().substring(getClass().getName().indexOf('.') + 1) + ".java");
anchor.setTarget("sourceWindow");
anchor.add(new SLabel("view java source code", SOURCE_LABEL_ICON));
add(anchor, "viewSource");
addComponentListener(new SComponentAdapter() {
public void componentShown(SComponentEvent e) {
if (!initialized) {
SComponent exampleComponent = createExample();
exampleComponent.setHorizontalAlignment(SComponent.CENTER);
add(exampleComponent, "content"); // content generated by example
initialized = true;
}
}
});
}
|
diff --git a/core/src/visad/trunk/SocketServer.java b/core/src/visad/trunk/SocketServer.java
index 447aa7941..e30ef9dfb 100644
--- a/core/src/visad/trunk/SocketServer.java
+++ b/core/src/visad/trunk/SocketServer.java
@@ -1,292 +1,296 @@
//
// SocketServer.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 1999 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library 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 library 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 library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import java.rmi.RemoteException;
import java.util.Vector;
import visad.util.Util;
/** SocketServer wraps around a VisAD display, providing support for
stand-alone remote displays (i.e., not dependent on the VisAD packages)
that communicate with the server using sockets. For an example, see
examples/Test68.java together with the
<a href="http://www.ssec.wisc.edu/~curtis/visad-applet.html">
stand-alone VisADApplet</a> usable from within a web browser. */
public class SocketServer implements RemoteSlaveDisplay {
/** debugging flag */
private static final boolean DEBUG = false;
/** the default port for server/client communication */
private static final int DEFAULT_PORT = 4567;
/** the port at which the server communicates with clients */
private int port;
/** the server's associated VisAD display */
private DisplayImpl display;
/** flag that prevents getImage() calls from signaling a FRAME_DONE event */
private boolean flag;
/** array of image data extracted from the VisAD display */
private byte[] pix;
/** height of image */
private int h;
/** width of image */
private int w;
/** the server's associated socket */
private ServerSocket serverSocket;
/** vector of client sockets connected to the server */
private Vector clientSockets = new Vector();
/** vector of client sockets' input streams */
private Vector clientInputs = new Vector();
/** vector of client sockets' output streams */
private Vector clientOutputs = new Vector();
/** thread monitoring incoming clients */
private Thread connectThread = null;
/** thread monitoring communication between server and clients */
private Thread commThread = null;
/** whether the server is still alive */
private boolean alive = true;
/** whether the display update was triggered by a getImage() call */
private boolean trigger = false;
/** contains the code for monitoring incoming clients */
private Runnable connect = new Runnable() {
public void run() {
while (alive) {
try {
// wait for a new socket to connect
Socket socket = serverSocket.accept();
if (!alive) break;
synchronized (clientSockets) {
if (socket != null) {
// add client to the list
clientSockets.add(socket);
// add client's input and output streams to the list
DataInputStream in =
new DataInputStream(socket.getInputStream());
clientInputs.add(in);
DataOutputStream out =
new DataOutputStream(socket.getOutputStream());
clientOutputs.add(out);
}
}
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
}
};
/** contains the code for monitoring server/client communication */
private Runnable comm = new Runnable() {
public void run() {
while (alive) {
synchronized (clientSockets) {
for (int i=0; i<clientInputs.size(); i++) {
DataInputStream in = (DataInputStream) clientInputs.elementAt(i);
// check for client requests in the form of MouseEvent data
try {
if (in.available() > 0) {
// receive the MouseEvent data
int id = in.readInt();
long when = in.readLong();
int mods = in.readInt();
int x = in.readInt();
int y = in.readInt();
int clicks = in.readInt();
boolean popup = in.readBoolean();
if (id >= 0) {
// construct resulting MouseEvent and process it
Component c = display.getComponent();
MouseEvent me =
new MouseEvent(c, id, when, mods, x, y, clicks, popup);
MouseBehavior mb = display.getMouseBehavior();
MouseHelper mh = mb.getMouseHelper();
mh.processEvent(me);
}
else {
// client has requested a refresh
updateClient(i);
}
}
}
catch (SocketException exc) {
// there is a problem with this socket, so kill it
killSocket(i);
break;
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
+ try {
+ Thread.sleep(500);
+ }
+ catch (InterruptedException exc) { }
}
}
}
};
/** construct a SocketServer for the given VisAD display */
public SocketServer(DisplayImpl d) throws IOException {
this(d, DEFAULT_PORT);
}
/** construct a SocketServer for the given VisAD display,
and communicate with clients using the given port */
public SocketServer(DisplayImpl d, int port) throws IOException {
display = d;
this.port = port;
// create a server socket at the given port
serverSocket = new ServerSocket(port);
// create a thread that listens for connecting clients
connectThread = new Thread(connect);
connectThread.start();
// create a thread for client/server communication
commThread = new Thread(comm);
commThread.start();
// register socket server as a "slaved display"
display.addSlave(this);
}
/** get the socket port used by this SocketServer */
public int getPort() {
return port;
}
/** send the latest image from the display to the given output stream */
private void updateClient(int i) {
DataOutputStream out = (DataOutputStream) clientOutputs.elementAt(i);
if (pix != null) {
try {
// send image width, height and type to the output stream
out.writeInt(w);
out.writeInt(h);
// send pixel data to the output stream
out.write(pix);
}
catch (SocketException exc) {
// there is a problem with this socket, so kill it
killSocket(i);
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
else if (DEBUG) System.err.println("Null pixels!");
}
/** display automatically calls sendImage when its content changes */
public void sendImage(int[] pixels, int width, int height, int type)
throws RemoteException
{
// convert pixels to byte array
pix = Util.intToBytes(pixels);
w = width;
h = height;
// update all clients with the new image
synchronized (clientSockets) {
for (int i=0; i<clientSockets.size(); i++) updateClient(i);
}
}
/** shuts down the given socket, and removes it from the socket vector */
private void killSocket(int i) {
DataInputStream in = (DataInputStream) clientInputs.elementAt(i);
DataOutputStream out = (DataOutputStream) clientOutputs.elementAt(i);
Socket socket = (Socket) clientSockets.elementAt(i);
// shut down socket input stream
try {
in.close();
}
catch (IOException exc) { }
// shut down socket output stream
try {
out.close();
}
catch (IOException exc) { }
// shut down socket itself
try {
socket.close();
}
catch (IOException exc) { }
// remove socket from socket vectors
clientSockets.remove(i);
clientInputs.remove(i);
clientOutputs.remove(i);
}
/** destroys this server and kills all associated threads */
public void killServer() {
// set flag to cause server's threads to stop running
alive = false;
// shut down all client sockets
synchronized (clientSockets) {
while (clientSockets.size() > 0) killSocket(0);
}
// shut down server socket
try {
serverSocket.close();
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
}
| true | true | public void run() {
while (alive) {
synchronized (clientSockets) {
for (int i=0; i<clientInputs.size(); i++) {
DataInputStream in = (DataInputStream) clientInputs.elementAt(i);
// check for client requests in the form of MouseEvent data
try {
if (in.available() > 0) {
// receive the MouseEvent data
int id = in.readInt();
long when = in.readLong();
int mods = in.readInt();
int x = in.readInt();
int y = in.readInt();
int clicks = in.readInt();
boolean popup = in.readBoolean();
if (id >= 0) {
// construct resulting MouseEvent and process it
Component c = display.getComponent();
MouseEvent me =
new MouseEvent(c, id, when, mods, x, y, clicks, popup);
MouseBehavior mb = display.getMouseBehavior();
MouseHelper mh = mb.getMouseHelper();
mh.processEvent(me);
}
else {
// client has requested a refresh
updateClient(i);
}
}
}
catch (SocketException exc) {
// there is a problem with this socket, so kill it
killSocket(i);
break;
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
}
}
}
| public void run() {
while (alive) {
synchronized (clientSockets) {
for (int i=0; i<clientInputs.size(); i++) {
DataInputStream in = (DataInputStream) clientInputs.elementAt(i);
// check for client requests in the form of MouseEvent data
try {
if (in.available() > 0) {
// receive the MouseEvent data
int id = in.readInt();
long when = in.readLong();
int mods = in.readInt();
int x = in.readInt();
int y = in.readInt();
int clicks = in.readInt();
boolean popup = in.readBoolean();
if (id >= 0) {
// construct resulting MouseEvent and process it
Component c = display.getComponent();
MouseEvent me =
new MouseEvent(c, id, when, mods, x, y, clicks, popup);
MouseBehavior mb = display.getMouseBehavior();
MouseHelper mh = mb.getMouseHelper();
mh.processEvent(me);
}
else {
// client has requested a refresh
updateClient(i);
}
}
}
catch (SocketException exc) {
// there is a problem with this socket, so kill it
killSocket(i);
break;
}
catch (IOException exc) {
if (DEBUG) exc.printStackTrace();
}
}
try {
Thread.sleep(500);
}
catch (InterruptedException exc) { }
}
}
}
|
diff --git a/src/com/dmdirc/parser/ProcessMode.java b/src/com/dmdirc/parser/ProcessMode.java
index f045219b8..762402784 100644
--- a/src/com/dmdirc/parser/ProcessMode.java
+++ b/src/com/dmdirc/parser/ProcessMode.java
@@ -1,353 +1,351 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* SVN: $Id$
*/
package com.dmdirc.parser;
import com.dmdirc.parser.callbacks.CallbackOnChannelSingleModeChanged;
import com.dmdirc.parser.callbacks.CallbackOnChannelNonUserModeChanged;
import com.dmdirc.parser.callbacks.CallbackOnChannelModeChanged;
import com.dmdirc.parser.callbacks.CallbackOnChannelUserModeChanged;
import com.dmdirc.parser.callbacks.CallbackOnUserModeChanged;
import com.dmdirc.parser.callbacks.CallbackOnUserModeDiscovered;
import java.util.Calendar;
/**
* Process a Mode line.
*/
public class ProcessMode extends IRCProcessor {
/**
* Process a Mode Line.
*
* @param sParam Type of line to process ("MODE", "324")
* @param token IRCTokenised line to process
*/
@Override
public void process(String sParam, String[] token) {
String[] sModestr;
String sChannelName;
if (sParam.equals("324")) {
sChannelName = token[3];
sModestr = new String[token.length-4];
System.arraycopy(token, 4, sModestr, 0, token.length-4);
} else if (sParam.equals("221")) {
processUserMode(sParam, token, new String[]{token[token.length-1]}, true);
return;
} else {
sChannelName = token[2];
sModestr = new String[token.length-3];
System.arraycopy(token, 3, sModestr, 0, token.length-3);
}
if (!isValidChannelName(sChannelName)) { processUserMode(sParam, token, sModestr, false); }
else { processChanMode(sParam, token, sModestr, sChannelName); }
}
/**
* Method to trim spaces from strings
*
* @param str String to trim
* @return String without spaces on the ends
*/
private String trim(String str) { return str.trim(); }
/**
* Process Chan modes.
*
* @param sParam String representation of parameter to parse
* @param token IRCTokenised Array of the incomming line
* @param sModestr The modes and params
* @param sChannelName Channel these modes are for
*/
public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) {
StringBuilder sFullModeStr = new StringBuilder();
String sNonUserModeStr = "";
String sNonUserModeStrParams = "";
String sModeParam;
String sTemp;
int nParam = 1;
long nTemp = 0, nValue = 0, nCurrent = 0;
boolean bPositive = true, bBooleanMode = true;
char cPositive = '+';
ChannelInfo iChannel;
ChannelClientInfo iChannelClientInfo;
ClientInfo iClient;
ChannelClientInfo setterCCI;
CallbackOnChannelSingleModeChanged cbSingle = null;
CallbackOnChannelNonUserModeChanged cbNonUser = null;
if (!sParam.equals("324")) {
cbSingle = (CallbackOnChannelSingleModeChanged) getCallbackManager().getCallbackType("OnChannelSingleModeChanged");
cbNonUser = (CallbackOnChannelNonUserModeChanged) getCallbackManager().getCallbackType("OnChannelNonUserModeChanged");
}
iChannel = getChannelInfo(sChannelName);
if (iChannel == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine()));
// iChannel = new ChannelInfo(myParser, sChannelName);
// myParser.addChannel(iChannel);
return;
}
// Get the current channel modes
if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); }
setterCCI = iChannel.getUser(token[0]);
if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) {
// Facilitate dmdirc formatter
if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); }
}
// Loop through the mode string, and add/remove modes/params where they are needed
for (int i = 0; i < sModestr[0].length(); ++i) {
Character cMode = sModestr[0].charAt(i);
if (cMode.equals(":".charAt(0))) { continue; }
sNonUserModeStr = sNonUserModeStr+cMode;
if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; }
else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; }
else {
if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; }
else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; }
else if (myParser.hPrefixModes.containsKey(cMode)) {
// (de) OP/Voice someone
sModeParam = sModestr[nParam++];
nValue = myParser.hPrefixModes.get(cMode);
callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive);
iChannelClientInfo = iChannel.getUser(sModeParam);
if (iChannelClientInfo == null) {
// Client not known?
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine()));
iClient = getClientInfo(sModeParam);
if (iClient == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine()));
iClient = new ClientInfo(myParser, sModeParam);
myParser.addClient(iClient);
}
iChannelClientInfo = iChannel.addClient(iClient);
}
callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode());
if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; }
else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; }
sTemp = sTemp+cMode;
callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp);
continue;
} else {
// unknown mode - add as boolean
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine()));
myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool);
nValue = myParser.nNextKeyCMBool;
bBooleanMode = true;
myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2;
}
if (bBooleanMode) {
callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive);
if (bPositive) { nCurrent = nCurrent | nValue; }
else { nCurrent = nCurrent ^ (nCurrent & nValue); }
} else {
- if (bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) {
- if (sModestr.length <= nParam) {
- myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Broken Modes. Parameter required but not given.", myParser.getLastLine()));
- }
+ if ((bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) && (sModestr.length <= nParam)) {
+ myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Broken Modes. Parameter required but not given.", myParser.getLastLine()));
}
if (nValue == IRCParser.MODE_LIST) {
// List Mode
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
nTemp = (Calendar.getInstance().getTimeInMillis() / 1000);
iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// Mode with a parameter
if (bPositive) {
// +Mode - always needs a parameter to set
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,sModeParam);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// -Mode - parameter isn't always needed, we need to check
if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) {
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
} else {
sModeParam = "";
}
callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,"");
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); }
}
}
}
}
}
// Call Callbacks
for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); }
iChannel.setMode(nCurrent);
if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); }
else { callChannelModeChanged(iChannel, setterCCI, token[0], sFullModeStr.toString().trim()); }
if (cbNonUser != null) { cbNonUser.call(iChannel, setterCCI, token[0], trim(sNonUserModeStr+sNonUserModeStrParams)); }
}
/**
* Process user modes.
*
* @param sParam String representation of parameter to parse
* @param token IRCTokenised Array of the incomming line
* @param clearOldModes Clear old modes before applying these modes (used by 221)
*/
private void processUserMode(String sParam, String token[], String sModestr[], boolean clearOldModes) {
long nCurrent = 0, nValue = 0;
boolean bPositive = true;
ClientInfo iClient;
iClient = getClientInfo(token[2]);
if (iClient == null) { return; }
if (clearOldModes) {
nCurrent = 0;
} else {
nCurrent = iClient.getUserMode();
}
for (int i = 0; i < sModestr[0].length(); ++i) {
Character cMode = sModestr[0].charAt(i);
if (cMode.equals("+".charAt(0))) { bPositive = true; }
else if (cMode.equals("-".charAt(0))) { bPositive = false; }
else if (cMode.equals(":".charAt(0))) { continue; }
else {
if (myParser.hUserModes.containsKey(cMode)) { nValue = myParser.hUserModes.get(cMode); }
else {
// Unknown mode
callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown user mode "+cMode+" - Added", myParser.getLastLine()));
myParser.hUserModes.put(cMode,myParser.nNextKeyUser);
nValue = myParser.nNextKeyUser;
myParser.nNextKeyUser = myParser.nNextKeyUser*2;
}
// Usermodes are always boolean
callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive);
if (bPositive) { nCurrent = nCurrent | nValue; }
else { nCurrent = nCurrent ^ (nCurrent & nValue); }
}
}
iClient.setUserMode(nCurrent);
if (sParam.equals("221")) {
callUserModeDiscovered(iClient, sModestr[0]);
} else {
callUserModeChanged(iClient, token[0], sModestr[0]);
}
}
/**
* Callback to all objects implementing the ChannelModeChanged Callback.
*
* @see IChannelModeChanged
* @param cChannel Channel where modes were changed
* @param cChannelClient Client chaning the modes (null if server)
* @param sHost Host doing the mode changing (User host or server name)
* @param sModes Exact String parsed
* @return true if a method was called, false otherwise
*/
protected boolean callChannelModeChanged(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sHost, String sModes) {
return ((CallbackOnChannelModeChanged) getCallbackManager()
.getCallbackType("OnChannelModeChanged")).call(cChannel, cChannelClient, sHost, sModes);
}
/**
* Callback to all objects implementing the ChannelUserModeChanged Callback.
*
* @see IChannelUserModeChanged
* @param cChannel Channel where modes were changed
* @param cChangedClient Client being changed
* @param cSetByClient Client chaning the modes (null if server)
* @param sMode String representing mode change (ie +o)
* @param sHost Host doing the mode changing (User host or server name)
* @return true if a method was called, false otherwise
*/
protected boolean callChannelUserModeChanged(ChannelInfo cChannel, ChannelClientInfo cChangedClient, ChannelClientInfo cSetByClient, String sHost, String sMode) {
return ((CallbackOnChannelUserModeChanged) getCallbackManager()
.getCallbackType("OnChannelUserModeChanged")).call(cChannel, cChangedClient, cSetByClient, sHost, sMode);
}
/**
* Callback to all objects implementing the UserModeChanged Callback.
*
* @see IUserModeChanged
* @param cClient Client that had the mode changed (almost always us)
* @param sSetby Host that set the mode (us or servername)
* @param sModes The modes set.
* @return true if a method was called, false otherwise
*/
protected boolean callUserModeChanged(ClientInfo cClient, String sSetby, String sModes) {
return ((CallbackOnUserModeChanged) getCallbackManager()
.getCallbackType("OnUserModeChanged")).call(cClient, sSetby, sModes);
}
/**
* Callback to all objects implementing the UserModeDiscovered Callback.
*
* @see IUserModeDiscovered
* @param cClient Client that had the mode changed (almost always us)
* @param sModes The modes set.
* @return true if a method was called, false otherwise
*/
protected boolean callUserModeDiscovered(ClientInfo cClient, String sModes) {
return ((CallbackOnUserModeDiscovered)getCallbackManager()
.getCallbackType("OnUserModeDiscovered")).call(cClient, sModes);
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
@Override
public String[] handles() {
String[] iHandle = new String[3];
iHandle[0] = "MODE";
iHandle[1] = "324";
iHandle[2] = "221";
return iHandle;
}
/**
* Create a new instance of the IRCProcessor Object.
*
* @param parser IRCParser That owns this IRCProcessor
* @param manager ProcessingManager that is in charge of this IRCProcessor
*/
protected ProcessMode (IRCParser parser, ProcessingManager manager) { super(parser, manager); }
}
| true | true | public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) {
StringBuilder sFullModeStr = new StringBuilder();
String sNonUserModeStr = "";
String sNonUserModeStrParams = "";
String sModeParam;
String sTemp;
int nParam = 1;
long nTemp = 0, nValue = 0, nCurrent = 0;
boolean bPositive = true, bBooleanMode = true;
char cPositive = '+';
ChannelInfo iChannel;
ChannelClientInfo iChannelClientInfo;
ClientInfo iClient;
ChannelClientInfo setterCCI;
CallbackOnChannelSingleModeChanged cbSingle = null;
CallbackOnChannelNonUserModeChanged cbNonUser = null;
if (!sParam.equals("324")) {
cbSingle = (CallbackOnChannelSingleModeChanged) getCallbackManager().getCallbackType("OnChannelSingleModeChanged");
cbNonUser = (CallbackOnChannelNonUserModeChanged) getCallbackManager().getCallbackType("OnChannelNonUserModeChanged");
}
iChannel = getChannelInfo(sChannelName);
if (iChannel == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine()));
// iChannel = new ChannelInfo(myParser, sChannelName);
// myParser.addChannel(iChannel);
return;
}
// Get the current channel modes
if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); }
setterCCI = iChannel.getUser(token[0]);
if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) {
// Facilitate dmdirc formatter
if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); }
}
// Loop through the mode string, and add/remove modes/params where they are needed
for (int i = 0; i < sModestr[0].length(); ++i) {
Character cMode = sModestr[0].charAt(i);
if (cMode.equals(":".charAt(0))) { continue; }
sNonUserModeStr = sNonUserModeStr+cMode;
if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; }
else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; }
else {
if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; }
else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; }
else if (myParser.hPrefixModes.containsKey(cMode)) {
// (de) OP/Voice someone
sModeParam = sModestr[nParam++];
nValue = myParser.hPrefixModes.get(cMode);
callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive);
iChannelClientInfo = iChannel.getUser(sModeParam);
if (iChannelClientInfo == null) {
// Client not known?
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine()));
iClient = getClientInfo(sModeParam);
if (iClient == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine()));
iClient = new ClientInfo(myParser, sModeParam);
myParser.addClient(iClient);
}
iChannelClientInfo = iChannel.addClient(iClient);
}
callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode());
if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; }
else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; }
sTemp = sTemp+cMode;
callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp);
continue;
} else {
// unknown mode - add as boolean
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine()));
myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool);
nValue = myParser.nNextKeyCMBool;
bBooleanMode = true;
myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2;
}
if (bBooleanMode) {
callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive);
if (bPositive) { nCurrent = nCurrent | nValue; }
else { nCurrent = nCurrent ^ (nCurrent & nValue); }
} else {
if (bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) {
if (sModestr.length <= nParam) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Broken Modes. Parameter required but not given.", myParser.getLastLine()));
}
}
if (nValue == IRCParser.MODE_LIST) {
// List Mode
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
nTemp = (Calendar.getInstance().getTimeInMillis() / 1000);
iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// Mode with a parameter
if (bPositive) {
// +Mode - always needs a parameter to set
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,sModeParam);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// -Mode - parameter isn't always needed, we need to check
if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) {
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
} else {
sModeParam = "";
}
callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,"");
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); }
}
}
}
}
}
// Call Callbacks
for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); }
iChannel.setMode(nCurrent);
if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); }
| public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) {
StringBuilder sFullModeStr = new StringBuilder();
String sNonUserModeStr = "";
String sNonUserModeStrParams = "";
String sModeParam;
String sTemp;
int nParam = 1;
long nTemp = 0, nValue = 0, nCurrent = 0;
boolean bPositive = true, bBooleanMode = true;
char cPositive = '+';
ChannelInfo iChannel;
ChannelClientInfo iChannelClientInfo;
ClientInfo iClient;
ChannelClientInfo setterCCI;
CallbackOnChannelSingleModeChanged cbSingle = null;
CallbackOnChannelNonUserModeChanged cbNonUser = null;
if (!sParam.equals("324")) {
cbSingle = (CallbackOnChannelSingleModeChanged) getCallbackManager().getCallbackType("OnChannelSingleModeChanged");
cbNonUser = (CallbackOnChannelNonUserModeChanged) getCallbackManager().getCallbackType("OnChannelNonUserModeChanged");
}
iChannel = getChannelInfo(sChannelName);
if (iChannel == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine()));
// iChannel = new ChannelInfo(myParser, sChannelName);
// myParser.addChannel(iChannel);
return;
}
// Get the current channel modes
if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); }
setterCCI = iChannel.getUser(token[0]);
if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) {
// Facilitate dmdirc formatter
if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); }
}
// Loop through the mode string, and add/remove modes/params where they are needed
for (int i = 0; i < sModestr[0].length(); ++i) {
Character cMode = sModestr[0].charAt(i);
if (cMode.equals(":".charAt(0))) { continue; }
sNonUserModeStr = sNonUserModeStr+cMode;
if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; }
else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; }
else {
if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; }
else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; }
else if (myParser.hPrefixModes.containsKey(cMode)) {
// (de) OP/Voice someone
sModeParam = sModestr[nParam++];
nValue = myParser.hPrefixModes.get(cMode);
callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive);
iChannelClientInfo = iChannel.getUser(sModeParam);
if (iChannelClientInfo == null) {
// Client not known?
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine()));
iClient = getClientInfo(sModeParam);
if (iClient == null) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine()));
iClient = new ClientInfo(myParser, sModeParam);
myParser.addClient(iClient);
}
iChannelClientInfo = iChannel.addClient(iClient);
}
callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode());
if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; }
else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; }
sTemp = sTemp+cMode;
callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp);
continue;
} else {
// unknown mode - add as boolean
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine()));
myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool);
nValue = myParser.nNextKeyCMBool;
bBooleanMode = true;
myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2;
}
if (bBooleanMode) {
callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive);
if (bPositive) { nCurrent = nCurrent | nValue; }
else { nCurrent = nCurrent ^ (nCurrent & nValue); }
} else {
if ((bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) && (sModestr.length <= nParam)) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Broken Modes. Parameter required but not given.", myParser.getLastLine()));
}
if (nValue == IRCParser.MODE_LIST) {
// List Mode
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
nTemp = (Calendar.getInstance().getTimeInMillis() / 1000);
iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// Mode with a parameter
if (bPositive) {
// +Mode - always needs a parameter to set
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,sModeParam);
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); }
} else {
// -Mode - parameter isn't always needed, we need to check
if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) {
sModeParam = sModestr[nParam++];
sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam;
} else {
sModeParam = "";
}
callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive);
iChannel.setModeParam(cMode,"");
if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); }
}
}
}
}
}
// Call Callbacks
for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); }
iChannel.setMode(nCurrent);
if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); }
|
diff --git a/app/controllers/Groups.java b/app/controllers/Groups.java
index f9c8df8..98c7141 100644
--- a/app/controllers/Groups.java
+++ b/app/controllers/Groups.java
@@ -1,155 +1,155 @@
package controllers;
import java.io.Console;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;
import org.apache.commons.io.IOUtils;
import models.*;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import play.libs.WS;
import play.libs.WS.HttpResponse;
import play.mvc.Before;
import play.mvc.Controller;
import requests.Comment_request;
import requests.Datum_request;
import requests.JsonRequest;
import requests.RunId_request;
import util.UnicodeString;
/*******************************************************************************
* Class Name: Group Controller
* - contain necessary implementations to facilitate the groups activities
* - serves as proxy server between client[flash, HTML5] and RollCall
*******************************************************************************/
public class Groups extends Controller{
/********************* Establish Connection with RollCall ******************/
@Before
static void createRollcallSession() {
String contents = "{ \"Session\": {\"username\":\"binden\" , \"password\":\"binden\"} }";
String url = "http://imediamac28.uio.no:8080";
WS.url(url).body(contents).post();
}
/********************* Retrieve the list of all groups *********************/
public static void all(){
//play serve as client to Ruby rollcall server at port 8080
//Talking to Jeremy Ruby Server for testing http://129.240.161.29:4567/groups
String url = "http://imediamac28.uio.no:8080/groups.json";
JsonElement result = WS.url(url).get().getJson();
String res = result.toString();
renderJSON(res);
}
/********************* Retrieve the group with ID `1` **********************/
public static void getById(String id){
//JsonReader.setLenient(true);
String url = "http://imediamac28.uio.no:8080/groups/" + id + ".json";
//WS.url accept only String type parameters
JsonElement result = WS.url(url).get().getJson();
String res = result.toString();
renderJSON(res);
}
/********************* Retrieve the runid by title **********************/
public static void getRunIdByTitle(String title){
//JsonReader.setLenient(true);
String url = "http://imediamac28.uio.no:8080/runs/" + title + ".json";
//WS.url accept only String type parameters
JsonElement result = WS.url(url).get().getJson();
String res = result.toString();
renderJSON(res);
}
/********************* Delete group with ID `1` ****************************/
public static void deleteGroup(String id){
String url = "http://imediamac28.uio.no:8080/groups/" + id;
Integer status = WS.url(url).delete().getStatus();
if(status == 1)
renderText("Group deleted");
}
/********************* Create new Comment **********************************/
public static void postComment() throws IOException {
String json = IOUtils.toString(request.body);
Comment_request req = new Gson().fromJson(json, Comment_request.class);
//Serialize request
Long project_id = req.project_id;
Long run_id = req.run_id;
Long group_id = req.group_id;
Long task_id = req.task_id;
float xpos = req.xpos;
float ypos = req.ypos;
String content = req.content;
MyGroup myGroup = MyGroup.findById(group_id);
Project project = Project.findById(project_id);
Task task = Task.findById(task_id);
Comment comment = myGroup.postComment(project,run_id, task, content, xpos, ypos);
renderTemplate("Comments/comment.json", comment);
}
/********************* Update the Comment **********************************/
public static void updateComment(Long id) throws IOException {
String json = IOUtils.toString(request.body);
System.out.println("PUT comments/id:"+ json);
Comment_request req = new Gson().fromJson(json, Comment_request.class);
System.out.println(json);
Long comment_id = req.comment_id;
//Unicode conversion
UnicodeString us = new UnicodeString();
String content = us.convert(req.content);
//String content = req.content;
float xpos = req.xpos;
float ypos = req.ypos;
- Comment comment = Comment.findById(comment_id);
+ Comment comment = Comment.findById(id);
comment.content = content;
comment.xpos = xpos;
comment.ypos = ypos;
comment.save();
renderTemplate("Comments/comment.json", comment);
}
/********************* Delete the Comment **********************************/
public static void deleteComment(Long id){
Comment.delete("from Comment c where c.id=?", id);
}
/********************* Show all Comments **********************************/
public static void showAllComments(){
List<Comment> comments = Comment.findAll();
renderTemplate("Comments/list.json", comments);
}
/********************* Show Comments by Group and Task **********************/
public static void showCommentbyGT(){
Long group_id = params.get("group_id",Long.class);
Long task_id = params.get("task_id",Long.class);
List<Comment> comments = Comment.find("SELECT c from Comment c Where c.myGroup.id =? and c.task.id=?"
, group_id, task_id).fetch();
renderTemplate("Comments/list.json", comments);
}
/********************* Update Task Data **********************************/
public static void updateTaskData() throws IOException {
String json = IOUtils.toString(request.body);
System.out.println(json);
Datum_request req = new Gson().fromJson(json, Datum_request.class);
//Serialize request
Long data_id = Long.parseLong(req.data_id);
String data = req.data;
//System.println(json);
TaskData existing_var = TaskData.findById(data_id);
existing_var.taskdata = data;
existing_var.save();
renderTemplate("TaskDatum/taskdataU.json", existing_var);
}
}
| true | true | public static void updateComment(Long id) throws IOException {
String json = IOUtils.toString(request.body);
System.out.println("PUT comments/id:"+ json);
Comment_request req = new Gson().fromJson(json, Comment_request.class);
System.out.println(json);
Long comment_id = req.comment_id;
//Unicode conversion
UnicodeString us = new UnicodeString();
String content = us.convert(req.content);
//String content = req.content;
float xpos = req.xpos;
float ypos = req.ypos;
Comment comment = Comment.findById(comment_id);
comment.content = content;
comment.xpos = xpos;
comment.ypos = ypos;
comment.save();
renderTemplate("Comments/comment.json", comment);
}
| public static void updateComment(Long id) throws IOException {
String json = IOUtils.toString(request.body);
System.out.println("PUT comments/id:"+ json);
Comment_request req = new Gson().fromJson(json, Comment_request.class);
System.out.println(json);
Long comment_id = req.comment_id;
//Unicode conversion
UnicodeString us = new UnicodeString();
String content = us.convert(req.content);
//String content = req.content;
float xpos = req.xpos;
float ypos = req.ypos;
Comment comment = Comment.findById(id);
comment.content = content;
comment.xpos = xpos;
comment.ypos = ypos;
comment.save();
renderTemplate("Comments/comment.json", comment);
}
|
diff --git a/src/com/fisherevans/lrk/states/CharacterState.java b/src/com/fisherevans/lrk/states/CharacterState.java
index d2c9c37..2cd6ecb 100644
--- a/src/com/fisherevans/lrk/states/CharacterState.java
+++ b/src/com/fisherevans/lrk/states/CharacterState.java
@@ -1,231 +1,231 @@
package com.fisherevans.lrk.states;
import com.fisherevans.lrk.Resources;
import com.fisherevans.lrk.StateLibrary;
import com.fisherevans.lrk.launcher.Game;
import com.fisherevans.lrk.managers.DisplayManager;
import com.fisherevans.lrk.rpg.items.*;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: immortal
* Date: 7/22/13
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class CharacterState extends LRKState
{
public enum InventoryType { Equipment, Consumables }
private LRKState _lastState;
private float _hWidth;
private InventoryType _currentType;
private ArrayList<Item> _currentList;
private Map<InventoryType, Integer> _currentPositions;
public CharacterState(LRKState lastState) throws SlickException
{
super(StateLibrary.getTempID());
_lastState = lastState;
}
@Override
public void init() throws SlickException
{
resize();
swapType();
_currentPositions = new HashMap<InventoryType, Integer>();
_currentPositions.put(InventoryType.Equipment, 0);
_currentPositions.put(InventoryType.Consumables, 0);
}
@Override
public void enter() throws SlickException
{
}
@Override
public void exit() throws SlickException
{
}
@Override
public void render(Graphics gfx) throws SlickException
{
//_lastState.render(gfx);
renderInventory(gfx, _currentType);
renderComparison(gfx);
/* renderStats(gfx);
if(_currentType == InventoryType.Equipment)
renderEquipmentPanel(gfx);
else
renderConsumablesPanel(gfx);*/
}
private final int INV_TITLE_HEIGHT = 32;
private final int INV_LINE_HEIGHT = 20;
private final int INV_LIST_PADDING = 12;
private final int INV_LIST_MARGIN = 20;
private final float INV_HEIGHT_RATIO = 0.6666f;
private float _invHeight, _invHeightList, _invHeightScroll, _invWidthScroll, _invXScroll, _invYScroll, _invYList;
public void renderInventory(Graphics gfx, InventoryType type)
{
// title
GFX.drawText(0, 0, _hWidth, INV_TITLE_HEIGHT, GFX.TEXT_CENTER, GFX.TEXT_CENTER, Resources.getFont(2), Color.white, type.toString());
// list bg
gfx.setColor(Color.darkGray);
gfx.fillRect(INV_LIST_MARGIN,
INV_TITLE_HEIGHT,
_hWidth - INV_LIST_MARGIN*2f,
_invHeightList);
float scrollHeight = _invHeightScroll/(float)_currentList.size();
gfx.setColor(Color.white);
gfx.fillRect(_invXScroll,
- _invYScroll + (getPosition()-1)*scrollHeight,
+ _invYScroll + (getPosition())*scrollHeight,
_invWidthScroll,
scrollHeight);
clip(0, INV_TITLE_HEIGHT, _hWidth, _invHeightList);
for(int id = 0;id < _currentList.size();id++)
{
Item item = _currentList.get(id);
Color color = id == _currentPositions.get(_currentType) ? Color.white : Color.lightGray;
GFX.drawTextCenteredV(INV_LIST_MARGIN + INV_LIST_PADDING,
_invYList + (id- getPosition())*INV_LINE_HEIGHT,
0, Resources.getFont(1), color, item.getName());
}
unClip();
}
public void renderEquipmentPanel(Graphics gfx)
{
}
public void renderConsumablesPanel(Graphics gfx)
{
}
public void renderComparison(Graphics gfx)
{
GFX.drawImageCentered(DisplayManager.getRenderWidth()*0.5f*0.3333f, DisplayManager.getRenderHeight()*0.8f, _currentList.get(_currentPositions.get(_currentType)).getImage().getScaledCopy(2));
}
public void renderStats(Graphics gfx)
{
}
private void clip(float x, float y, float width, float height)
{
Game.getContainer().getGraphics().setClip(
(int)(x*DisplayManager.getScale()),
(int)(y*DisplayManager.getScale()),
(int)(width*DisplayManager.getScale()),
(int)(height*DisplayManager.getScale()));
}
private void unClip()
{
Game.getContainer().getGraphics().clearClip();
}
@Override
public void update(float delta) throws SlickException
{
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void destroy() throws SlickException
{
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void resize()
{
_hWidth = DisplayManager.getRenderWidth()/2f;
// Inventory
_invHeight = DisplayManager.getRenderHeight()*INV_HEIGHT_RATIO;
_invHeightList = _invHeight - INV_TITLE_HEIGHT - INV_LIST_MARGIN;
_invHeightScroll = _invHeightList - INV_LIST_PADDING*2;
_invWidthScroll = INV_LIST_PADDING/2f;
_invXScroll = _hWidth - INV_LIST_MARGIN - INV_LIST_PADDING*0.75f;
_invYScroll = INV_TITLE_HEIGHT + INV_LIST_PADDING;
_invYList = _invHeightList/2f + INV_TITLE_HEIGHT;
}
public int getPosition()
{
return _currentPositions.get(_currentType);
}
public void keyBack()
{
StateLibrary.setActiveState(_lastState);
}
public void keyLeft()
{
swapType();
}
public void keyRight()
{
swapType();
}
public void keyUp()
{
if(_currentPositions.get(_currentType) <= 0)
{
_currentPositions.put(_currentType, 0);
return;
}
_currentPositions.put(_currentType, _currentPositions.get(_currentType) - 1);
}
public void keyDown()
{
if(_currentPositions.get(_currentType) >= _currentList.size()-1)
{
_currentPositions.put(_currentType, _currentList.size()-1);
return;
}
_currentPositions.put(_currentType, _currentPositions.get(_currentType)+1);
}
private void swapType()
{
if(_currentType == InventoryType.Equipment)
{
_currentType = InventoryType.Consumables;
_currentList = Game.lrk.getPlayer().getInventory().getConsumables();
}
else
{
_currentType = InventoryType.Equipment;
_currentList = Game.lrk.getPlayer().getInventory().getEquipment();
}
}
}
| true | true | public void renderInventory(Graphics gfx, InventoryType type)
{
// title
GFX.drawText(0, 0, _hWidth, INV_TITLE_HEIGHT, GFX.TEXT_CENTER, GFX.TEXT_CENTER, Resources.getFont(2), Color.white, type.toString());
// list bg
gfx.setColor(Color.darkGray);
gfx.fillRect(INV_LIST_MARGIN,
INV_TITLE_HEIGHT,
_hWidth - INV_LIST_MARGIN*2f,
_invHeightList);
float scrollHeight = _invHeightScroll/(float)_currentList.size();
gfx.setColor(Color.white);
gfx.fillRect(_invXScroll,
_invYScroll + (getPosition()-1)*scrollHeight,
_invWidthScroll,
scrollHeight);
clip(0, INV_TITLE_HEIGHT, _hWidth, _invHeightList);
for(int id = 0;id < _currentList.size();id++)
{
Item item = _currentList.get(id);
Color color = id == _currentPositions.get(_currentType) ? Color.white : Color.lightGray;
GFX.drawTextCenteredV(INV_LIST_MARGIN + INV_LIST_PADDING,
_invYList + (id- getPosition())*INV_LINE_HEIGHT,
0, Resources.getFont(1), color, item.getName());
}
unClip();
}
| public void renderInventory(Graphics gfx, InventoryType type)
{
// title
GFX.drawText(0, 0, _hWidth, INV_TITLE_HEIGHT, GFX.TEXT_CENTER, GFX.TEXT_CENTER, Resources.getFont(2), Color.white, type.toString());
// list bg
gfx.setColor(Color.darkGray);
gfx.fillRect(INV_LIST_MARGIN,
INV_TITLE_HEIGHT,
_hWidth - INV_LIST_MARGIN*2f,
_invHeightList);
float scrollHeight = _invHeightScroll/(float)_currentList.size();
gfx.setColor(Color.white);
gfx.fillRect(_invXScroll,
_invYScroll + (getPosition())*scrollHeight,
_invWidthScroll,
scrollHeight);
clip(0, INV_TITLE_HEIGHT, _hWidth, _invHeightList);
for(int id = 0;id < _currentList.size();id++)
{
Item item = _currentList.get(id);
Color color = id == _currentPositions.get(_currentType) ? Color.white : Color.lightGray;
GFX.drawTextCenteredV(INV_LIST_MARGIN + INV_LIST_PADDING,
_invYList + (id- getPosition())*INV_LINE_HEIGHT,
0, Resources.getFont(1), color, item.getName());
}
unClip();
}
|
diff --git a/src/ac/robinson/mediatablet/MediaViewerActivity.java b/src/ac/robinson/mediatablet/MediaViewerActivity.java
index 4795d32..19f6aba 100644
--- a/src/ac/robinson/mediatablet/MediaViewerActivity.java
+++ b/src/ac/robinson/mediatablet/MediaViewerActivity.java
@@ -1,609 +1,609 @@
/*
* Copyright (C) 2012 Simon Robinson
*
* This file is part of Com-Me.
*
* Com-Me 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.
*
* Com-Me 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 Com-Me.
* If not, see <http://www.gnu.org/licenses/>.
*/
package ac.robinson.mediatablet;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import ac.robinson.mediatablet.activity.HomesteadBrowserActivity;
import ac.robinson.mediatablet.activity.PeopleBrowserActivity;
import ac.robinson.mediatablet.importing.ImportedFileParser;
import ac.robinson.mediatablet.provider.MediaItem;
import ac.robinson.mediatablet.provider.MediaManager;
import ac.robinson.mediatablet.provider.MediaTabletProvider;
import ac.robinson.mediatablet.provider.PersonItem;
import ac.robinson.mediatablet.provider.PersonManager;
import ac.robinson.mediautilities.FrameMediaContainer;
import ac.robinson.mediautilities.MediaUtilities;
import ac.robinson.mediautilities.SMILUtilities;
import ac.robinson.util.IOUtilities;
import ac.robinson.util.ImageCacheUtilities;
import ac.robinson.util.StringUtilities;
import ac.robinson.util.UIUtilities;
import ac.robinson.util.UIUtilities.ReflectionTab;
import ac.robinson.util.UIUtilities.ReflectionTabListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public abstract class MediaViewerActivity extends MediaTabletActivity {
private String mMediaInternalId;
private String mMediaParentId;
private File mMediaFile;
private int mMediaType;
private boolean mOwnerMode;
abstract protected void initialiseView(Bundle savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load ids on screen rotation
mMediaInternalId = null;
mMediaParentId = null;
if (savedInstanceState != null) {
mMediaInternalId = savedInstanceState.getString(getString(R.string.extra_internal_id));
mMediaParentId = savedInstanceState.getString(getString(R.string.extra_parent_id));
} else {
final Intent intent = getIntent();
if (intent != null) {
mMediaInternalId = intent.getStringExtra(getString(R.string.extra_internal_id));
mMediaParentId = intent.getStringExtra(getString(R.string.extra_parent_id));
}
}
if (mMediaInternalId == null) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.error_loading_media);
finish();
return;
}
MediaItem currentMediaItem = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
mMediaFile = currentMediaItem.getFile();
mMediaType = currentMediaItem.getType();
if (mMediaFile == null || !mMediaFile.exists()) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.error_loading_media);
finish();
return;
}
// mMediaParentId == null -> public media mode
// mMediaParentId != null && mOwnerMode == true -> private mode
// mMediaParentId != null && mOwnerMode == false -> private shared media mode
mOwnerMode = false;
ContentResolver contentResolver = getContentResolver();
UIUtilities.configureActionBar(this, false, false, R.string.title_playback, 0);
if (mMediaParentId != null) {
PersonItem currentPersonItem = PersonManager.findPersonByInternalId(contentResolver, mMediaParentId);
mOwnerMode = !currentPersonItem.isLocked();
String personName = currentPersonItem == null ? null : currentPersonItem.getName();
String mediaTitle = currentPersonItem == null || personName == null ? getString(R.string.title_media_browser)
: String.format(getString(mOwnerMode ? R.string.title_media_browser_private_personalised
: R.string.title_media_browser_public_personalised), personName);
String peopleTitle = currentPersonItem == null || personName == null ? getString(R.string.title_people_browser)
: String.format(getString(R.string.title_people_browser_personalised), personName);
UIUtilities.addActionBarTabs(this, new ReflectionTab[] {
new ReflectionTab(R.id.intent_homestead_browser, R.drawable.ic_menu_homesteads,
getString(R.string.title_homestead_browser)),
new ReflectionTab(R.id.intent_people_browser, R.drawable.ic_menu_people, peopleTitle),
new ReflectionTab(R.id.intent_media_browser, R.drawable.ic_menu_media, mediaTitle),
new ReflectionTab(R.id.intent_media_item_viewer, android.R.drawable.ic_menu_info_details,
getString(R.string.title_playback), true) }, mReflectionTabListener);
} else {
UIUtilities.addActionBarTabs(this, new ReflectionTab[] {
new ReflectionTab(R.id.intent_homestead_browser, R.drawable.ic_menu_homesteads,
getString(R.string.title_homestead_browser)),
new ReflectionTab(R.id.intent_media_browser, R.drawable.ic_menu_public_media,
getString(R.string.title_media_browser_public)),
new ReflectionTab(R.id.intent_media_item_viewer, android.R.drawable.ic_menu_info_details,
getString(R.string.title_playback), true) }, mReflectionTabListener);
}
initialiseView(savedInstanceState);
// for API 11 and above, buttons are in the action bar - could use XML-v11 but maintenance is a hassle
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
findViewById(R.id.panel_media_viewer).setVisibility(View.GONE);
} else {
if (mMediaParentId == null || !mOwnerMode) {
findViewById(R.id.button_media_view_view_people).setVisibility(View.GONE);
findViewById(R.id.button_media_view_view_media).setVisibility(View.GONE);
findViewById(R.id.button_media_view_view_public_media).setVisibility(View.GONE);
findViewById(R.id.button_media_view_back).setVisibility(View.VISIBLE);
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(getString(R.string.extra_internal_id), mMediaInternalId);
savedInstanceState.putString(getString(R.string.extra_parent_id), mMediaParentId);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onDestroy() {
ImageCacheUtilities.cleanupCache();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (mOwnerMode) {
inflater.inflate(R.menu.share, menu);
}
inflater.inflate(R.menu.send, menu);
if (mMediaParentId != null) {
inflater.inflate(R.menu.public_media, menu);
}
inflater.inflate(R.menu.delete, menu);
menu.findItem(R.id.menu_delete).setTitle(getString(R.string.menu_delete_media));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
shareMedia();
return true;
case R.id.menu_send:
sendMedia();
return true;
case R.id.menu_view_public_media:
viewPublicMedia();
return true;
case R.id.menu_delete:
showDeleteMediaDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void loadPreferences(SharedPreferences mediaTabletSettings) {
}
@Override
protected String getCurrentPersonId() {
return mOwnerMode ? mMediaParentId : PersonItem.UNKNOWN_PERSON_ID;
}
protected String getCurrentMediaId() {
return mMediaInternalId;
}
protected File getCurrentMediaFile() {
return mMediaFile;
}
protected int getCurrentMediaType() {
return mMediaType;
}
private void sendFiles(ArrayList<Uri> filesToSend, String mimeType) {
if (filesToSend == null || filesToSend.size() <= 0) {
// TODO: show error (but remember it's from a background task, so we can't show a Toast)
return;
}
// also see: http://stackoverflow.com/questions/2344768/
final Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendIntent.setType(mimeType); // application/smil+xml (or html), or video/quicktime, but then no bluetooth opt
sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, filesToSend);
startActivity(Intent.createChooser(sendIntent, getString(R.string.send_media_title))); // (single task mode)
// startActivity(sendIntent); //no title (but does allow saving default...)
}
private void sendMedia() {
if (MediaTablet.DIRECTORY_TEMP == null) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_missing_directory, true);
return;
}
boolean canCopyToExternal = true;
if (IOUtilities.isInternalPath(MediaTablet.DIRECTORY_TEMP.getAbsolutePath())) {
canCopyToExternal = false;
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_potential_problem, true);
}
// important to keep awake to export because we only have one chance to display the export options
// after creating mov or smil file (will be cancelled on screen unlock; Android is weird)
// TODO: move to a better (e.g. notification bar) method of exporting?
UIUtilities.acquireKeepScreenOn(getWindow());
ArrayList<Uri> filesToSend;
String mimeType = "video/*";
MediaItem currentMediaItem = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
if (currentMediaItem.getType() != MediaTabletProvider.TYPE_NARRATIVE) {
filesToSend = new ArrayList<Uri>();
File currentFile = currentMediaItem.getFile();
File publicFile = currentFile;
// can't send from private data directory
if (IOUtilities.isInternalPath(currentFile.getAbsolutePath()) && canCopyToExternal) {
try {
publicFile = new File(MediaTablet.DIRECTORY_TEMP, currentFile.getName());
IOUtilities.copyFile(currentFile, publicFile);
IOUtilities.setFullyPublic(publicFile);
} catch (IOException e) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.error_sending_media);
return;
}
}
filesToSend.add(Uri.fromFile(publicFile));
switch (currentMediaItem.getType()) {
case MediaTabletProvider.TYPE_IMAGE_BACK:
case MediaTabletProvider.TYPE_IMAGE_FRONT:
mimeType = "image/*";
break;
case MediaTabletProvider.TYPE_AUDIO:
mimeType = "audio/*";
break;
case MediaTabletProvider.TYPE_VIDEO:
break;
case MediaTabletProvider.TYPE_TEXT:
mimeType = "text/*";
break;
case MediaTabletProvider.TYPE_UNKNOWN:
default:
mimeType = "unknown"; // TODO
break;
}
} else {
// TODO: extract and combine with MediaPhone version
Resources res = getResources();
final ArrayList<FrameMediaContainer> smilContents = SMILUtilities.getSMILFrameList(
currentMediaItem.getFile(), res.getInteger(R.integer.frame_narrative_sequence_increment), false, 0,
false);
// random name to counter repeat sending name issues
final String exportName = String.format("%s-%s",
getString(R.string.app_name).replaceAll("[^a-zA-Z0-9]+", "-").toLowerCase(Locale.ENGLISH),
MediaTabletProvider.getNewInternalId().substring(0, 8));
final Map<Integer, Object> settings = new Hashtable<Integer, Object>();
settings.put(MediaUtilities.KEY_AUDIO_RESOURCE_ID, R.raw.ic_audio_playback);
// some output settings
settings.put(MediaUtilities.KEY_BACKGROUND_COLOUR, res.getColor(R.color.icon_background));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_NO_IMAGE, res.getColor(R.color.icon_text_no_image));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_WITH_IMAGE, res.getColor(R.color.icon_text_with_image));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_COLOUR, res.getColor(R.color.icon_text_background));
settings.put(MediaUtilities.KEY_TEXT_SPACING, res.getDimensionPixelSize(R.dimen.export_icon_text_padding));
settings.put(MediaUtilities.KEY_TEXT_CORNER_RADIUS,
res.getDimensionPixelSize(R.dimen.export_icon_text_corner_radius));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_SPAN_WIDTH,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);
// TODO: do we want to do getDimensionPixelSize for export?
settings.put(MediaUtilities.KEY_MAX_TEXT_FONT_SIZE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_size));
settings.put(MediaUtilities.KEY_MAX_TEXT_CHARACTERS_PER_LINE,
res.getInteger(R.integer.export_maximum_text_characters_per_line));
settings.put(MediaUtilities.KEY_MAX_TEXT_HEIGHT_WITH_IMAGE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_height_with_image));
settings.put(MediaUtilities.KEY_OUTPUT_WIDTH, res.getInteger(R.integer.export_smil_width));
settings.put(MediaUtilities.KEY_OUTPUT_HEIGHT, res.getInteger(R.integer.export_smil_height));
settings.put(MediaUtilities.KEY_PLAYER_BAR_ADJUSTMENT,
res.getInteger(R.integer.export_smil_player_bar_adjustment));
filesToSend = SMILUtilities.generateNarrativeSMIL(getResources(), new File(MediaTablet.DIRECTORY_TEMP,
- String.format("%s%s", exportName, MediaUtilities.SMIL_FILE_EXTENSION)), smilContents, settings);
+ exportName + MediaUtilities.SMIL_FILE_EXTENSION), smilContents, settings);
}
sendFiles(filesToSend, mimeType);
}
private void shareMedia() {
final CharSequence[] publicMediaOptions = { getString(R.string.share_media_private),
getString(R.string.share_media_choose), getString(R.string.share_media_public) };
MediaItem currentMediaItem = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
AlertDialog.Builder builder = new AlertDialog.Builder(MediaViewerActivity.this);
builder.setTitle(R.string.share_media_title);
// builder.setMessage(R.string.share_media_hint); // breaks the dialog
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setSingleChoiceItems(publicMediaOptions, (currentMediaItem.isPubliclyShared() ? 2 : 0),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0 || item == 2) {
// no need to update the icon (will be done when next viewed)
ContentResolver contentResolver = getContentResolver();
MediaItem sharedMediaItem = MediaManager.findMediaByInternalId(contentResolver,
mMediaInternalId);
int newVisibility = item == 0 ? MediaItem.MEDIA_PRIVATE : MediaItem.MEDIA_PUBLIC;
// TODO: should we share each individual narrative component?
// if (sharedMediaItem.getType() == MediaTabletProvider.TYPE_NARRATIVE) {
// ArrayList<FrameMediaContainer> smilContents = SMILUtilities.getSMILFrameList(
// sharedMediaItem.getFile(), 1, false, 0, false);
//
// for (FrameMediaContainer frame : smilContents) {
//
// if (frame.mImagePath != null) {
// final MediaItem imageMediaItem = MediaManager.findMediaByInternalId(
// contentResolver, MediaItem.getInternalId(frame.mImagePath));
// imageMediaItem.setPubliclySharedStatus(newVisibility);
// MediaManager.updateMedia(contentResolver, imageMediaItem);
// }
//
// for (String mediaPath : frame.mAudioPaths) {
// final MediaItem audioMediaItem = MediaManager.findMediaByInternalId(
// contentResolver, MediaItem.getInternalId(mediaPath));
// audioMediaItem.setPubliclySharedStatus(newVisibility);
// MediaManager.updateMedia(contentResolver, audioMediaItem);
// }
//
// // text is stored in the narrative file itself - no need to share
// }
// }
sharedMediaItem.setPubliclySharedStatus(newVisibility);
MediaManager.updateMedia(contentResolver, sharedMediaItem);
} else {
Intent showPeopleIntent = new Intent(MediaViewerActivity.this, PeopleBrowserActivity.class);
startActivityForResult(showPeopleIntent, R.id.intent_people_browser);
}
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void sendShareMedia() {
if (mMediaParentId == null || !mOwnerMode) {
sendMedia();
} else {
final CharSequence[] sendShareOptions = { getString(R.string.menu_send), getString(R.string.menu_share),
getString(R.string.button_delete) };
AlertDialog.Builder builder = new AlertDialog.Builder(MediaViewerActivity.this);
builder.setTitle(R.string.edit_media_title);
// builder.setMessage(R.string.edit_media_hint); // breaks the dialog
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setItems(sendShareOptions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
sendMedia();
break;
case 1:
shareMedia();
break;
case 2:
showDeleteMediaDialog();
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private void showDeleteMediaDialog() {
if (mOwnerMode) {
AlertDialog.Builder builder = new AlertDialog.Builder(MediaViewerActivity.this);
builder.setTitle(R.string.delete_media_confirmation);
builder.setMessage(R.string.delete_media_hint);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setPositiveButton(R.string.button_delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
deleteMedia();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
LayoutInflater inflater = LayoutInflater.from(MediaViewerActivity.this);
final View textEntryView = inflater.inflate(R.layout.password_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(MediaViewerActivity.this);
builder.setMessage(R.string.delete_media_password_prompt).setCancelable(false).setView(textEntryView)
.setPositiveButton(R.string.button_delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (MediaTablet.ADMINISTRATOR_PASSWORD.equals(StringUtilities
.sha1Hash(((EditText) textEntryView.findViewById(R.id.text_password_entry))
.getText().toString()))) {
deleteMedia();
} else {
UIUtilities.showToast(MediaViewerActivity.this,
R.string.delete_media_password_incorrect);
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
}
}
private void deleteMedia() {
ContentResolver contentResolver = getContentResolver();
MediaItem mediaToDelete = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
mediaToDelete.setDeleted(true);
MediaManager.updateMedia(contentResolver, mediaToDelete);
UIUtilities.showToast(MediaViewerActivity.this, R.string.delete_media_deleted);
finish();
}
private void viewHomesteads() {
Intent intent = new Intent(MediaViewerActivity.this, HomesteadBrowserActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void viewPeople() {
final Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.extra_finish_activity), true);
setResult(Activity.RESULT_OK, resultIntent); // exit media browser too
finish();
}
public void handleButtonClicks(View currentButton) {
switch (currentButton.getId()) {
case R.id.button_media_view_share_media:
sendShareMedia();
break;
case R.id.button_media_view_view_homesteads:
viewHomesteads();
case R.id.button_media_view_view_people:
viewPeople();
break;
case R.id.button_media_view_view_media:
case R.id.button_media_view_back:
finish();
break;
case R.id.button_media_view_view_public_media:
viewPublicMedia();
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
switch (requestCode) {
case R.id.intent_media_browser:
if (resultCode == Activity.RESULT_OK && resultIntent != null) {
if (resultIntent.getBooleanExtra(getString(R.string.extra_finish_activity), false)) {
if (resultIntent.getBooleanExtra(getString(R.string.extra_finish_parent_activities), false)) {
viewHomesteads();
} else {
finish();
}
}
}
break;
case R.id.intent_people_browser:
if (resultCode == Activity.RESULT_OK && resultIntent != null
&& resultIntent.hasExtra(getString(R.string.extra_selected_items))) {
ContentResolver contentResolver = getContentResolver();
MediaItem sharedMediaItem = MediaManager.findMediaByInternalId(contentResolver, mMediaInternalId);
ArrayList<FrameMediaContainer> smilContents = null;
if (sharedMediaItem.getType() == MediaTabletProvider.TYPE_NARRATIVE) {
smilContents = SMILUtilities.getSMILFrameList(sharedMediaItem.getFile(), 1, false, 0, false);
}
String[] selectedPeople = resultIntent
.getStringArrayExtra(getString(R.string.extra_selected_items));
int numPeopleShared = selectedPeople.length;
for (String shareDestination : selectedPeople) {
if (!shareDestination.equals(mMediaParentId)) { // don't send to self
if (sharedMediaItem.getType() == MediaTabletProvider.TYPE_NARRATIVE) {
ImportedFileParser.duplicateSMILElements(contentResolver, smilContents,
sharedMediaItem.getFile(), shareDestination, MediaItem.MEDIA_PRIVATE, false);
} else {
final MediaItem newMediaItem = MediaItem.fromExisting(sharedMediaItem,
MediaTabletProvider.getNewInternalId(), shareDestination,
System.currentTimeMillis());
newMediaItem.setPubliclySharedStatus(MediaItem.MEDIA_PRIVATE);
try {
IOUtilities.copyFile(sharedMediaItem.getFile(), newMediaItem.getFile());
MediaManager.addMedia(contentResolver, newMediaItem);
} catch (IOException e) {
}
}
} else {
numPeopleShared -= 1;
}
}
Toast.makeText(
MediaViewerActivity.this,
String.format(
numPeopleShared == 1 ? getString(R.string.share_media_choose_completed_singular)
: getString(R.string.share_media_choose_completed_plural), numPeopleShared),
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onActivityResult(requestCode, resultCode, resultIntent);
}
}
private ReflectionTabListener mReflectionTabListener = new ReflectionTabListener() {
@Override
public void onTabSelected(int tabId) {
switch (tabId) {
case R.id.intent_homestead_browser:
viewHomesteads();
break;
case R.id.intent_people_browser:
viewPeople();
break;
case R.id.intent_media_browser:
finish();
break;
default:
break;
}
}
@Override
public void onTabReselected(int tabId) {
}
@Override
public void onTabUnselected(int tabId) {
}
};
}
| true | true | private void sendMedia() {
if (MediaTablet.DIRECTORY_TEMP == null) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_missing_directory, true);
return;
}
boolean canCopyToExternal = true;
if (IOUtilities.isInternalPath(MediaTablet.DIRECTORY_TEMP.getAbsolutePath())) {
canCopyToExternal = false;
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_potential_problem, true);
}
// important to keep awake to export because we only have one chance to display the export options
// after creating mov or smil file (will be cancelled on screen unlock; Android is weird)
// TODO: move to a better (e.g. notification bar) method of exporting?
UIUtilities.acquireKeepScreenOn(getWindow());
ArrayList<Uri> filesToSend;
String mimeType = "video/*";
MediaItem currentMediaItem = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
if (currentMediaItem.getType() != MediaTabletProvider.TYPE_NARRATIVE) {
filesToSend = new ArrayList<Uri>();
File currentFile = currentMediaItem.getFile();
File publicFile = currentFile;
// can't send from private data directory
if (IOUtilities.isInternalPath(currentFile.getAbsolutePath()) && canCopyToExternal) {
try {
publicFile = new File(MediaTablet.DIRECTORY_TEMP, currentFile.getName());
IOUtilities.copyFile(currentFile, publicFile);
IOUtilities.setFullyPublic(publicFile);
} catch (IOException e) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.error_sending_media);
return;
}
}
filesToSend.add(Uri.fromFile(publicFile));
switch (currentMediaItem.getType()) {
case MediaTabletProvider.TYPE_IMAGE_BACK:
case MediaTabletProvider.TYPE_IMAGE_FRONT:
mimeType = "image/*";
break;
case MediaTabletProvider.TYPE_AUDIO:
mimeType = "audio/*";
break;
case MediaTabletProvider.TYPE_VIDEO:
break;
case MediaTabletProvider.TYPE_TEXT:
mimeType = "text/*";
break;
case MediaTabletProvider.TYPE_UNKNOWN:
default:
mimeType = "unknown"; // TODO
break;
}
} else {
// TODO: extract and combine with MediaPhone version
Resources res = getResources();
final ArrayList<FrameMediaContainer> smilContents = SMILUtilities.getSMILFrameList(
currentMediaItem.getFile(), res.getInteger(R.integer.frame_narrative_sequence_increment), false, 0,
false);
// random name to counter repeat sending name issues
final String exportName = String.format("%s-%s",
getString(R.string.app_name).replaceAll("[^a-zA-Z0-9]+", "-").toLowerCase(Locale.ENGLISH),
MediaTabletProvider.getNewInternalId().substring(0, 8));
final Map<Integer, Object> settings = new Hashtable<Integer, Object>();
settings.put(MediaUtilities.KEY_AUDIO_RESOURCE_ID, R.raw.ic_audio_playback);
// some output settings
settings.put(MediaUtilities.KEY_BACKGROUND_COLOUR, res.getColor(R.color.icon_background));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_NO_IMAGE, res.getColor(R.color.icon_text_no_image));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_WITH_IMAGE, res.getColor(R.color.icon_text_with_image));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_COLOUR, res.getColor(R.color.icon_text_background));
settings.put(MediaUtilities.KEY_TEXT_SPACING, res.getDimensionPixelSize(R.dimen.export_icon_text_padding));
settings.put(MediaUtilities.KEY_TEXT_CORNER_RADIUS,
res.getDimensionPixelSize(R.dimen.export_icon_text_corner_radius));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_SPAN_WIDTH,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);
// TODO: do we want to do getDimensionPixelSize for export?
settings.put(MediaUtilities.KEY_MAX_TEXT_FONT_SIZE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_size));
settings.put(MediaUtilities.KEY_MAX_TEXT_CHARACTERS_PER_LINE,
res.getInteger(R.integer.export_maximum_text_characters_per_line));
settings.put(MediaUtilities.KEY_MAX_TEXT_HEIGHT_WITH_IMAGE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_height_with_image));
settings.put(MediaUtilities.KEY_OUTPUT_WIDTH, res.getInteger(R.integer.export_smil_width));
settings.put(MediaUtilities.KEY_OUTPUT_HEIGHT, res.getInteger(R.integer.export_smil_height));
settings.put(MediaUtilities.KEY_PLAYER_BAR_ADJUSTMENT,
res.getInteger(R.integer.export_smil_player_bar_adjustment));
filesToSend = SMILUtilities.generateNarrativeSMIL(getResources(), new File(MediaTablet.DIRECTORY_TEMP,
String.format("%s%s", exportName, MediaUtilities.SMIL_FILE_EXTENSION)), smilContents, settings);
}
sendFiles(filesToSend, mimeType);
}
| private void sendMedia() {
if (MediaTablet.DIRECTORY_TEMP == null) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_missing_directory, true);
return;
}
boolean canCopyToExternal = true;
if (IOUtilities.isInternalPath(MediaTablet.DIRECTORY_TEMP.getAbsolutePath())) {
canCopyToExternal = false;
UIUtilities.showToast(MediaViewerActivity.this, R.string.export_potential_problem, true);
}
// important to keep awake to export because we only have one chance to display the export options
// after creating mov or smil file (will be cancelled on screen unlock; Android is weird)
// TODO: move to a better (e.g. notification bar) method of exporting?
UIUtilities.acquireKeepScreenOn(getWindow());
ArrayList<Uri> filesToSend;
String mimeType = "video/*";
MediaItem currentMediaItem = MediaManager.findMediaByInternalId(getContentResolver(), mMediaInternalId);
if (currentMediaItem.getType() != MediaTabletProvider.TYPE_NARRATIVE) {
filesToSend = new ArrayList<Uri>();
File currentFile = currentMediaItem.getFile();
File publicFile = currentFile;
// can't send from private data directory
if (IOUtilities.isInternalPath(currentFile.getAbsolutePath()) && canCopyToExternal) {
try {
publicFile = new File(MediaTablet.DIRECTORY_TEMP, currentFile.getName());
IOUtilities.copyFile(currentFile, publicFile);
IOUtilities.setFullyPublic(publicFile);
} catch (IOException e) {
UIUtilities.showToast(MediaViewerActivity.this, R.string.error_sending_media);
return;
}
}
filesToSend.add(Uri.fromFile(publicFile));
switch (currentMediaItem.getType()) {
case MediaTabletProvider.TYPE_IMAGE_BACK:
case MediaTabletProvider.TYPE_IMAGE_FRONT:
mimeType = "image/*";
break;
case MediaTabletProvider.TYPE_AUDIO:
mimeType = "audio/*";
break;
case MediaTabletProvider.TYPE_VIDEO:
break;
case MediaTabletProvider.TYPE_TEXT:
mimeType = "text/*";
break;
case MediaTabletProvider.TYPE_UNKNOWN:
default:
mimeType = "unknown"; // TODO
break;
}
} else {
// TODO: extract and combine with MediaPhone version
Resources res = getResources();
final ArrayList<FrameMediaContainer> smilContents = SMILUtilities.getSMILFrameList(
currentMediaItem.getFile(), res.getInteger(R.integer.frame_narrative_sequence_increment), false, 0,
false);
// random name to counter repeat sending name issues
final String exportName = String.format("%s-%s",
getString(R.string.app_name).replaceAll("[^a-zA-Z0-9]+", "-").toLowerCase(Locale.ENGLISH),
MediaTabletProvider.getNewInternalId().substring(0, 8));
final Map<Integer, Object> settings = new Hashtable<Integer, Object>();
settings.put(MediaUtilities.KEY_AUDIO_RESOURCE_ID, R.raw.ic_audio_playback);
// some output settings
settings.put(MediaUtilities.KEY_BACKGROUND_COLOUR, res.getColor(R.color.icon_background));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_NO_IMAGE, res.getColor(R.color.icon_text_no_image));
settings.put(MediaUtilities.KEY_TEXT_COLOUR_WITH_IMAGE, res.getColor(R.color.icon_text_with_image));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_COLOUR, res.getColor(R.color.icon_text_background));
settings.put(MediaUtilities.KEY_TEXT_SPACING, res.getDimensionPixelSize(R.dimen.export_icon_text_padding));
settings.put(MediaUtilities.KEY_TEXT_CORNER_RADIUS,
res.getDimensionPixelSize(R.dimen.export_icon_text_corner_radius));
settings.put(MediaUtilities.KEY_TEXT_BACKGROUND_SPAN_WIDTH,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);
// TODO: do we want to do getDimensionPixelSize for export?
settings.put(MediaUtilities.KEY_MAX_TEXT_FONT_SIZE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_size));
settings.put(MediaUtilities.KEY_MAX_TEXT_CHARACTERS_PER_LINE,
res.getInteger(R.integer.export_maximum_text_characters_per_line));
settings.put(MediaUtilities.KEY_MAX_TEXT_HEIGHT_WITH_IMAGE,
res.getDimensionPixelSize(R.dimen.export_maximum_text_height_with_image));
settings.put(MediaUtilities.KEY_OUTPUT_WIDTH, res.getInteger(R.integer.export_smil_width));
settings.put(MediaUtilities.KEY_OUTPUT_HEIGHT, res.getInteger(R.integer.export_smil_height));
settings.put(MediaUtilities.KEY_PLAYER_BAR_ADJUSTMENT,
res.getInteger(R.integer.export_smil_player_bar_adjustment));
filesToSend = SMILUtilities.generateNarrativeSMIL(getResources(), new File(MediaTablet.DIRECTORY_TEMP,
exportName + MediaUtilities.SMIL_FILE_EXTENSION), smilContents, settings);
}
sendFiles(filesToSend, mimeType);
}
|
diff --git a/src/main/java/fizzbuzz/FizzBuzzWithSwitch.java b/src/main/java/fizzbuzz/FizzBuzzWithSwitch.java
index bb904d5..19c1342 100644
--- a/src/main/java/fizzbuzz/FizzBuzzWithSwitch.java
+++ b/src/main/java/fizzbuzz/FizzBuzzWithSwitch.java
@@ -1,25 +1,25 @@
package fizzbuzz;
public class FizzBuzzWithSwitch implements FizzBuzz {
@Override
public String messageFor(int number) {
// Simple bit flag approach
int status = isMultipleOf(3, number);
status |= (isMultipleOf(5, number) << 1);
switch(status){
case 0: return "" + number; // Simples
case 1: return "Fizz"; // Multiple of 3
case 2: return "Buzz"; // Multiple of 5
case 3: return "FizzBuzz"; // Multiple of 3 & 5
default:
- throw new IllegalStateException("Unexpected status: " + status);
+ throw new AssertionError("Unexpected status: " + status);
}
}
private static int isMultipleOf(int divisor, int number){
return (number % divisor == 0) ? 1 : 0;
}
}
| true | true | public String messageFor(int number) {
// Simple bit flag approach
int status = isMultipleOf(3, number);
status |= (isMultipleOf(5, number) << 1);
switch(status){
case 0: return "" + number; // Simples
case 1: return "Fizz"; // Multiple of 3
case 2: return "Buzz"; // Multiple of 5
case 3: return "FizzBuzz"; // Multiple of 3 & 5
default:
throw new IllegalStateException("Unexpected status: " + status);
}
}
| public String messageFor(int number) {
// Simple bit flag approach
int status = isMultipleOf(3, number);
status |= (isMultipleOf(5, number) << 1);
switch(status){
case 0: return "" + number; // Simples
case 1: return "Fizz"; // Multiple of 3
case 2: return "Buzz"; // Multiple of 5
case 3: return "FizzBuzz"; // Multiple of 3 & 5
default:
throw new AssertionError("Unexpected status: " + status);
}
}
|
diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
index 63023fd3d4..774aa4698c 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
@@ -1,886 +1,886 @@
package org.drools.reteoo;
/*
* Copyright 2005 JBoss 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.
*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.drools.InitialFact;
import org.drools.RuleIntegrationException;
import org.drools.RuntimeDroolsException;
import org.drools.base.ClassFieldExtractor;
import org.drools.base.ClassObjectType;
import org.drools.base.DroolsQuery;
import org.drools.base.FieldFactory;
import org.drools.base.ValueType;
import org.drools.base.evaluators.Operator;
import org.drools.common.BaseNode;
import org.drools.common.BetaConstraints;
import org.drools.common.DefaultBetaConstraints;
import org.drools.common.DoubleBetaConstraints;
import org.drools.common.EmptyBetaConstraints;
import org.drools.common.InstanceEqualsConstraint;
import org.drools.common.InstanceNotEqualsConstraint;
import org.drools.common.QuadroupleBetaConstraints;
import org.drools.common.SingleBetaConstraints;
import org.drools.common.TripleBetaConstraints;
import org.drools.rule.Accumulate;
import org.drools.rule.And;
import org.drools.rule.Collect;
import org.drools.rule.Column;
import org.drools.rule.Declaration;
import org.drools.rule.EvalCondition;
import org.drools.rule.Exists;
import org.drools.rule.From;
import org.drools.rule.GroupElement;
import org.drools.rule.InvalidPatternException;
import org.drools.rule.LiteralConstraint;
import org.drools.rule.Not;
import org.drools.rule.Query;
import org.drools.rule.Rule;
import org.drools.spi.AlphaNodeFieldConstraint;
import org.drools.spi.BetaNodeFieldConstraint;
import org.drools.spi.Constraint;
import org.drools.spi.FieldValue;
/**
* Builds the Rete-OO network for a <code>Package</code>.
*
* @see org.drools.rule.Package
*
* @author <a href="mailto:[email protected]">Mark Proctor</a>
* @author <a href="mailto:[email protected]">Bob McWhirter</a>
*
*/
class ReteooBuilder
implements
Serializable {
// ------------------------------------------------------------
// Instance members
// ------------------------------------------------------------
/**
*
*/
private static final long serialVersionUID = 1737643968218792944L;
/** The RuleBase */
private transient ReteooRuleBase ruleBase;
/** Rete network to build against. */
private transient Rete rete;
private transient ReteooWorkingMemory[] workingMemories;
/** Nodes that have been attached. */
private final Map attachedNodes;
private TupleSource tupleSource;
private ObjectSource objectSource;
private Map declarations;
private int id;
private Map rules;
private Map objectType;
private int currentOffsetAdjustment;
private final boolean removeIdentities;
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
/**
* Construct a <code>Builder</code> against an existing <code>Rete</code>
* network.
*/
ReteooBuilder(final ReteooRuleBase ruleBase) {
this.ruleBase = ruleBase;
this.rete = this.ruleBase.getRete();
this.attachedNodes = new HashMap();
this.rules = new HashMap();
//Set to 1 as Rete node is set to 0
this.id = 1;
this.removeIdentities = this.ruleBase.getConfiguration().isRemoveIdentities();
}
/**
* Allow this to be settable, otherwise we get infinite recursion on serialisation
* @param ruleBase
*/
void setRuleBase(final ReteooRuleBase ruleBase) {
this.ruleBase = ruleBase;
}
/**
* Allow this to be settable, otherwise we get infinite recursion on serialisation
* @param ruleBase
*/
void setRete(final Rete rete) {
}
// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
/**
* Add a <code>Rule</code> to the network.
*
* @param rule
* The rule to add.
*
* @throws RuleIntegrationException
* if an error prevents complete construction of the network for
* the <code>Rule</code>.
* @throws InvalidPatternException
*/
void addRule(final Rule rule) throws InvalidPatternException {
// reset working memories for potential propagation
this.workingMemories = (ReteooWorkingMemory[]) this.ruleBase.getWorkingMemories().toArray( new ReteooWorkingMemory[this.ruleBase.getWorkingMemories().size()] );
this.currentOffsetAdjustment = 0;
final List nodes = new ArrayList();
final And[] and = rule.getTransformedLhs();
for ( int i = 0; i < and.length; i++ ) {
if ( !hasColumns( and[i] ) ) {
addInitialFactMatch( and[i] );
}
addRule( and[i],
rule );
BaseNode node = null;
if ( !(rule instanceof Query) ) {
// Check a consequence is set
if ( rule.getConsequence() == null ) {
throw new InvalidPatternException( "Rule '" + rule.getName() + "' has no Consequence" );
}
node = new TerminalNode( this.id++,
this.tupleSource,
rule );
} else {
// Check there is no consequence
if ( rule.getConsequence() != null ) {
throw new InvalidPatternException( "Query '" + rule.getName() + "' should have no Consequence" );
}
node = new QueryTerminalNode( this.id++,
this.tupleSource,
rule );
}
nodes.add( node );
if ( this.workingMemories.length == 0 ) {
node.attach();
} else {
node.attach( this.workingMemories );
}
}
this.rules.put( rule,
nodes.toArray( new BaseNode[nodes.size()] ) );
}
private boolean hasColumns(final GroupElement ge) {
for ( final Iterator it = ge.getChildren().iterator(); it.hasNext(); ) {
final Object object = it.next();
if ( object instanceof Column || (object instanceof GroupElement && hasColumns( (GroupElement) object )) ) {
return true;
}
}
return false;
}
private void addInitialFactMatch(final And and) {
And temp = null;
// If we have children we know there are no columns but we need to make sure that InitialFact is first
if ( !and.getChildren().isEmpty() ) {
temp = (And) and.clone();
and.getChildren().clear();
}
final Column column = new Column( 0,
new ClassObjectType( InitialFact.class ) );
and.addChild( column );
// now we know InitialFact is first add all the previous constrains
if ( temp != null ) {
and.getChildren().addAll( temp.getChildren() );
}
this.currentOffsetAdjustment = 1;
}
private void addRule(final And and,
final Rule rule) throws InvalidPatternException {
this.objectSource = null;
this.tupleSource = null;
this.declarations = new HashMap();
this.objectType = new LinkedHashMap();
if ( rule instanceof Query ) {
attachQuery( rule.getName() );
}
for ( final Iterator it = and.getChildren().iterator(); it.hasNext(); ) {
final Object object = it.next();
if ( object instanceof EvalCondition ) {
final EvalCondition eval = (EvalCondition) object;
checkUnboundDeclarations( eval.getRequiredDeclarations() );
this.tupleSource = attachNode( new EvalConditionNode( this.id++,
this.tupleSource,
eval ) );
continue;
}
BetaConstraints binder = null;
Column column = null;
if ( object instanceof Column ) {
column = (Column) object;
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( (Column) object,
and,
this.removeIdentities );
// If a tupleSource does not exist then we need to adapt this
// into
// a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
this.objectSource ) );
// objectSource is created by the attachColumn method, if we
// adapt this to
// a TupleSource then we need to null the objectSource
// reference.
this.objectSource = null;
}
} else if ( object instanceof GroupElement ) {
// If its not a Column or EvalCondition then it can either be a Not or an Exists
GroupElement ce = (GroupElement) object;
while ( !(ce.getChildren().get( 0 ) instanceof Column) ) {
ce = (GroupElement) ce.getChildren().get( 0 );
}
column = (Column) ce.getChildren().get( 0 );
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource objectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
objectSource ) );
}
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( column,
and,
- false );
+ this.removeIdentities );
}
if ( object.getClass() == Not.class ) {
attachNot( this.tupleSource,
(Not) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == Exists.class ) {
attachExists( this.tupleSource,
(Exists) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == From.class ) {
attachFrom( this.tupleSource,
(From) object );
} else if ( object.getClass() == Accumulate.class ) {
attachAccumulate( this.tupleSource,
and,
(Accumulate) object );
} else if ( object.getClass() == Collect.class ) {
attachCollect( this.tupleSource,
and,
(Collect) object );
} else if ( this.objectSource != null ) {
this.tupleSource = attachNode( new JoinNode( this.id++,
this.tupleSource,
this.objectSource,
binder ) );
binder = null;
}
}
}
public BaseNode[] getTerminalNodes(final Rule rule) {
return (BaseNode[]) this.rules.remove( rule );
}
private void attachQuery(final String queryName) {
// incrementing offset adjustment, since we are adding a new ObjectNodeType as our
// first column
this.currentOffsetAdjustment += 1;
final ObjectSource objectTypeSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( DroolsQuery.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
final ClassFieldExtractor extractor = new ClassFieldExtractor( DroolsQuery.class,
"name" );
final FieldValue field = FieldFactory.getFieldValue( queryName,
ValueType.STRING_TYPE );
final LiteralConstraint constraint = new LiteralConstraint( extractor,
ValueType.STRING_TYPE.getEvaluator( Operator.EQUAL ),
field );
final ObjectSource alphaNodeSource = attachNode( new AlphaNode( this.id++,
constraint,
objectTypeSource,
this.ruleBase.getConfiguration().isAlphaMemory(),
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
alphaNodeSource ) );
}
private BetaConstraints attachColumn(final Column column,
final GroupElement parent,
boolean removeIdentities) throws InvalidPatternException {
// Adjusting offset in case a previous Initial-Fact was added to the network
column.adjustOffset( this.currentOffsetAdjustment );
// Check if the Column is bound
if ( column.getDeclaration() != null ) {
final Declaration declaration = column.getDeclaration();
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
}
final List predicates = attachAlphaNodes( column,
removeIdentities );
final BetaConstraints binder = createBetaNodeConstraint( predicates );
return binder;
}
public List attachAlphaNodes(final Column column,
final boolean removeIdentities) throws InvalidPatternException {
final List constraints = column.getConstraints();
this.objectSource = attachNode( new ObjectTypeNode( this.id++,
column.getObjectType(),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
final List betaConstraints = new ArrayList();
if ( removeIdentities && column.getObjectType().getClass() == ClassObjectType.class ) {
// Check if this object type exists before
// If it does we need stop instance equals cross product
final Class thisClass = ((ClassObjectType) column.getObjectType()).getClassType();
for ( final Iterator it = this.objectType.entrySet().iterator(); it.hasNext(); ) {
final Map.Entry entry = (Map.Entry) it.next();
final Class previousClass = ((ClassObjectType) entry.getKey()).getClassType();
if ( thisClass.isAssignableFrom( previousClass ) ) {
betaConstraints.add( new InstanceNotEqualsConstraint( (Column) entry.getValue() ) );
}
}
// Must be added after the checking, otherwise it matches against itself
this.objectType.put( column.getObjectType(),
column );
}
for ( final Iterator it = constraints.iterator(); it.hasNext(); ) {
final Object object = it.next();
// Check if its a declaration
if ( object instanceof Declaration ) {
final Declaration declaration = (Declaration) object;
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
continue;
}
final Constraint constraint = (Constraint) object;
Declaration[] declarations = constraint.getRequiredDeclarations();
boolean isAlphaConstraint = true;
for(int i = 0; isAlphaConstraint && i < declarations.length; i++ ) {
if( declarations[i].getColumn() != column ) {
isAlphaConstraint = false;
}
}
if ( isAlphaConstraint ) {
this.objectSource = attachNode( new AlphaNode( this.id++,
(AlphaNodeFieldConstraint) constraint,
this.objectSource ) );
} else {
checkUnboundDeclarations( constraint.getRequiredDeclarations() );
betaConstraints.add( constraint );
}
}
return betaConstraints;
}
private void attachNot(final TupleSource tupleSource,
final Not not,
final ObjectSource ObjectSource,
final BetaConstraints binder,
final Column column) {
final NotNode notNode = (NotNode) attachNode( new NotNode( this.id++,
tupleSource,
ObjectSource,
binder ) );
if ( not.getChild() instanceof Not ) {
final RightInputAdapterNode adapter = (RightInputAdapterNode) attachNode( new RightInputAdapterNode( this.id++,
column,
notNode ) );
attachNot( tupleSource,
(Not) not.getChild(),
adapter,
EmptyBetaConstraints.getInstance(),
column );
} else if ( not.getChild() instanceof Exists ) {
final RightInputAdapterNode adapter = (RightInputAdapterNode) attachNode( new RightInputAdapterNode( this.id++,
column,
notNode ) );
attachExists( tupleSource,
(Exists) not.getChild(),
adapter,
EmptyBetaConstraints.getInstance(),
column );
} else {
this.tupleSource = notNode;
}
}
private void attachExists(final TupleSource tupleSource,
final Exists exists,
final ObjectSource ObjectSource,
final BetaConstraints binder,
final Column column) {
NotNode notNode = (NotNode) attachNode( new NotNode( this.id++,
tupleSource,
ObjectSource,
binder ) );
RightInputAdapterNode adapter = (RightInputAdapterNode) attachNode( new RightInputAdapterNode( this.id++,
column,
notNode ) );
final BetaConstraints identityBinder = new SingleBetaConstraints( new InstanceEqualsConstraint( column ), this.ruleBase.getConfiguration() );
notNode = (NotNode) attachNode( new NotNode( this.id++,
tupleSource,
adapter,
identityBinder ) );
if ( exists.getChild() instanceof Not ) {
adapter = (RightInputAdapterNode) attachNode( new RightInputAdapterNode( this.id++,
column,
notNode ) );
attachNot( tupleSource,
(Not) exists.getChild(),
adapter,
EmptyBetaConstraints.getInstance(),
column );
} else if ( exists.getChild() instanceof Exists ) {
adapter = (RightInputAdapterNode) attachNode( new RightInputAdapterNode( this.id++,
column,
notNode ) );
attachExists( tupleSource,
(Exists) exists.getChild(),
adapter,
EmptyBetaConstraints.getInstance(),
column );
} else {
this.tupleSource = notNode;
}
}
/**
* Attaches a node into the network. If a node already exists that could
* substitute, it is used instead.
*
* @param candidate
* The node to attach.
* @param leafNodes
* The list to which the newly added node will be added.
*/
private TupleSource attachNode(final TupleSource candidate) {
TupleSource node = (TupleSource) this.attachedNodes.get( candidate );
if ( this.ruleBase.getConfiguration().isShareBetaNodes() && node != null ) {
if ( !node.isInUse() ) {
if ( this.workingMemories.length == 0 ) {
node.attach();
} else {
node.attach( this.workingMemories );
}
}
node.addShare();
this.id--;
} else {
if ( this.workingMemories.length == 0 ) {
candidate.attach();
} else {
candidate.attach( this.workingMemories );
}
this.attachedNodes.put( candidate,
candidate );
node = candidate;
}
return node;
}
private void attachFrom(final TupleSource tupleSource,
final From from) {
final Column column = from.getColumn();
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource objectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
objectSource ) );
}
// Adjusting offset in case a previous Initial-Fact was added to the network
column.adjustOffset( this.currentOffsetAdjustment );
final List constraints = column.getConstraints();
// Check if the Column is bound
if ( column.getDeclaration() != null ) {
final Declaration declaration = column.getDeclaration();
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
}
final List betaConstraints = new ArrayList();
final List alphaConstraints = new ArrayList();
for ( final Iterator it = constraints.iterator(); it.hasNext(); ) {
final Object object = it.next();
// Check if its a declaration
if ( object instanceof Declaration ) {
final Declaration declaration = (Declaration) object;
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
continue;
}
final AlphaNodeFieldConstraint fieldConstraint = (AlphaNodeFieldConstraint) object;
if ( fieldConstraint instanceof LiteralConstraint ) {
alphaConstraints.add( fieldConstraint );
} else {
checkUnboundDeclarations( fieldConstraint.getRequiredDeclarations() );
betaConstraints.add( fieldConstraint );
}
}
final BetaConstraints binder = createBetaNodeConstraint( betaConstraints );
this.tupleSource = attachNode( new FromNode( this.id++,
from.getDataProvider(),
this.tupleSource,
(AlphaNodeFieldConstraint[]) alphaConstraints.toArray( new AlphaNodeFieldConstraint[alphaConstraints.size()] ),
binder ) );
}
private void attachAccumulate(final TupleSource tupleSource,
final And parent,
final Accumulate accumulate) {
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource auxObjectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
auxObjectSource ) );
}
final Column sourceColumn = accumulate.getSourceColumn();
final BetaConstraints sourceBinder = attachColumn( sourceColumn,
parent,
true );
final Column column = accumulate.getResultColumn();
// Adjusting offset in case a previous Initial-Fact was added to the network
column.adjustOffset( this.currentOffsetAdjustment );
final List constraints = column.getConstraints();
// Check if the Column is bound
if ( column.getDeclaration() != null ) {
final Declaration declaration = column.getDeclaration();
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
}
final List betaConstraints = new ArrayList();
final List alphaConstraints = new ArrayList();
for ( final Iterator it = constraints.iterator(); it.hasNext(); ) {
final Object object = it.next();
// Check if its a declaration
if ( object instanceof Declaration ) {
final Declaration declaration = (Declaration) object;
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
continue;
}
final AlphaNodeFieldConstraint fieldConstraint = (AlphaNodeFieldConstraint) object;
if ( fieldConstraint instanceof LiteralConstraint ) {
alphaConstraints.add( fieldConstraint );
} else {
checkUnboundDeclarations( fieldConstraint.getRequiredDeclarations() );
betaConstraints.add( fieldConstraint );
}
}
final BetaConstraints resultsBinder = createBetaNodeConstraint( betaConstraints );
this.tupleSource = attachNode( new AccumulateNode( this.id++,
this.tupleSource,
this.objectSource,
(AlphaNodeFieldConstraint[]) alphaConstraints.toArray( new AlphaNodeFieldConstraint[alphaConstraints.size()] ),
sourceBinder,
resultsBinder,
accumulate ) );
}
private void attachCollect(final TupleSource tupleSource,
final And parent,
final Collect collect) {
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource auxObjectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
auxObjectSource ) );
}
final Column sourceColumn = collect.getSourceColumn();
final BetaConstraints sourceBinder = attachColumn( sourceColumn,
parent,
true );
final Column column = collect.getResultColumn();
// Adjusting offset in case a previous Initial-Fact was added to the network
column.adjustOffset( this.currentOffsetAdjustment );
final List constraints = column.getConstraints();
// Check if the Column is bound
if ( column.getDeclaration() != null ) {
final Declaration declaration = column.getDeclaration();
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
}
final List betaConstraints = new ArrayList();
final List alphaConstraints = new ArrayList();
for ( final Iterator it = constraints.iterator(); it.hasNext(); ) {
final Object object = it.next();
// Check if its a declaration
if ( object instanceof Declaration ) {
final Declaration declaration = (Declaration) object;
// Add the declaration the map of previously bound declarations
this.declarations.put( declaration.getIdentifier(),
declaration );
continue;
}
final AlphaNodeFieldConstraint fieldConstraint = (AlphaNodeFieldConstraint) object;
if ( fieldConstraint instanceof LiteralConstraint ) {
alphaConstraints.add( fieldConstraint );
} else {
checkUnboundDeclarations( fieldConstraint.getRequiredDeclarations() );
betaConstraints.add( fieldConstraint );
}
}
final BetaConstraints resultsBinder = createBetaNodeConstraint( betaConstraints );
this.tupleSource = attachNode( new CollectNode( this.id++,
this.tupleSource,
this.objectSource,
(AlphaNodeFieldConstraint[]) alphaConstraints.toArray( new AlphaNodeFieldConstraint[alphaConstraints.size()] ),
sourceBinder,
resultsBinder,
collect ) );
}
private ObjectSource attachNode(final ObjectSource candidate) {
ObjectSource node = (ObjectSource) this.attachedNodes.get( candidate );
if ( this.ruleBase.getConfiguration().isShareAlphaNodes() && node != null) {
if ( !node.isInUse() ) {
if ( this.workingMemories.length == 0 ) {
node.attach();
} else {
node.attach( this.workingMemories );
}
}
node.addShare();
this.id--;
} else {
if ( this.workingMemories.length == 0 ) {
candidate.attach();
} else {
candidate.attach( this.workingMemories );
}
this.attachedNodes.put( candidate,
candidate );
node = candidate;
}
return node;
}
public void removeRule(final Rule rule) {
// reset working memories for potential propagation
this.workingMemories = (ReteooWorkingMemory[]) this.ruleBase.getWorkingMemories().toArray( new ReteooWorkingMemory[this.ruleBase.getWorkingMemories().size()] );
final Object object = this.rules.get( rule );
final BaseNode[] nodes = (BaseNode[]) object;
for ( int i = 0, length = nodes.length; i < length; i++ ) {
final BaseNode node = nodes[i];
node.remove( null,
this.workingMemories );
}
}
/**
* Make sure the required declarations are previously bound
*
* @param declarations
* @throws InvalidPatternException
*/
private void checkUnboundDeclarations(final Declaration[] declarations) throws InvalidPatternException {
final List list = new ArrayList();
for ( int i = 0, length = declarations.length; i < length; i++ ) {
if ( this.declarations.get( declarations[i].getIdentifier() ) == null ) {
list.add( declarations[i].getIdentifier() );
}
}
// Make sure the required declarations
if ( list.size() != 0 ) {
final StringBuffer buffer = new StringBuffer();
buffer.append( list.get( 0 ) );
for ( int i = 1, size = list.size(); i < size; i++ ) {
buffer.append( ", " + list.get( i ) );
}
throw new InvalidPatternException( "Required Declarations not bound: '" + buffer );
}
}
public BetaConstraints createBetaNodeConstraint(final List list) {
BetaConstraints constraints;
switch ( list.size() ) {
case 0 :
constraints = EmptyBetaConstraints.getInstance();
break;
case 1 :
constraints = new SingleBetaConstraints( (BetaNodeFieldConstraint) list.get( 0 ), this.ruleBase.getConfiguration() );
break;
case 2 :
constraints = new DoubleBetaConstraints( (BetaNodeFieldConstraint[]) list.toArray( new BetaNodeFieldConstraint[list.size()] ), this.ruleBase.getConfiguration() );
break;
case 3 :
constraints = new TripleBetaConstraints( (BetaNodeFieldConstraint[]) list.toArray( new BetaNodeFieldConstraint[list.size()] ), this.ruleBase.getConfiguration() );
break;
case 4 :
constraints = new QuadroupleBetaConstraints( (BetaNodeFieldConstraint[]) list.toArray( new BetaNodeFieldConstraint[list.size()] ), this.ruleBase.getConfiguration() );
break;
default :
constraints = new DefaultBetaConstraints( (BetaNodeFieldConstraint[]) list.toArray( new BetaNodeFieldConstraint[list.size()] ), this.ruleBase.getConfiguration() );
}
return constraints;
}
}
| true | true | private void addRule(final And and,
final Rule rule) throws InvalidPatternException {
this.objectSource = null;
this.tupleSource = null;
this.declarations = new HashMap();
this.objectType = new LinkedHashMap();
if ( rule instanceof Query ) {
attachQuery( rule.getName() );
}
for ( final Iterator it = and.getChildren().iterator(); it.hasNext(); ) {
final Object object = it.next();
if ( object instanceof EvalCondition ) {
final EvalCondition eval = (EvalCondition) object;
checkUnboundDeclarations( eval.getRequiredDeclarations() );
this.tupleSource = attachNode( new EvalConditionNode( this.id++,
this.tupleSource,
eval ) );
continue;
}
BetaConstraints binder = null;
Column column = null;
if ( object instanceof Column ) {
column = (Column) object;
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( (Column) object,
and,
this.removeIdentities );
// If a tupleSource does not exist then we need to adapt this
// into
// a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
this.objectSource ) );
// objectSource is created by the attachColumn method, if we
// adapt this to
// a TupleSource then we need to null the objectSource
// reference.
this.objectSource = null;
}
} else if ( object instanceof GroupElement ) {
// If its not a Column or EvalCondition then it can either be a Not or an Exists
GroupElement ce = (GroupElement) object;
while ( !(ce.getChildren().get( 0 ) instanceof Column) ) {
ce = (GroupElement) ce.getChildren().get( 0 );
}
column = (Column) ce.getChildren().get( 0 );
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource objectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
objectSource ) );
}
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( column,
and,
false );
}
if ( object.getClass() == Not.class ) {
attachNot( this.tupleSource,
(Not) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == Exists.class ) {
attachExists( this.tupleSource,
(Exists) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == From.class ) {
attachFrom( this.tupleSource,
(From) object );
} else if ( object.getClass() == Accumulate.class ) {
attachAccumulate( this.tupleSource,
and,
(Accumulate) object );
} else if ( object.getClass() == Collect.class ) {
attachCollect( this.tupleSource,
and,
(Collect) object );
} else if ( this.objectSource != null ) {
this.tupleSource = attachNode( new JoinNode( this.id++,
this.tupleSource,
this.objectSource,
binder ) );
binder = null;
}
}
}
| private void addRule(final And and,
final Rule rule) throws InvalidPatternException {
this.objectSource = null;
this.tupleSource = null;
this.declarations = new HashMap();
this.objectType = new LinkedHashMap();
if ( rule instanceof Query ) {
attachQuery( rule.getName() );
}
for ( final Iterator it = and.getChildren().iterator(); it.hasNext(); ) {
final Object object = it.next();
if ( object instanceof EvalCondition ) {
final EvalCondition eval = (EvalCondition) object;
checkUnboundDeclarations( eval.getRequiredDeclarations() );
this.tupleSource = attachNode( new EvalConditionNode( this.id++,
this.tupleSource,
eval ) );
continue;
}
BetaConstraints binder = null;
Column column = null;
if ( object instanceof Column ) {
column = (Column) object;
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( (Column) object,
and,
this.removeIdentities );
// If a tupleSource does not exist then we need to adapt this
// into
// a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
this.objectSource ) );
// objectSource is created by the attachColumn method, if we
// adapt this to
// a TupleSource then we need to null the objectSource
// reference.
this.objectSource = null;
}
} else if ( object instanceof GroupElement ) {
// If its not a Column or EvalCondition then it can either be a Not or an Exists
GroupElement ce = (GroupElement) object;
while ( !(ce.getChildren().get( 0 ) instanceof Column) ) {
ce = (GroupElement) ce.getChildren().get( 0 );
}
column = (Column) ce.getChildren().get( 0 );
// If a tupleSource does not exist then we need to adapt an
// InitialFact into a a TupleSource using LeftInputAdapterNode
if ( this.tupleSource == null ) {
// adjusting offset as all tuples will now contain initial-fact at index 0
this.currentOffsetAdjustment = 1;
final ObjectSource objectSource = attachNode( new ObjectTypeNode( this.id++,
new ClassObjectType( InitialFact.class ),
this.rete,
this.ruleBase.getConfiguration().getAlphaNodeHashingThreshold()) );
this.tupleSource = attachNode( new LeftInputAdapterNode( this.id++,
objectSource ) );
}
// @REMOVEME after the milestone period
if(( binder != null) && ( binder != EmptyBetaConstraints.getInstance()))
throw new RuntimeDroolsException("This is a bug! Please report to Drools development team!");
binder = attachColumn( column,
and,
this.removeIdentities );
}
if ( object.getClass() == Not.class ) {
attachNot( this.tupleSource,
(Not) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == Exists.class ) {
attachExists( this.tupleSource,
(Exists) object,
this.objectSource,
binder,
column );
binder = null;
} else if ( object.getClass() == From.class ) {
attachFrom( this.tupleSource,
(From) object );
} else if ( object.getClass() == Accumulate.class ) {
attachAccumulate( this.tupleSource,
and,
(Accumulate) object );
} else if ( object.getClass() == Collect.class ) {
attachCollect( this.tupleSource,
and,
(Collect) object );
} else if ( this.objectSource != null ) {
this.tupleSource = attachNode( new JoinNode( this.id++,
this.tupleSource,
this.objectSource,
binder ) );
binder = null;
}
}
}
|
diff --git a/src/de/thm/ateam/memory/engine/type/SQLite.java b/src/de/thm/ateam/memory/engine/type/SQLite.java
index 8b38414..af92d15 100644
--- a/src/de/thm/ateam/memory/engine/type/SQLite.java
+++ b/src/de/thm/ateam/memory/engine/type/SQLite.java
@@ -1,63 +1,62 @@
/* memory
* de.thm.ateam.memory.engine
* SQLite.java
* 04.06.2012
*
* by Frank Kevin Zey
*/
package de.thm.ateam.memory.engine.type;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author Frank Kevin Zey
*
*/
public class SQLite extends SQLiteOpenHelper {
private final static String DB_NAME = "memory.sqlite";
private final static int DB_VERSION = 1;
public SQLite(Context ctx) {
super(ctx, DB_NAME, null, DB_VERSION);
}
/* (non-Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + PlayerDB.TABLE_NAME + "("
+ PlayerDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PlayerDB.NICK + " VARCHAR(42),"
+ PlayerDB.WIN + " INTEGER,"
+ PlayerDB.LOSE + " INTEGER,"
+ PlayerDB.DRAW + " INTEGER,"
+ PlayerDB.HIT + " INTEGER,"
+ PlayerDB.TURN + " INTEGER,"
+ "UNIQUE (" + PlayerDB.NICK + "));");
db.execSQL("CREATE TABLE " + DeckDB.TABLE_NAME + "("
+ DeckDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.NAME + " VARCHAR(42),"
+ DeckDB.BACK_CARD + "BLOB,"
+ "UNIQUE (" + DeckDB.NAME + "));");
db.execSQL("CREATE TABLE " + DeckDB.CARD_TABLE_NAME + "("
+ DeckDB.CARD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.CARD_DECK_ID + " INTEGER,"
- + DeckDB.CARD_BLOB + " BLOB,"
- + "UNIQUE (" + DeckDB.NAME + "));");
+ + DeckDB.CARD_BLOB + " BLOB;");
}
/* (non-Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//db.needUpgrade(newVersion);
}
}
| true | true | public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + PlayerDB.TABLE_NAME + "("
+ PlayerDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PlayerDB.NICK + " VARCHAR(42),"
+ PlayerDB.WIN + " INTEGER,"
+ PlayerDB.LOSE + " INTEGER,"
+ PlayerDB.DRAW + " INTEGER,"
+ PlayerDB.HIT + " INTEGER,"
+ PlayerDB.TURN + " INTEGER,"
+ "UNIQUE (" + PlayerDB.NICK + "));");
db.execSQL("CREATE TABLE " + DeckDB.TABLE_NAME + "("
+ DeckDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.NAME + " VARCHAR(42),"
+ DeckDB.BACK_CARD + "BLOB,"
+ "UNIQUE (" + DeckDB.NAME + "));");
db.execSQL("CREATE TABLE " + DeckDB.CARD_TABLE_NAME + "("
+ DeckDB.CARD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.CARD_DECK_ID + " INTEGER,"
+ DeckDB.CARD_BLOB + " BLOB,"
+ "UNIQUE (" + DeckDB.NAME + "));");
}
| public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + PlayerDB.TABLE_NAME + "("
+ PlayerDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PlayerDB.NICK + " VARCHAR(42),"
+ PlayerDB.WIN + " INTEGER,"
+ PlayerDB.LOSE + " INTEGER,"
+ PlayerDB.DRAW + " INTEGER,"
+ PlayerDB.HIT + " INTEGER,"
+ PlayerDB.TURN + " INTEGER,"
+ "UNIQUE (" + PlayerDB.NICK + "));");
db.execSQL("CREATE TABLE " + DeckDB.TABLE_NAME + "("
+ DeckDB.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.NAME + " VARCHAR(42),"
+ DeckDB.BACK_CARD + "BLOB,"
+ "UNIQUE (" + DeckDB.NAME + "));");
db.execSQL("CREATE TABLE " + DeckDB.CARD_TABLE_NAME + "("
+ DeckDB.CARD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DeckDB.CARD_DECK_ID + " INTEGER,"
+ DeckDB.CARD_BLOB + " BLOB;");
}
|
diff --git a/com/buglabs/bug/module/camera/CameraModlet.java b/com/buglabs/bug/module/camera/CameraModlet.java
index bd68fb3..e768ace 100644
--- a/com/buglabs/bug/module/camera/CameraModlet.java
+++ b/com/buglabs/bug/module/camera/CameraModlet.java
@@ -1,308 +1,308 @@
/* Copyright (c) 2007, 2008 Bug Labs, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
package com.buglabs.bug.module.camera;
import java.awt.Rectangle;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
import com.buglabs.bug.input.pub.InputEventProvider;
import com.buglabs.bug.jni.camera.Camera;
import com.buglabs.bug.jni.camera.CameraControl;
import com.buglabs.bug.jni.common.CharDeviceUtils;
import com.buglabs.bug.menu.pub.StatusBarUtils;
import com.buglabs.bug.module.camera.pub.ICameraButtonEventProvider;
import com.buglabs.bug.module.camera.pub.ICameraDevice;
import com.buglabs.bug.module.camera.pub.ICameraModuleControl;
import com.buglabs.bug.module.pub.IModlet;
import com.buglabs.module.IModuleControl;
import com.buglabs.module.IModuleProperty;
import com.buglabs.module.ModuleProperty;
import com.buglabs.services.ws.IWSResponse;
import com.buglabs.services.ws.PublicWSDefinition;
import com.buglabs.services.ws.PublicWSProvider;
import com.buglabs.services.ws.WSResponse;
import com.buglabs.util.LogServiceUtil;
import com.buglabs.util.RemoteOSGiServiceConstants;
import com.buglabs.util.trackers.PublicWSAdminTracker;
/**
*
* @author kgilmer
*
*/
public class CameraModlet implements IModlet, ICameraDevice, PublicWSProvider, IModuleControl {
private static final String IMAGE_MIME_TYPE = "image/jpg";
private static final String DEVNODE_INPUT_DEVICE = "/dev/input/bmi_cam";
private static final String CAMERA_DEVICE_NODE = "/dev/v4l/video0";
private static final String CAMERA_CONTROL_DEVICE_NODE = "/dev/bug_camera_control";
private ServiceTracker wsTracker;
private int megapixels;
private List modProps;
private final BundleContext context;
private final int slotId;
private final String moduleName;
private ServiceRegistration moduleControl;
private ServiceRegistration cameraService;
private ServiceRegistration bepReg;
private LogService logService;
private Camera camera;
private String moduleId;
private String regionKey;
private static boolean icon[][] = { { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, true, true, true, true, true, true, true, true, true, true, true, true, false, false },
{ false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, false },
{ false, true, false, false, false, false, false, false, false, false, false, true, true, false, true, false },
{ false, true, false, false, true, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, false, false, false, false, false, false, true, false, true, false },
{ false, true, false, true, false, false, false, false, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, true, true, false, true, true, true, true, false, true, false },
{ false, true, false, true, false, false, true, true, false, true, true, true, true, false, true, false },
{ false, true, false, true, false, true, false, false, true, true, true, true, true, false, true, false },
{ false, true, false, true, false, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, true, true, true, true, true, true, true, true, true, true, false, true, false },
{ false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, false },
{ false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false },
{ false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false } };
private CameraModuleControl cameraControl;
private ServiceRegistration cameraControlRef;
private CameraControl cc;
private InputEventProvider bep;
public CameraModlet(BundleContext context, int slotId, String moduleId) {
this.context = context;
this.slotId = slotId;
this.moduleId = moduleId;
this.moduleName = "CAMERA";
// TODO See if we can get this from the Camera driver.
this.megapixels = 2;
}
public String getModuleId() {
return moduleId;
}
public int getSlotId() {
return slotId;
}
public void setup() throws Exception {
logService = LogServiceUtil.getLogService(context);
}
public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
- regionKey = StatusBarUtils.displayImage(context, icon);
+ regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName());
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
/**
* @return A dictionary with R-OSGi enable property.
*/
private Dictionary createRemotableProperties(Dictionary ht) {
if (ht == null) {
ht = new Hashtable();
}
ht.put(RemoteOSGiServiceConstants.R_OSGi_REGISTRATION, "true");
return ht;
}
public void stop() throws Exception {
StatusBarUtils.releaseRegion(context, regionKey);
cameraControlRef.unregister();
cameraService.unregister();
moduleControl.unregister();
bep.tearDown();
bepReg.unregister();
wsTracker.close();
camera.close();
cc.close();
}
/**
* @return a dictionary of properties for the IButtonEventProvider service.
*/
private Dictionary getButtonServiceProperties() {
Dictionary props = new Hashtable();
props.put("ButtonEventProvider", this.getClass().getName());
props.put("ButtonsProvided", "Camera");
return props;
}
public PublicWSDefinition discover(int operation) {
if (operation == PublicWSProvider.GET) {
return new PublicWSDefinition() {
public List getParameters() {
return null;
}
public String getReturnType() {
return IMAGE_MIME_TYPE;
}
};
}
return null;
}
public IWSResponse execute(int operation, String input) {
if (operation == PublicWSProvider.GET) {
return new WSResponse(getImageInputStream(), IMAGE_MIME_TYPE);
}
return null;
}
public String getPublicName() {
return "Picture";
}
public List getModuleProperties() {
modProps.clear();
//Removing...this information needs to come from the device.
//modProps.add(new ModuleProperty("MP", "" + megapixels, "Number", false));
modProps.add(new ModuleProperty("Slot", "" + slotId));
return modProps;
}
public String getModuleName() {
return moduleName;
}
public boolean setModuleProperty(IModuleProperty property) {
return false;
}
public byte[] getImage() {
return camera.grabFrame();
}
public boolean initOverlay(Rectangle pbounds){
if (camera.overlayinit(pbounds.x, pbounds.y, pbounds.width, pbounds.height) < 0)
return false;
else
return true;
}
public boolean startOverlay(){
if (camera.overlaystart() < 0)
return false;
else
return true;
}
public boolean stopOverlay(){
if (camera.overlaystop() < 0)
return false;
else
return true;
}
public InputStream getImageInputStream() {
return new ByteArrayInputStream(camera.grabFrame());
}
public String getFormat() {
return IMAGE_MIME_TYPE;
}
public String getDescription() {
return "This service can return image data from a hardware camera.";
}
}
| true | true | public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
regionKey = StatusBarUtils.displayImage(context, icon);
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
| public void start() throws Exception {
modProps = new ArrayList();
camera = new Camera();
//TODO: Change this when we move to linux 2.6.22 or greater since
//BMI agent should listen to UDEV ACTION=="online" before starting modlets
try {
CharDeviceUtils.openDeviceWithRetry(camera, CAMERA_DEVICE_NODE, 2);
} catch (IOException e) {
String errormsg = "Unable to open camera device node: " + CAMERA_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cc = new CameraControl();
try {
CharDeviceUtils.openDeviceWithRetry(cc, CAMERA_CONTROL_DEVICE_NODE, 2);
} catch (IOException e){
String errormsg = "Unable to open camera device node: " + CAMERA_CONTROL_DEVICE_NODE +
"\n trying again...";
logService.log(LogService.LOG_ERROR, errormsg);
throw e;
}
cameraControl = new CameraModuleControl(cc);
cameraControlRef = context.registerService(ICameraModuleControl.class.getName(), cameraControl, createRemotableProperties(null));
moduleControl = context.registerService(IModuleControl.class.getName(), this, createRemotableProperties(null));
cameraService = context.registerService(ICameraDevice.class.getName(), this, createRemotableProperties(null));
bep = new CameraInputEventProvider(DEVNODE_INPUT_DEVICE, logService);
bep.start();
bepReg = context.registerService(ICameraButtonEventProvider.class.getName(), bep, createRemotableProperties(getButtonServiceProperties()));
// Display the camera icon
regionKey = StatusBarUtils.displayImage(context, icon, this.getModuleName());
List wsProviders = new ArrayList();
wsProviders.add(this);
wsTracker = PublicWSAdminTracker.createTracker(context, wsProviders);
}
|
diff --git a/src/server/src/main/java/org/apache/accumulo/server/logger/LogWriter.java b/src/server/src/main/java/org/apache/accumulo/server/logger/LogWriter.java
index a8bc87c5d..53104ef2b 100644
--- a/src/server/src/main/java/org/apache/accumulo/server/logger/LogWriter.java
+++ b/src/server/src/main/java/org/apache/accumulo/server/logger/LogWriter.java
@@ -1,624 +1,624 @@
/*
* 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.accumulo.server.logger;
import static org.apache.accumulo.server.logger.LogEvents.COMPACTION_FINISH;
import static org.apache.accumulo.server.logger.LogEvents.COMPACTION_START;
import static org.apache.accumulo.server.logger.LogEvents.DEFINE_TABLET;
import static org.apache.accumulo.server.logger.LogEvents.MANY_MUTATIONS;
import static org.apache.accumulo.server.logger.LogEvents.MUTATION;
import static org.apache.accumulo.server.logger.LogEvents.OPEN;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.accumulo.cloudtrace.instrument.Span;
import org.apache.accumulo.cloudtrace.instrument.Trace;
import org.apache.accumulo.cloudtrace.thrift.TInfo;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.thrift.TKeyExtent;
import org.apache.accumulo.core.data.thrift.TMutation;
import org.apache.accumulo.core.security.thrift.AuthInfo;
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
import org.apache.accumulo.core.tabletserver.thrift.LogCopyInfo;
import org.apache.accumulo.core.tabletserver.thrift.LogFile;
import org.apache.accumulo.core.tabletserver.thrift.MutationLogger;
import org.apache.accumulo.core.tabletserver.thrift.NoSuchLogIDException;
import org.apache.accumulo.core.tabletserver.thrift.TabletMutations;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.server.logger.metrics.LogWriterMetrics;
import org.apache.accumulo.server.trace.TraceFileSystem;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Metadata;
import org.apache.hadoop.io.SequenceFile.Reader;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.WritableName;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.thrift.TException;
/**
* Write log operations to open {@link org.apache.hadoop.io.SequenceFile}s referenced by log id's.
*/
class LogWriter implements MutationLogger.Iface {
static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogWriter.class);
static {
WritableName.setName(LogFileKey.class, Constants.OLD_PACKAGE_NAME + ".server.logger.LogFileKey");
WritableName.setName(LogFileValue.class, Constants.OLD_PACKAGE_NAME + ".server.logger.LogFileValue");
}
static class LogWriteException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public LogWriteException(Throwable why) {
super(why);
}
}
/**
* Generate log ids.
*/
private static final SecureRandom random = new SecureRandom();
private final FileSystem fs;
private final ExecutorService copyThreadPool;
private final static Mutation empty[] = new Mutation[0];
private boolean closed = false;
private static class Logger {
SequenceFile.Writer seq;
FSDataOutputStream out;
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
Logger(Configuration conf, String path) throws IOException {
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(conf).getRaw());
out = local.create(new Path(path));
seq = SequenceFile.createWriter(conf, out, LogFileKey.class, LogFileValue.class, CompressionType.NONE, null);
}
void logEntry() throws IOException {
try {
long t1 = System.currentTimeMillis();
seq.append(key, value);
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.logAppend, (t2 - t1));
out.flush();
long t3 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.logFlush, (t3 - t2));
} catch (IOException ioe) {
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.logException, 0);
throw ioe;
}
}
void close() throws IOException {
seq.close();
out.close();
}
}
/**
* The current loggers in use.
*/
private Map<Long,Logger> logs = new ConcurrentHashMap<Long,Logger>();
/**
* Map from filename to open log id.
*/
private Map<String,Long> file2id = new ConcurrentHashMap<String,Long>();
/**
* Local directory where logs are created.
*/
private final List<String> roots;
private int nextRoot = 0;
private final String instanceId;
private LogArchiver logArchiver;
// Metrics MBean
private static LogWriterMetrics metrics = new LogWriterMetrics();
private final AccumuloConfiguration acuConf;
/**
*
* @param fs
* The HDFS instance shared by master/tservers.
* @param logDirectories
* The local directories to write the recovery logs.
* @param instanceId
* The accumulo instance for which we are logging.
*/
public LogWriter(AccumuloConfiguration acuConf, FileSystem fs, Collection<String> logDirectories, String instanceId, int threadPoolSize, boolean archive) {
this.acuConf = acuConf;
this.fs = fs;
this.roots = new ArrayList<String>(logDirectories);
this.instanceId = instanceId;
this.copyThreadPool = Executors.newFixedThreadPool(threadPoolSize);
try {
this.logArchiver = new LogArchiver(acuConf, TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf())), fs, new ArrayList<String>(logDirectories), archive);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
// Register the metrics MBean
try {
metrics.register();
} catch (Exception e) {
log.error("Exception registering MBean with MBean Server", e);
}
}
@Override
synchronized public void close(TInfo info, long id) throws NoSuchLogIDException {
long t1 = System.currentTimeMillis();
synchronized (logs) {
Logger out = logs.remove(id);
if (out == null) {
throw new NoSuchLogIDException();
}
try {
out.close();
} catch (IOException ex) {
log.error("IOException occurred closing file", ex);
}
// Iterative search: this is ok if the number of open files is small
for (Entry<String,Long> entry : file2id.entrySet()) {
if (entry.getValue().equals(id)) {
file2id.remove(entry.getKey());
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.close, (t2 - t1));
return;
}
}
}
throw new RuntimeException("Unexpected failure to find a filename matching an id");
}
private final String findLocalFilename(String localLog) throws FileNotFoundException {
for (String root : roots) {
String path = root + "/" + localLog;
if (new File(path).exists())
return path;
}
throw new FileNotFoundException("No file " + localLog + " found in " + roots);
}
@Override
public LogCopyInfo startCopy(TInfo info, AuthInfo credentials, final String localLog, final String fullyQualifiedFileName, final boolean sort) {
log.info("Copying " + localLog + " to " + fullyQualifiedFileName);
final long t1 = System.currentTimeMillis();
try {
Long id = file2id.get(localLog);
if (id != null)
close(info, id);
} catch (NoSuchLogIDException e) {
log.error("Unexpected error thrown", e);
throw new RuntimeException(e);
}
File file;
try {
file = new File(findLocalFilename(localLog));
log.info(file.getAbsoluteFile().toString());
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
long result = file.length();
copyThreadPool.execute(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Copying " + localLog + " to shared file system");
for (int i = 0; i < 3; i++) {
try {
if (sort) {
copySortLog(localLog, fullyQualifiedFileName);
} else {
copyLog(localLog, fullyQualifiedFileName);
}
return;
} catch (IOException e) {
log.error("error during copy", e);
}
UtilWaitThread.sleep(1000);
}
log.error("Unable to copy file to DFS, too many retries " + localLog);
try {
fs.create(new Path(fullyQualifiedFileName + ".failed")).close();
} catch (IOException ex) {
log.error("Unable to create failure flag file", ex);
}
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.copy, (t2 - t1));
}
private void copySortLog(String localLog, String fullyQualifiedFileName) throws IOException {
final long SORT_BUFFER_SIZE = acuConf.getMemoryInBytes(Property.LOGGER_SORT_BUFFER_SIZE);
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
Path dest = new Path(fullyQualifiedFileName + ".recovered");
- log.debug("Sorting log file to DSF " + dest);
+ log.debug("Sorting log file to DFS " + dest);
fs.mkdirs(dest);
int part = 0;
Reader reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
try {
final ArrayList<Pair<LogFileKey,LogFileValue>> kv = new ArrayList<Pair<LogFileKey,LogFileValue>>();
long memorySize = 0;
while (true) {
final long position = reader.getPosition();
final LogFileKey key = new LogFileKey();
final LogFileValue value = new LogFileValue();
try {
if (!reader.next(key, value))
break;
} catch (EOFException e) {
log.warn("Unexpected end of file reading write ahead log " + localLog);
break;
}
kv.add(new Pair<LogFileKey,LogFileValue>(key, value));
memorySize += reader.getPosition() - position;
if (memorySize > SORT_BUFFER_SIZE) {
writeSortedEntries(dest, part++, kv);
kv.clear();
memorySize = 0;
}
}
if (!kv.isEmpty())
writeSortedEntries(dest, part++, kv);
fs.create(new Path(dest, "finished")).close();
} finally {
reader.close();
}
}
private void writeSortedEntries(Path dest, int part, final List<Pair<LogFileKey,LogFileValue>> kv) throws IOException {
String path = dest + String.format("/part-r-%05d", part);
- log.debug("Writing partial log file to DSF " + path);
+ log.debug("Writing partial log file to DFS " + path);
log.debug("Sorting");
Span span = Trace.start("Logger sort");
span.data("logfile", dest.getName());
Collections.sort(kv, new Comparator<Pair<LogFileKey,LogFileValue>>() {
@Override
public int compare(Pair<LogFileKey,LogFileValue> o1, Pair<LogFileKey,LogFileValue> o2) {
return o1.getFirst().compareTo(o2.getFirst());
}
});
span.stop();
span = Trace.start("Logger write");
span.data("logfile", dest.getName());
MapFile.Writer writer = new MapFile.Writer(fs.getConf(), fs, path, LogFileKey.class, LogFileValue.class);
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
fs.setReplication(new Path(path + "/" + MapFile.DATA_FILE_NAME), replication);
fs.setReplication(new Path(path + "/" + MapFile.INDEX_FILE_NAME), replication);
try {
for (Pair<LogFileKey,LogFileValue> entry : kv)
writer.append(entry.getFirst(), entry.getSecond());
} finally {
writer.close();
span.stop();
}
}
private void copyLog(final String localLog, final String fullyQualifiedFileName) throws IOException {
Path dest = new Path(fullyQualifiedFileName + ".copy");
- log.debug("Copying log file to DSF " + dest);
+ log.debug("Copying log file to DFS " + dest);
fs.delete(dest, true);
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
Writer writer = null;
Reader reader = null;
try {
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
writer = SequenceFile.createWriter(fs, fs.getConf(), dest, LogFileKey.class, LogFileValue.class, fs.getConf().getInt("io.file.buffer.size", 4096),
replication, fs.getDefaultBlockSize(), SequenceFile.CompressionType.BLOCK, new DefaultCodec(), null, new Metadata());
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
while (reader.next(key, value)) {
writer.append(key, value);
}
} catch (IOException ex) {
log.warn("May have a partial copy of a recovery file: " + localLog, ex);
} finally {
if (reader != null)
reader.close();
if (writer != null)
writer.close();
}
// Make file appear in the shared file system as the target name only after it is completely copied
fs.rename(dest, new Path(fullyQualifiedFileName));
log.info("Copying " + localLog + " complete");
}
});
return new LogCopyInfo(result, null);
}
@Override
public LogFile create(TInfo info, AuthInfo credentials, String tserverSession) throws ThriftSecurityException {
if (closed)
throw new RuntimeException("Logger is closed");
long t1 = System.currentTimeMillis();
LogFile result = new LogFile();
result.id = random.nextLong();
while (logs.get(result.id) != null)
result.id = random.nextLong();
result.name = UUID.randomUUID().toString();
Logger out = null;
try {
out = new Logger(fs.getConf(), roots.get(nextRoot++ % roots.size()) + "/" + result.name);
out.key.event = OPEN;
out.key.tserverSession = tserverSession;
out.key.filename = instanceId;
out.value.mutations = empty;
out.logEntry();
logs.put(result.id, out);
file2id.put(result.name, result.id);
} catch (Throwable e) {
if (out != null) {
try {
out.close();
} catch (Throwable t) {
log.error("Error closing file", t);
}
}
log.error("Unable to create log " + result.name);
throw new RuntimeException(e);
}
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.create, (t2 - t1));
log.info("Created log " + result.name);
return result;
}
@Override
public void log(TInfo info, long id, final long seq, final int tid, final TMutation mutation) throws NoSuchLogIDException {
Logger out = logs.get(id);
if (out == null)
throw new NoSuchLogIDException();
out.key.event = MUTATION;
out.key.seq = seq;
out.key.tid = tid;
out.value.mutations = new Mutation[1];
out.value.mutations[0] = new Mutation(mutation);
try {
out.logEntry();
} catch (Throwable e) {
log.error("log failure, closing log", e);
try {
close(info, id);
} catch (Throwable t) {
log.error("failure closing log", t);
}
throw new LogWriteException(e);
}
}
private void logMany(TInfo info, long id, final long seq, final int tid, Mutation muations[]) throws NoSuchLogIDException {
Logger out = logs.get(id);
if (out == null)
throw new NoSuchLogIDException();
out.key.event = MANY_MUTATIONS;
out.key.seq = seq;
out.key.tid = tid;
out.value.mutations = muations;
try {
out.logEntry();
} catch (Throwable e) {
log.error("log failure, closing log", e);
try {
close(info, id);
} catch (Throwable t) {
log.error("failure closing log", t);
}
throw new LogWriteException(e);
}
}
@Override
public void minorCompactionFinished(TInfo info, long id, final long seq, final int tid, final String fqfn) throws NoSuchLogIDException {
Logger out = logs.get(id);
if (out == null)
throw new NoSuchLogIDException();
out.key.event = COMPACTION_FINISH;
out.key.seq = seq;
out.key.tid = tid;
out.value.mutations = empty;
// this lock should not be necessary since there should only be one writer
try {
out.logEntry();
} catch (Throwable e) {
log.error("log failure, closing log", e);
try {
close(info, id);
} catch (Throwable t) {
log.error("failure closing log", t);
}
throw new LogWriteException(e);
}
}
@Override
public void minorCompactionStarted(TInfo info, long id, final long seq, final int tid, final String fqfn) throws NoSuchLogIDException {
Logger out = logs.get(id);
if (out == null)
throw new NoSuchLogIDException();
out.key.event = COMPACTION_START;
out.key.seq = seq;
out.key.tid = tid;
out.key.filename = fqfn;
out.value.mutations = empty;
try {
out.logEntry();
} catch (Throwable e) {
log.error("log failure, closing log", e);
try {
close(info, id);
} catch (Throwable t) {
log.error("failure closing log", t);
}
throw new LogWriteException(e);
}
}
@Override
public void defineTablet(TInfo info, long id, final long seq, final int tid, final TKeyExtent tablet) throws NoSuchLogIDException {
Logger out = logs.get(id);
if (out == null)
throw new NoSuchLogIDException();
out.key.event = DEFINE_TABLET;
out.key.seq = seq;
out.key.tid = tid;
out.key.tablet = new KeyExtent(tablet);
out.value.mutations = empty;
try {
out.logEntry();
} catch (Throwable e) {
log.error("log failure, closing log", e);
try {
close(info, id);
} catch (Throwable t) {
log.error("failure closing log", t);
}
throw new LogWriteException(e);
}
}
public void shutdown() {
// Make sure everything is closed
log.info("Shutting down");
List<Long> ids = new ArrayList<Long>();
ids.addAll(logs.keySet());
for (long id : ids) {
try {
close(null, id);
} catch (Throwable t) {
log.warn("Shutdown close exception:", t);
}
}
}
@Override
public List<String> getClosedLogs(TInfo info, AuthInfo credentials) throws ThriftSecurityException {
ArrayList<String> result = new ArrayList<String>();
for (String root : roots) {
for (File file : new File(root).listFiles()) {
// skip dot-files
if (file.getName().indexOf('.') >= 0)
continue;
// skip open logs
if (file2id.containsKey(file.getName()))
continue;
if (LogArchiver.isArchive(file.getName()))
continue;
try {
UUID.fromString(file.getName());
result.add(file.getName());
} catch (IllegalArgumentException ex) {
log.debug("Ignoring file " + file.getName());
}
}
}
return result;
}
@Override
public void remove(TInfo info, AuthInfo credentials, List<String> files) {
log.info("Deleting " + files.size() + " log files");
try {
for (String file : files) {
if (file2id.get(file) != null) {
log.warn("ignoring attempt to delete open file " + file);
} else {
logArchiver.archive(this.findLocalFilename(file));
}
}
} catch (IOException ex) {
log.error("Unable to delete files", ex);
}
}
@Override
public void logManyTablets(TInfo info, long id, List<TabletMutations> mutations) throws NoSuchLogIDException {
for (TabletMutations tm : mutations) {
Mutation ma[] = new Mutation[tm.mutations.size()];
int index = 0;
for (TMutation tmut : tm.mutations)
ma[index++] = new Mutation(tmut);
logMany(info, id, tm.seq, tm.tabletID, ma);
}
}
@Override
synchronized public void beginShutdown(TInfo tinfo, AuthInfo credentials) throws TException {
closed = true;
synchronized (logs) {
for (Logger out : logs.values()) {
try {
out.close();
} catch (IOException ex) {
log.error("IOException occurred closing file", ex);
}
}
logs.clear();
file2id.clear();
}
}
@Override
public void halt(TInfo tinfo, AuthInfo credentials) throws TException {}
}
| false | true | public LogCopyInfo startCopy(TInfo info, AuthInfo credentials, final String localLog, final String fullyQualifiedFileName, final boolean sort) {
log.info("Copying " + localLog + " to " + fullyQualifiedFileName);
final long t1 = System.currentTimeMillis();
try {
Long id = file2id.get(localLog);
if (id != null)
close(info, id);
} catch (NoSuchLogIDException e) {
log.error("Unexpected error thrown", e);
throw new RuntimeException(e);
}
File file;
try {
file = new File(findLocalFilename(localLog));
log.info(file.getAbsoluteFile().toString());
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
long result = file.length();
copyThreadPool.execute(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Copying " + localLog + " to shared file system");
for (int i = 0; i < 3; i++) {
try {
if (sort) {
copySortLog(localLog, fullyQualifiedFileName);
} else {
copyLog(localLog, fullyQualifiedFileName);
}
return;
} catch (IOException e) {
log.error("error during copy", e);
}
UtilWaitThread.sleep(1000);
}
log.error("Unable to copy file to DFS, too many retries " + localLog);
try {
fs.create(new Path(fullyQualifiedFileName + ".failed")).close();
} catch (IOException ex) {
log.error("Unable to create failure flag file", ex);
}
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.copy, (t2 - t1));
}
private void copySortLog(String localLog, String fullyQualifiedFileName) throws IOException {
final long SORT_BUFFER_SIZE = acuConf.getMemoryInBytes(Property.LOGGER_SORT_BUFFER_SIZE);
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
Path dest = new Path(fullyQualifiedFileName + ".recovered");
log.debug("Sorting log file to DSF " + dest);
fs.mkdirs(dest);
int part = 0;
Reader reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
try {
final ArrayList<Pair<LogFileKey,LogFileValue>> kv = new ArrayList<Pair<LogFileKey,LogFileValue>>();
long memorySize = 0;
while (true) {
final long position = reader.getPosition();
final LogFileKey key = new LogFileKey();
final LogFileValue value = new LogFileValue();
try {
if (!reader.next(key, value))
break;
} catch (EOFException e) {
log.warn("Unexpected end of file reading write ahead log " + localLog);
break;
}
kv.add(new Pair<LogFileKey,LogFileValue>(key, value));
memorySize += reader.getPosition() - position;
if (memorySize > SORT_BUFFER_SIZE) {
writeSortedEntries(dest, part++, kv);
kv.clear();
memorySize = 0;
}
}
if (!kv.isEmpty())
writeSortedEntries(dest, part++, kv);
fs.create(new Path(dest, "finished")).close();
} finally {
reader.close();
}
}
private void writeSortedEntries(Path dest, int part, final List<Pair<LogFileKey,LogFileValue>> kv) throws IOException {
String path = dest + String.format("/part-r-%05d", part);
log.debug("Writing partial log file to DSF " + path);
log.debug("Sorting");
Span span = Trace.start("Logger sort");
span.data("logfile", dest.getName());
Collections.sort(kv, new Comparator<Pair<LogFileKey,LogFileValue>>() {
@Override
public int compare(Pair<LogFileKey,LogFileValue> o1, Pair<LogFileKey,LogFileValue> o2) {
return o1.getFirst().compareTo(o2.getFirst());
}
});
span.stop();
span = Trace.start("Logger write");
span.data("logfile", dest.getName());
MapFile.Writer writer = new MapFile.Writer(fs.getConf(), fs, path, LogFileKey.class, LogFileValue.class);
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
fs.setReplication(new Path(path + "/" + MapFile.DATA_FILE_NAME), replication);
fs.setReplication(new Path(path + "/" + MapFile.INDEX_FILE_NAME), replication);
try {
for (Pair<LogFileKey,LogFileValue> entry : kv)
writer.append(entry.getFirst(), entry.getSecond());
} finally {
writer.close();
span.stop();
}
}
private void copyLog(final String localLog, final String fullyQualifiedFileName) throws IOException {
Path dest = new Path(fullyQualifiedFileName + ".copy");
log.debug("Copying log file to DSF " + dest);
fs.delete(dest, true);
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
Writer writer = null;
Reader reader = null;
try {
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
writer = SequenceFile.createWriter(fs, fs.getConf(), dest, LogFileKey.class, LogFileValue.class, fs.getConf().getInt("io.file.buffer.size", 4096),
replication, fs.getDefaultBlockSize(), SequenceFile.CompressionType.BLOCK, new DefaultCodec(), null, new Metadata());
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
while (reader.next(key, value)) {
writer.append(key, value);
}
} catch (IOException ex) {
log.warn("May have a partial copy of a recovery file: " + localLog, ex);
} finally {
if (reader != null)
reader.close();
if (writer != null)
writer.close();
}
// Make file appear in the shared file system as the target name only after it is completely copied
fs.rename(dest, new Path(fullyQualifiedFileName));
log.info("Copying " + localLog + " complete");
}
});
return new LogCopyInfo(result, null);
}
| public LogCopyInfo startCopy(TInfo info, AuthInfo credentials, final String localLog, final String fullyQualifiedFileName, final boolean sort) {
log.info("Copying " + localLog + " to " + fullyQualifiedFileName);
final long t1 = System.currentTimeMillis();
try {
Long id = file2id.get(localLog);
if (id != null)
close(info, id);
} catch (NoSuchLogIDException e) {
log.error("Unexpected error thrown", e);
throw new RuntimeException(e);
}
File file;
try {
file = new File(findLocalFilename(localLog));
log.info(file.getAbsoluteFile().toString());
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
long result = file.length();
copyThreadPool.execute(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Copying " + localLog + " to shared file system");
for (int i = 0; i < 3; i++) {
try {
if (sort) {
copySortLog(localLog, fullyQualifiedFileName);
} else {
copyLog(localLog, fullyQualifiedFileName);
}
return;
} catch (IOException e) {
log.error("error during copy", e);
}
UtilWaitThread.sleep(1000);
}
log.error("Unable to copy file to DFS, too many retries " + localLog);
try {
fs.create(new Path(fullyQualifiedFileName + ".failed")).close();
} catch (IOException ex) {
log.error("Unable to create failure flag file", ex);
}
long t2 = System.currentTimeMillis();
if (metrics.isEnabled())
metrics.add(LogWriterMetrics.copy, (t2 - t1));
}
private void copySortLog(String localLog, String fullyQualifiedFileName) throws IOException {
final long SORT_BUFFER_SIZE = acuConf.getMemoryInBytes(Property.LOGGER_SORT_BUFFER_SIZE);
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
Path dest = new Path(fullyQualifiedFileName + ".recovered");
log.debug("Sorting log file to DFS " + dest);
fs.mkdirs(dest);
int part = 0;
Reader reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
try {
final ArrayList<Pair<LogFileKey,LogFileValue>> kv = new ArrayList<Pair<LogFileKey,LogFileValue>>();
long memorySize = 0;
while (true) {
final long position = reader.getPosition();
final LogFileKey key = new LogFileKey();
final LogFileValue value = new LogFileValue();
try {
if (!reader.next(key, value))
break;
} catch (EOFException e) {
log.warn("Unexpected end of file reading write ahead log " + localLog);
break;
}
kv.add(new Pair<LogFileKey,LogFileValue>(key, value));
memorySize += reader.getPosition() - position;
if (memorySize > SORT_BUFFER_SIZE) {
writeSortedEntries(dest, part++, kv);
kv.clear();
memorySize = 0;
}
}
if (!kv.isEmpty())
writeSortedEntries(dest, part++, kv);
fs.create(new Path(dest, "finished")).close();
} finally {
reader.close();
}
}
private void writeSortedEntries(Path dest, int part, final List<Pair<LogFileKey,LogFileValue>> kv) throws IOException {
String path = dest + String.format("/part-r-%05d", part);
log.debug("Writing partial log file to DFS " + path);
log.debug("Sorting");
Span span = Trace.start("Logger sort");
span.data("logfile", dest.getName());
Collections.sort(kv, new Comparator<Pair<LogFileKey,LogFileValue>>() {
@Override
public int compare(Pair<LogFileKey,LogFileValue> o1, Pair<LogFileKey,LogFileValue> o2) {
return o1.getFirst().compareTo(o2.getFirst());
}
});
span.stop();
span = Trace.start("Logger write");
span.data("logfile", dest.getName());
MapFile.Writer writer = new MapFile.Writer(fs.getConf(), fs, path, LogFileKey.class, LogFileValue.class);
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
fs.setReplication(new Path(path + "/" + MapFile.DATA_FILE_NAME), replication);
fs.setReplication(new Path(path + "/" + MapFile.INDEX_FILE_NAME), replication);
try {
for (Pair<LogFileKey,LogFileValue> entry : kv)
writer.append(entry.getFirst(), entry.getSecond());
} finally {
writer.close();
span.stop();
}
}
private void copyLog(final String localLog, final String fullyQualifiedFileName) throws IOException {
Path dest = new Path(fullyQualifiedFileName + ".copy");
log.debug("Copying log file to DFS " + dest);
fs.delete(dest, true);
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
Writer writer = null;
Reader reader = null;
try {
short replication = (short) acuConf.getCount(Property.LOGGER_RECOVERY_FILE_REPLICATION);
writer = SequenceFile.createWriter(fs, fs.getConf(), dest, LogFileKey.class, LogFileValue.class, fs.getConf().getInt("io.file.buffer.size", 4096),
replication, fs.getDefaultBlockSize(), SequenceFile.CompressionType.BLOCK, new DefaultCodec(), null, new Metadata());
FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(fs.getConf()).getRaw());
reader = new SequenceFile.Reader(local, new Path(findLocalFilename(localLog)), fs.getConf());
while (reader.next(key, value)) {
writer.append(key, value);
}
} catch (IOException ex) {
log.warn("May have a partial copy of a recovery file: " + localLog, ex);
} finally {
if (reader != null)
reader.close();
if (writer != null)
writer.close();
}
// Make file appear in the shared file system as the target name only after it is completely copied
fs.rename(dest, new Path(fullyQualifiedFileName));
log.info("Copying " + localLog + " complete");
}
});
return new LogCopyInfo(result, null);
}
|
diff --git a/jason/asSyntax/Literal.java b/jason/asSyntax/Literal.java
index 841557c..816ba1a 100644
--- a/jason/asSyntax/Literal.java
+++ b/jason/asSyntax/Literal.java
@@ -1,360 +1,360 @@
// ----------------------------------------------------------------------------
// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
//
// This library 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 library 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 this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// To contact the authors:
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
//----------------------------------------------------------------------------
package jason.asSyntax;
import jason.JasonException;
import jason.asSemantics.Agent;
import jason.asSemantics.Unifier;
import jason.asSyntax.parser.as2j;
import java.io.StringReader;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* A Literal is a Pred with strong negation (~).
*/
public class Literal extends Pred implements LogicalFormula {
private static final long serialVersionUID = 1L;
public static final boolean LPos = true;
public static final boolean LNeg = false;
public static final Literal LTrue = new Literal("true");
public static final Literal LFalse = new Literal("false");
static private Logger logger = Logger.getLogger(Literal.class.getName());
private boolean type = LPos;
/** creates a positive literal */
public Literal(String functor) {
super(functor);
}
/** if pos == true, the literal is positive, otherwise it is negative */
public Literal(boolean pos, String functor) {
super(functor);
type = pos;
}
/** if pos == true, the literal is positive, otherwise it is negative */
public Literal(boolean pos, Pred p) {
super(p);
type = pos;
}
public Literal(Literal l) {
super((Pred) l);
type = l.type;
}
public static Literal parseLiteral(String sLiteral) {
as2j parser = new as2j(new StringReader(sLiteral));
try {
return parser.literal();
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
}
}
public boolean isInternalAction() {
return getFunctor() != null && getFunctor().indexOf('.') >= 0;
}
@Override
public boolean isLiteral() {
return true;
}
@Override
public boolean isAtom() {
return super.isAtom() && !negated();
}
public boolean negated() {
return (type == LNeg);
}
public void setNegated(boolean b) {
type = b;
hashCodeCache = null;
}
/**
* logCons checks whether one particular predicate
* is a log(ical)Cons(equence) of the belief base.
*
* Returns an iterator for all unifiers that are logCons.
*/
@SuppressWarnings("unchecked")
public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
if (isInternalAction()) {
try {
// clone terms array
Term[] current = getTermsArray();
Term[] clone = new Term[current.length];
for (int i=0; i<clone.length; i++) {
clone[i] = (Term)current[i].clone();
clone[i].apply(un);
}
// calls execute
Object oresult = ag.getIA(this).execute(ag.getTS(), un, clone);
if (oresult instanceof Boolean && (Boolean)oresult) {
return LogExpr.createUnifIterator(un);
} else if (oresult instanceof Iterator) {
return ((Iterator<Unifier>)oresult);
}
} catch (Exception e) {
logger.log(Level.SEVERE, getErrorMsg(ag) + ": " + e.getMessage(), e);
}
return LogExpr.EMPTY_UNIF_LIST.iterator(); // empty iterator for unifier
- } else if (this == LTrue) {
+ } else if (this.equals(LTrue)) {
return LogExpr.createUnifIterator(un);
- } else if (this == LFalse) {
+ } else if (this.equals(LFalse)) {
return LogExpr.EMPTY_UNIF_LIST.iterator();
} else {
final Iterator<Literal> il = ag.getBB().getRelevant(this);
if (il == null)
return LogExpr.EMPTY_UNIF_LIST.iterator();
return new Iterator<Unifier>() {
Unifier current = null;
Iterator<Unifier> ruleIt = null; // current rule solutions iterator
Rule rule; // current rule
public boolean hasNext() {
if (current == null)
get();
return current != null;
}
public Unifier next() {
if (current == null)
get();
Unifier a = current;
current = null; //get();
return a;
}
private void get() {
//logger.info("*"+Literal.this+" in get, ruleit = "+ruleIt);
current = null;
// try rule iterator
while (ruleIt != null && ruleIt.hasNext()) {
// unifies the rule head with the result of rule evaluation
Unifier ruleUn = ruleIt.next(); // evaluation result
Literal rhead = rule.headClone();
rhead.apply(ruleUn);
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, rhead)) {
current = unC;
return;
}
}
// try literal iterator
while (il.hasNext()) {
Literal b = il.next(); // b is the relevant entry in BB
if (b.isRule()) {
rule = (Rule)b;
// create a copy of this literal, ground it and
// make its vars annonym, it is
// used to define what will be the unifier used
// inside the rule.
// Only vars from rule head should get value in the
// unifier used inside the rule evaluation.
Literal h = (Literal)Literal.this.clone();
h.apply(un);
h.makeVarsAnnon();
Unifier ruleUn = new Unifier();
if (ruleUn.unifies(h, rule)) {
//logger.info("go "+h+" rule="+rule+" un="+ruleUn);
ruleIt = rule.getBody().logicalConsequence(ag,ruleUn);
//logger.info("ruleIt for "+h+" ="+ruleIt);
get();
//logger.info("ret from "+h+" get="+current+" - "+il.hasNext());
if (current != null) { // if it get a value
return;
}
}
} else {
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, b)) {
current = unC;
return;
}
}
}
}
public void remove() {
}
};
}
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (o instanceof Literal) {
final Literal l = (Literal) o;
return type == l.type && hashCode() == l.hashCode() && super.equals(l);
} else if (o instanceof Structure) {
return !negated() && super.equals(o);
}
return false;
}
public String getErrorMsg(Agent ag) {
String line = "";
if (getSrcLine() >= 0) {
line = ":"+getSrcLine();
}
String ia = "";
if (isInternalAction()) {
ia = " internal action";
}
return "Error in "+ia+"'"+this+"' ("+ ag.getASLSource() + line + ")";
}
@Override
public int compareTo(Term t) {
if (t.isLiteral()) {
Literal tl = (Literal)t;
if (!negated() && tl.negated()) {
return -1;
} if (negated() && !tl.negated()) {
return 1;
}
}
int c = super.compareTo(t);
if (c != 0)
return c;
return 0;
}
public Object clone() {
Literal c = new Literal(this);
c.predicateIndicatorCache = this.predicateIndicatorCache;
c.hashCodeCache = this.hashCodeCache;
return c;
}
@Override
protected int calcHashCode() {
int result = super.calcHashCode();
if (negated()) {
result += 3271;
}
return result;
}
/** return [~] super.getFunctorArity */
@Override
public PredicateIndicator getPredicateIndicator() {
if (predicateIndicatorCache == null) {
predicateIndicatorCache = new PredicateIndicator(((type == LPos) ? "" : "~")+getFunctor(),getTermsSize());
}
return predicateIndicatorCache;
}
/** returns this literal as a list [<functor>, <list of terms>, <list of annots>] */
public ListTerm getAsListOfTerms() {
ListTerm l = new ListTermImpl();
l.add(new Literal(type, getFunctor()));
ListTerm lt = new ListTermImpl();
if (getTerms() != null) {
lt.addAll(getTerms());
}
l.add(lt);
if (hasAnnot()) {
l.add((ListTerm)getAnnots().clone());
} else {
l.add(new ListTermImpl());
}
return l;
}
/** creates a literal from a list [<functor>, <list of terms>, <list of annots>] */
public static Literal newFromListOfTerms(ListTerm lt) throws JasonException {
try {
Iterator<Term> i = lt.iterator();
Term tfunctor = i.next();
boolean pos = Literal.LPos;
if (tfunctor.isLiteral() && ((Literal)tfunctor).negated()) {
pos = Literal.LNeg;
}
Literal l = new Literal(pos,((Structure)tfunctor).getFunctor());
if (i.hasNext()) {
l.setTerms((ListTerm)((ListTerm)i.next()).clone());
}
if (i.hasNext()) {
l.setAnnots((ListTerm)((ListTerm)i.next()).clone());
}
return l;
} catch (Exception e) {
throw new JasonException("Error creating literal from "+lt);
}
}
public String toString() {
if (type == LPos)
return super.toString();
else
return "~" + super.toString();
}
/** get as XML */
@Override
public Element getAsDOM(Document document) {
Element u = (Element) document.createElement("literal");
if (isInternalAction()) {
u.setAttribute("ia", isInternalAction()+"");
}
u.setAttribute("negated", negated()+"");
u.appendChild(super.getAsDOM(document));
return u;
}
}
| false | true | public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
if (isInternalAction()) {
try {
// clone terms array
Term[] current = getTermsArray();
Term[] clone = new Term[current.length];
for (int i=0; i<clone.length; i++) {
clone[i] = (Term)current[i].clone();
clone[i].apply(un);
}
// calls execute
Object oresult = ag.getIA(this).execute(ag.getTS(), un, clone);
if (oresult instanceof Boolean && (Boolean)oresult) {
return LogExpr.createUnifIterator(un);
} else if (oresult instanceof Iterator) {
return ((Iterator<Unifier>)oresult);
}
} catch (Exception e) {
logger.log(Level.SEVERE, getErrorMsg(ag) + ": " + e.getMessage(), e);
}
return LogExpr.EMPTY_UNIF_LIST.iterator(); // empty iterator for unifier
} else if (this == LTrue) {
return LogExpr.createUnifIterator(un);
} else if (this == LFalse) {
return LogExpr.EMPTY_UNIF_LIST.iterator();
} else {
final Iterator<Literal> il = ag.getBB().getRelevant(this);
if (il == null)
return LogExpr.EMPTY_UNIF_LIST.iterator();
return new Iterator<Unifier>() {
Unifier current = null;
Iterator<Unifier> ruleIt = null; // current rule solutions iterator
Rule rule; // current rule
public boolean hasNext() {
if (current == null)
get();
return current != null;
}
public Unifier next() {
if (current == null)
get();
Unifier a = current;
current = null; //get();
return a;
}
private void get() {
//logger.info("*"+Literal.this+" in get, ruleit = "+ruleIt);
current = null;
// try rule iterator
while (ruleIt != null && ruleIt.hasNext()) {
// unifies the rule head with the result of rule evaluation
Unifier ruleUn = ruleIt.next(); // evaluation result
Literal rhead = rule.headClone();
rhead.apply(ruleUn);
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, rhead)) {
current = unC;
return;
}
}
// try literal iterator
while (il.hasNext()) {
Literal b = il.next(); // b is the relevant entry in BB
if (b.isRule()) {
rule = (Rule)b;
// create a copy of this literal, ground it and
// make its vars annonym, it is
// used to define what will be the unifier used
// inside the rule.
// Only vars from rule head should get value in the
// unifier used inside the rule evaluation.
Literal h = (Literal)Literal.this.clone();
h.apply(un);
h.makeVarsAnnon();
Unifier ruleUn = new Unifier();
if (ruleUn.unifies(h, rule)) {
//logger.info("go "+h+" rule="+rule+" un="+ruleUn);
ruleIt = rule.getBody().logicalConsequence(ag,ruleUn);
//logger.info("ruleIt for "+h+" ="+ruleIt);
get();
//logger.info("ret from "+h+" get="+current+" - "+il.hasNext());
if (current != null) { // if it get a value
return;
}
}
} else {
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, b)) {
current = unC;
return;
}
}
}
}
public void remove() {
}
};
}
}
| public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
if (isInternalAction()) {
try {
// clone terms array
Term[] current = getTermsArray();
Term[] clone = new Term[current.length];
for (int i=0; i<clone.length; i++) {
clone[i] = (Term)current[i].clone();
clone[i].apply(un);
}
// calls execute
Object oresult = ag.getIA(this).execute(ag.getTS(), un, clone);
if (oresult instanceof Boolean && (Boolean)oresult) {
return LogExpr.createUnifIterator(un);
} else if (oresult instanceof Iterator) {
return ((Iterator<Unifier>)oresult);
}
} catch (Exception e) {
logger.log(Level.SEVERE, getErrorMsg(ag) + ": " + e.getMessage(), e);
}
return LogExpr.EMPTY_UNIF_LIST.iterator(); // empty iterator for unifier
} else if (this.equals(LTrue)) {
return LogExpr.createUnifIterator(un);
} else if (this.equals(LFalse)) {
return LogExpr.EMPTY_UNIF_LIST.iterator();
} else {
final Iterator<Literal> il = ag.getBB().getRelevant(this);
if (il == null)
return LogExpr.EMPTY_UNIF_LIST.iterator();
return new Iterator<Unifier>() {
Unifier current = null;
Iterator<Unifier> ruleIt = null; // current rule solutions iterator
Rule rule; // current rule
public boolean hasNext() {
if (current == null)
get();
return current != null;
}
public Unifier next() {
if (current == null)
get();
Unifier a = current;
current = null; //get();
return a;
}
private void get() {
//logger.info("*"+Literal.this+" in get, ruleit = "+ruleIt);
current = null;
// try rule iterator
while (ruleIt != null && ruleIt.hasNext()) {
// unifies the rule head with the result of rule evaluation
Unifier ruleUn = ruleIt.next(); // evaluation result
Literal rhead = rule.headClone();
rhead.apply(ruleUn);
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, rhead)) {
current = unC;
return;
}
}
// try literal iterator
while (il.hasNext()) {
Literal b = il.next(); // b is the relevant entry in BB
if (b.isRule()) {
rule = (Rule)b;
// create a copy of this literal, ground it and
// make its vars annonym, it is
// used to define what will be the unifier used
// inside the rule.
// Only vars from rule head should get value in the
// unifier used inside the rule evaluation.
Literal h = (Literal)Literal.this.clone();
h.apply(un);
h.makeVarsAnnon();
Unifier ruleUn = new Unifier();
if (ruleUn.unifies(h, rule)) {
//logger.info("go "+h+" rule="+rule+" un="+ruleUn);
ruleIt = rule.getBody().logicalConsequence(ag,ruleUn);
//logger.info("ruleIt for "+h+" ="+ruleIt);
get();
//logger.info("ret from "+h+" get="+current+" - "+il.hasNext());
if (current != null) { // if it get a value
return;
}
}
} else {
Unifier unC = (Unifier) un.clone();
if (unC.unifies(Literal.this, b)) {
current = unC;
return;
}
}
}
}
public void remove() {
}
};
}
}
|
diff --git a/saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/QueryResource.java b/saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/QueryResource.java
index 298ff57a..6c1b3093 100644
--- a/saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/QueryResource.java
+++ b/saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/QueryResource.java
@@ -1,821 +1,819 @@
/*
* Copyright (C) 2011 Paul Stoellberger
*
* 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 of the License, or (at your option)
* any later version.
*
* 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 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.saiku.web.rest.resources;
import java.io.StringReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SaikuDimensionSelection;
import org.saiku.olap.dto.SaikuQuery;
import org.saiku.olap.dto.resultset.CellDataSet;
import org.saiku.service.olap.OlapDiscoverService;
import org.saiku.service.olap.OlapQueryService;
import org.saiku.service.util.exception.SaikuServiceException;
import org.saiku.web.rest.objects.MdxQueryObject;
import org.saiku.web.rest.objects.SavedQuery;
import org.saiku.web.rest.objects.SelectionRestObject;
import org.saiku.web.rest.objects.resultset.QueryResult;
import org.saiku.web.rest.util.RestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* QueryServlet contains all the methods required when manipulating an OLAP Query.
* @author Tom Barber
*
*/
@Component
@Path("/saiku/{username}/query")
@Scope("request")
@XmlAccessorType(XmlAccessType.NONE)
public class QueryResource {
private static final Logger log = LoggerFactory.getLogger(QueryResource.class);
private OlapQueryService olapQueryService;
private OlapDiscoverService olapDiscoverService;
@Autowired
public void setOlapQueryService(OlapQueryService olapqs) {
olapQueryService = olapqs;
}
@Autowired
public void setOlapDiscoverService(OlapDiscoverService olapds) {
olapDiscoverService = olapds;
}
/*
* Query methods
*/
/**
* Return a list of open queries.
*/
@GET
@Produces({"application/json" })
public List<String> getQueries() {
return olapQueryService.getQueries();
}
@GET
@Produces({"application/json" })
@Path("/{queryname}")
public SaikuQuery getQuery(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "\tGET");
}
return olapQueryService.getQuery(queryName);
}
/**
* Delete query from the query pool.
* @return a HTTP 410(Works) or HTTP 404(Call failed).
*/
@DELETE
@Path("/{queryname}")
public Status deleteQuery(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "\tDELETE");
}
try{
olapQueryService.deleteQuery(queryName);
return(Status.GONE);
}
catch(Exception e){
log.error("Cannot delete query (" + queryName + ")",e);
return(Status.NOT_FOUND);
}
}
/**
* Create a new Saiku Query.
* @param connectionName the name of the Saiku connection.
* @param cubeName the name of the cube.
* @param catalogName the catalog name.
* @param schemaName the name of the schema.
* @param queryName the name you want to assign to the query.
* @return
*
* @return a query model.
*
* @see
*/
@POST
@Produces({"application/json" })
@Path("/{queryname}")
public SaikuQuery createQuery(
@FormParam("connection") String connectionName,
@FormParam("cube") String cubeName,
@FormParam("catalog") String catalogName,
@FormParam("schema") String schemaName,
@FormParam("xml") @DefaultValue("") String xml,
@PathParam("queryname") String queryName) throws ServletException
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "\tPOST\t xml:" + (xml == null));
}
SaikuCube cube = new SaikuCube(connectionName, cubeName,cubeName, catalogName, schemaName);
if (xml != null && xml.length() > 0) {
return olapQueryService.createNewOlapQuery(queryName, xml);
}
return olapQueryService.createNewOlapQuery(queryName, cube);
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/properties")
public Properties getProperties(@PathParam("queryname") String queryName) {
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/properties\tGET");
}
return olapQueryService.getProperties(queryName);
}
@POST
@Produces({"application/json" })
@Path("/{queryname}/properties")
public Status setProperties(
@PathParam("queryname") String queryName,
@FormParam("properties") String properties)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/properties\tPOST");
}
try {
Properties props = new Properties();
System.out.print("PROPERTIES: " + properties);
StringReader sr = new StringReader(properties);
props.load(sr);
olapQueryService.setProperties(queryName, props);
return Status.OK;
} catch(Exception e) {
log.error("Cannot set properties for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@POST
@Produces({"application/json" })
@Path("/{queryname}/properties/{propertyKey}")
public Status setProperties(
@PathParam("queryname") String queryName,
@PathParam("propertyKey") String propertyKey,
@FormParam("propertyValue") String propertyValue)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/properties/"+ propertyKey + "\tPOST");
}
try{
Properties props = new Properties();
props.put(propertyKey, propertyValue);
olapQueryService.setProperties(queryName, props);
return Status.OK;
}catch(Exception e){
log.error("Cannot set property (" + propertyKey + " ) for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@GET
@Path("/{queryname}/mdx")
public MdxQueryObject getMDXQuery(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/mdx/\tGET");
}
try {
String mdx = olapQueryService.getMDXQuery(queryName);
return new MdxQueryObject(mdx);
}
catch (Exception e) {
log.error("Cannot get mdx for query (" + queryName + ")",e);
return null;
}
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/xml")
public SavedQuery getQueryXml(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/xml/\tGET");
}
try {
String xml = olapQueryService.getQueryXml(queryName);
return new SavedQuery(queryName, null, xml);
}
catch (Exception e) {
log.error("Cannot get xml for query (" + queryName + ")",e);
return null;
}
}
@GET
@Produces({"application/vnd.ms-excel" })
@Path("/{queryname}/export/xls")
public Response getQueryExcelExport(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/export/xls/\tGET");
}
return getQueryExcelExport(queryName, "hierarchical");
}
@GET
@Produces({"application/vnd.ms-excel" })
@Path("/{queryname}/export/xls/{format}")
public Response getQueryExcelExport(
@PathParam("queryname") String queryName,
@PathParam("format") @DefaultValue("HIERARCHICAL") String format){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/export/xls/"+format+"\tGET");
}
try {
byte[] doc = olapQueryService.getExport(queryName,"xls",format);
return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
"content-disposition",
"attachment; filename = saiku-export.xls").header(
"content-length",doc.length).build();
}
catch (Exception e) {
log.error("Cannot get excel for query (" + queryName + ")",e);
return Response.serverError().build();
}
}
@GET
@Produces({"text/csv" })
@Path("/{queryname}/export/csv")
public Response getQueryCsvExport(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/export/csv\tGET");
}
return getQueryCsvExport(queryName, "flat");
}
@GET
@Produces({"text/csv" })
@Path("/{queryname}/export/csv/{format}")
public Response getQueryCsvExport(
@PathParam("queryname") String queryName,
@PathParam("format") String format){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/export/csv/"+format+"\tGET");
}
try {
byte[] doc = olapQueryService.getExport(queryName,"csv",format);
return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
"content-disposition",
"attachment; filename = saiku-export.csv").header(
"content-length",doc.length).build();
}
catch (Exception e) {
log.error("Cannot get csv for query (" + queryName + ")",e);
return Response.serverError().build();
}
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/result")
public QueryResult execute(@PathParam("queryname") String queryName){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/result\tGET");
}
try {
CellDataSet cs = olapQueryService.execute(queryName);
return RestUtil.convert(cs);
}
catch (Exception e) {
log.error("Cannot execute query (" + queryName + ")",e);
String error = ExceptionUtils.getRootCauseMessage(e);
return new QueryResult(error);
}
}
@POST
@Produces({"application/json" })
@Path("/{queryname}/result")
public QueryResult executeMdx(
@PathParam("queryname") String queryName,
@FormParam("mdx") String mdx)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/result\tPOST\t"+mdx);
}
try {
olapQueryService.qm2mdx(queryName);
CellDataSet cs = olapQueryService.executeMdx(queryName,mdx);
return RestUtil.convert(cs);
}
catch (Exception e) {
log.error("Cannot execute query (" + queryName + ") using mdx:\n" + mdx,e);
String error = ExceptionUtils.getRootCauseMessage(e);
return new QueryResult(error);
}
}
@POST
@Produces({"application/json" })
@Path("/{queryname}/qm2mdx")
public SaikuQuery transformQm2Mdx(@PathParam("queryname") String queryName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/qm2mdx\tPOST\t");
}
try {
olapQueryService.qm2mdx(queryName);
return olapQueryService.getQuery(queryName);
}
catch (Exception e) {
log.error("Cannot transform Qm2Mdx query (" + queryName + ")",e);
}
return null;
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/drillthrough:{maxrows}")
public QueryResult execute(
@PathParam("queryname") String queryName,
@PathParam("maxrows") @DefaultValue("100") Integer maxrows)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/drillthrough\tGET");
}
QueryResult rsc;
ResultSet rs = null;
try {
Long start = (new Date()).getTime();
rs = olapQueryService.drilldown(queryName, maxrows);
rsc = RestUtil.convert(rs);
Long runtime = (new Date()).getTime()- start;
rsc.setRuntime(runtime.intValue());
}
catch (Exception e) {
log.error("Cannot execute query (" + queryName + ")",e);
String error = ExceptionUtils.getRootCauseMessage(e);
rsc = new QueryResult(error);
}
finally {
if (rs != null) {
try {
Statement statement = rs.getStatement();
statement.close();
rs.close();
} catch (SQLException e) {
throw new SaikuServiceException(e);
} finally {
rs = null;
}
}
}
return rsc;
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/result/{format}")
public QueryResult execute(
@PathParam("queryname") String queryName,
@PathParam("format") String formatter){
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/result"+formatter+"\tGET");
}
try {
CellDataSet cs = olapQueryService.execute(queryName,formatter);
return RestUtil.convert(cs);
}
catch (Exception e) {
log.error("Cannot execute query (" + queryName + ")",e);
String error = ExceptionUtils.getRootCauseMessage(e);
return new QueryResult(error);
}
}
/*
* Axis Methods.
*/
/**
* Return a list of dimensions for an axis in a query.
* @param queryName the name of the query.
* @param axisName the name of the axis.
* @return a list of available dimensions.
* @see DimensionRestPojo
*/
@GET
@Produces({"application/json" })
@Path("/{queryname}/axis/{axis}")
public List<SaikuDimensionSelection> getAxisInfo(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"\tGET");
}
return olapQueryService.getAxisSelection(queryName, axisName);
}
/**
* Remove all dimensions and selections on an axis
* @param queryName the name of the query.
* @param axisName the name of the axis.
*/
@DELETE
@Produces({"application/json" })
@Path("/{queryname}/axis/{axis}")
public void deleteAxis(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"\tDELETE");
}
olapQueryService.clearAxis(queryName, axisName);
}
@DELETE
@Produces({"application/json" })
@Path("/{queryname}/axis/")
public void clearAllAxisSelections(@PathParam("queryname") String queryName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis\tDELETE");
}
olapQueryService.resetQuery(queryName);
}
@PUT
@Produces({"application/json" })
@Path("/{queryname}/swapaxes")
public Status swapAxes(@PathParam("queryname") String queryName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/swapaxes\tPUT");
}
olapQueryService.swapAxes(queryName);
return Status.OK;
}
@GET
@Produces({"application/json" })
@Path("/{queryname}/cell/{position}/{value}")
public Status setCell(@PathParam("queryname") String queryName,
@PathParam("position") String position,
@PathParam("value") String value)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/cell/" + position+ "/" + value + "\tGET");
}
String[] positions = position.split(":");
List<Integer> cellPosition = new ArrayList<Integer>();
for (String p : positions) {
Integer pInt = Integer.parseInt(p);
cellPosition.add(pInt);
}
olapQueryService.setCellValue(queryName, cellPosition, value, null);
return Status.OK;
}
/*
* Dimension Methods
*/
/**
* Return a dimension and its selections for an axis in a query.
* @param queryName the name of the query.
* @param axis the name of the axis.
* @param dimension the name of the axis.
* @return a list of available dimensions.
* @see DimensionRestPojo
*/
@GET
@Produces({"application/json" })
@Path("/{queryname}/axis/{axis}/dimension/{dimension}")
public SaikuDimensionSelection getAxisDimensionInfo(
@PathParam("queryname") String queryName,
@PathParam("axis") String axis,
@PathParam("dimension") String dimension)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axis+"/dimension/"+dimension+"\tGET");
}
return olapQueryService.getAxisDimensionSelections(queryName, axis, dimension);
}
/**
* Move a dimension from one axis to another.
* @param queryName the name of the query.
* @param axisName the name of the axis.
* @param dimensionName the name of the dimension.
*
* @return HTTP 200 or HTTP 500.
*
* @see Status
*/
@POST
@Path("/{queryname}/axis/{axis}/dimension/{dimension}")
public Status moveDimension(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@FormParam("position") @DefaultValue("-1")int position)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tPOST");
}
try{
olapQueryService.moveDimension(queryName, axisName, dimensionName, position);
return Status.OK;
} catch(Exception e) {
log.error("Cannot move dimension "+ dimensionName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
/**
* Delete a dimension.
* @return
*/
@DELETE
@Path("/{queryname}/axis/{axis}/dimension/{dimension}")
public Status deleteDimension(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tDELETE");
}
try{
olapQueryService.removeDimension(queryName, axisName, dimensionName);
return Status.OK;
}catch(Exception e){
log.error("Cannot remove dimension "+ dimensionName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@PUT
@Consumes("application/x-www-form-urlencoded")
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/")
public Status updateSelections(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
- MultivaluedMap<String, String> formParams) {
+ @FormParam("selections") String selectionJSON) {
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tPUT");
}
try{
- if (formParams.containsKey("selections")) {
- LinkedList<String> sels = (LinkedList<String>) formParams.get("selections");
- String selectionJSON = (String) sels.getFirst();
+ if (selectionJSON != null) {
ObjectMapper mapper = new ObjectMapper();
List<SelectionRestObject> selections = mapper.readValue(selectionJSON, TypeFactory.collectionType(ArrayList.class, SelectionRestObject.class));
for (SelectionRestObject selection : selections) {
if (selection.getType() != null && "member".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename(), -1, -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename());
}
}
if (selection.getType() != null && "level".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename(), -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename());
}
}
}
return Status.OK;
}
} catch (Exception e){
log.error("Cannot updates selections for query (" + queryName + ")",e);
}
return Status.INTERNAL_SERVER_ERROR;
}
@DELETE
@Consumes("application/x-www-form-urlencoded")
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/member/")
public Status removeMembers(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
MultivaluedMap<String, String> formParams) {
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tPUT");
}
try{
if (formParams.containsKey("selections")) {
LinkedList<String> sels = (LinkedList<String>) formParams.get("selections");
String selectionJSON = (String) sels.getFirst();
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
List<SelectionRestObject> selections = mapper.readValue(selectionJSON, TypeFactory.collectionType(ArrayList.class, SelectionRestObject.class));
for (SelectionRestObject member : selections) {
removeMember("MEMBER", queryName, axisName, dimensionName, member.getUniquename());
}
return Status.OK;
}
} catch (Exception e){
log.error("Cannot updates selections for query (" + queryName + ")",e);
}
return Status.INTERNAL_SERVER_ERROR;
}
/**
* Move a member.
* @return
*/
@POST
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/member/{member}")
public Status includeMember(
@FormParam("selection") @DefaultValue("MEMBER") String selectionType,
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@PathParam("member") String uniqueMemberName,
@FormParam("position") @DefaultValue("-1") int position,
@FormParam("memberposition") @DefaultValue("-1") int memberposition)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"/member/"+uniqueMemberName+"\tPOST");
}
try{
olapQueryService.moveDimension(queryName, axisName, dimensionName, position);
boolean ret = olapQueryService.includeMember(queryName, dimensionName, uniqueMemberName, selectionType, memberposition);
if(ret == true){
return Status.CREATED;
}
else{
log.error("Cannot include member "+ dimensionName+ " for query (" + queryName + ")");
return Status.INTERNAL_SERVER_ERROR;
}
} catch (Exception e){
log.error("Cannot include member "+ dimensionName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@DELETE
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/member/{member}")
public Status removeMember(
@FormParam("selection") @DefaultValue("MEMBER") String selectionType,
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@PathParam("member") String uniqueMemberName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"/member/"+uniqueMemberName+"\tDELETE");
}
try{
boolean ret = olapQueryService.removeMember(queryName, dimensionName, uniqueMemberName, selectionType);
if(ret == true){
return Status.OK;
}
else{
log.error("Cannot remove member "+ dimensionName+ " for query (" + queryName + ")");
return Status.INTERNAL_SERVER_ERROR;
}
} catch (Exception e){
log.error("Cannot remove member "+ dimensionName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@POST
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/hierarchy/{hierarchy}/{level}")
public Status includeLevel(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@PathParam("hierarchy") String uniqueHierarchyName,
@PathParam("level") String uniqueLevelName,
@FormParam("position") @DefaultValue("-1") int position)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"/hierarchy/"+uniqueHierarchyName+"/"+uniqueLevelName+"\tPOST");
}
try{
olapQueryService.moveDimension(queryName, axisName, dimensionName, position);
boolean ret = olapQueryService.includeLevel(queryName, dimensionName, uniqueHierarchyName, uniqueLevelName);
if(ret == true){
return Status.CREATED;
}
else{
log.error("Cannot include level of hierarchy "+ uniqueHierarchyName+ " for query (" + queryName + ")");
return Status.INTERNAL_SERVER_ERROR;
}
} catch (Exception e){
log.error("Cannot include level of hierarchy "+ uniqueHierarchyName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
@DELETE
@Path("/{queryname}/axis/{axis}/dimension/{dimension}/hierarchy/{hierarchy}/{level}")
public Status removeLevel(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@PathParam("hierarchy") String uniqueHierarchyName,
@PathParam("level") String uniqueLevelName)
{
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"/hierarchy/"+uniqueHierarchyName+"/"+uniqueLevelName+"\tDELETE");
}
try{
boolean ret = olapQueryService.removeLevel(queryName, dimensionName, uniqueHierarchyName, uniqueLevelName);
if(ret == true){
return Status.OK;
}
else{
log.error("Cannot remove level of hierarchy "+ uniqueHierarchyName+ " for query (" + queryName + ")");
return Status.INTERNAL_SERVER_ERROR;
}
} catch (Exception e){
log.error("Cannot include level of hierarchy "+ uniqueHierarchyName+ " for query (" + queryName + ")",e);
return Status.INTERNAL_SERVER_ERROR;
}
}
}
| false | true | public Status updateSelections(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
MultivaluedMap<String, String> formParams) {
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tPUT");
}
try{
if (formParams.containsKey("selections")) {
LinkedList<String> sels = (LinkedList<String>) formParams.get("selections");
String selectionJSON = (String) sels.getFirst();
ObjectMapper mapper = new ObjectMapper();
List<SelectionRestObject> selections = mapper.readValue(selectionJSON, TypeFactory.collectionType(ArrayList.class, SelectionRestObject.class));
for (SelectionRestObject selection : selections) {
if (selection.getType() != null && "member".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename(), -1, -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename());
}
}
if (selection.getType() != null && "level".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename(), -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename());
}
}
}
return Status.OK;
}
} catch (Exception e){
log.error("Cannot updates selections for query (" + queryName + ")",e);
}
return Status.INTERNAL_SERVER_ERROR;
}
| public Status updateSelections(
@PathParam("queryname") String queryName,
@PathParam("axis") String axisName,
@PathParam("dimension") String dimensionName,
@FormParam("selections") String selectionJSON) {
if (log.isDebugEnabled()) {
log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+axisName+"/dimension/"+dimensionName+"\tPUT");
}
try{
if (selectionJSON != null) {
ObjectMapper mapper = new ObjectMapper();
List<SelectionRestObject> selections = mapper.readValue(selectionJSON, TypeFactory.collectionType(ArrayList.class, SelectionRestObject.class));
for (SelectionRestObject selection : selections) {
if (selection.getType() != null && "member".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename(), -1, -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeMember("MEMBER", queryName, axisName, dimensionName, selection.getUniquename());
}
}
if (selection.getType() != null && "level".equals(selection.getType().toLowerCase())) {
if (selection.getAction() != null && "add".equals(selection.getAction().toLowerCase())) {
includeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename(), -1);
}
if (selection.getAction() != null && "delete".equals(selection.getAction().toLowerCase())) {
removeLevel(queryName, axisName, dimensionName, selection.getHierarchy(), selection.getUniquename());
}
}
}
return Status.OK;
}
} catch (Exception e){
log.error("Cannot updates selections for query (" + queryName + ")",e);
}
return Status.INTERNAL_SERVER_ERROR;
}
|
diff --git a/graphviewer/src/jp/ac/osaka_u/ist/sel/metricstool/graphviewer/GraphViewer.java b/graphviewer/src/jp/ac/osaka_u/ist/sel/metricstool/graphviewer/GraphViewer.java
index 204ba3c6..152ce110 100644
--- a/graphviewer/src/jp/ac/osaka_u/ist/sel/metricstool/graphviewer/GraphViewer.java
+++ b/graphviewer/src/jp/ac/osaka_u/ist/sel/metricstool/graphviewer/GraphViewer.java
@@ -1,233 +1,234 @@
package jp.ac.osaka_u.ist.sel.metricstool.graphviewer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jp.ac.osaka_u.ist.sel.metricstool.cfg.IntraProceduralCFG;
import jp.ac.osaka_u.ist.sel.metricstool.main.MetricsTool;
import jp.ac.osaka_u.ist.sel.metricstool.main.Settings;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.DataManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetConstructorInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetMethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageEvent;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageListener;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePool;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE;
import jp.ac.osaka_u.ist.sel.metricstool.pdg.ControlDependenceEdge;
import jp.ac.osaka_u.ist.sel.metricstool.pdg.DataDependenceEdge;
import jp.ac.osaka_u.ist.sel.metricstool.pdg.IntraProceduralPDG;
import jp.ac.osaka_u.ist.sel.metricstool.pdg.PDGEdge;
import jp.ac.osaka_u.ist.sel.metricstool.pdg.PDGNode;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
/**
* ���͂��ꂽ�v���O������CFG�܂���PDG��graphviz�����ɏo�͂��郂�W���[��
*
* @author higo
*
*/
public class GraphViewer extends MetricsTool {
public static void main(String[] args) {
try {
//�@�R�}���h���C������������
final Options options = new Options();
{
final Option d = new Option("d", "directory", true, "target directory");
d.setArgName("directory");
d.setArgs(1);
d.setRequired(true);
options.addOption(d);
}
{
final Option l = new Option("l", "language", true,
"programming language of analyzed source code");
l.setArgName("language");
l.setArgs(1);
l.setRequired(true);
options.addOption(l);
}
{
final Option c = new Option("c", "ControlFlowGraph", true, "control flow graph");
c.setArgName("file");
c.setArgs(1);
c.setRequired(false);
options.addOption(c);
}
{
final Option p = new Option("p", "ProgramDepencenceGraph", true,
"program dependence graph");
p.setArgName("file");
p.setArgs(1);
p.setRequired(false);
options.addOption(p);
}
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// ��͗p�ݒ�
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d"));
Settings.getInstance().setVerbose(true);
// ���\���p�ݒ�
{
final Class<?> metricstool = MetricsTool.class;
final Field out = metricstool.getDeclaredField("out");
out.setAccessible(true);
out.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "scdetector";
}
}, MESSAGE_TYPE.OUT));
final Field err = metricstool.getDeclaredField("err");
err.setAccessible(true);
err.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "main";
}
}, MESSAGE_TYPE.ERROR));
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(
new MessageListener() {
public void messageReceived(MessageEvent event) {
System.err.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
}
// �Ώۃf�B���N�g���ȉ���Java�t�@�C����o�^���C���
{
final GraphViewer viewer = new GraphViewer();
viewer.readTargetFiles();
viewer.analyzeTargetFiles();
}
if (cmd.hasOption("c")) {
out.println("building and outputing CFGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("c")));
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(method);
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(constructor);
}
writer.close();
}
if (cmd.hasOption("p")) {
out.println("building and outputing PDGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("p")));
writer.write("digraph XXX {");
writer.newLine();
int createdGraphNumber = 0;
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(method);
writer.write("subgraph cluster");
writer.write(Integer.toString(createdGraphNumber++));
writer.write(" {");
writer.newLine();
writer.write("label = \"");
writer.write(method.getMethodName());
writer.write("\";");
+ writer.newLine();
final Map<PDGNode<?>, Integer> nodeLabels = new HashMap<PDGNode<?>, Integer>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
nodeLabels.put(node, nodeLabels.size());
}
for (final Map.Entry<PDGNode<?>, Integer> entry : nodeLabels.entrySet()) {
writer.write(Integer.toString(entry.getValue()));
writer.write(" [label = \"");
writer.write(entry.getKey().getText());
writer.write("\"];");
writer.newLine();
}
final Set<PDGEdge> edges = new HashSet<PDGEdge>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
edges.addAll(node.getBackwardEdges());
edges.addAll(node.getForwardEdges());
}
for (final PDGEdge edge : edges) {
writer.write(Integer.toString(nodeLabels.get(edge.getFromNode())));
writer.write(" -> ");
writer.write(Integer.toString(nodeLabels.get(edge.getToNode())));
if (edge instanceof DataDependenceEdge) {
writer.write(" [style = solid]");
} else if (edge instanceof ControlDependenceEdge) {
writer.write(" [style = dotted]");
}
writer.write(";");
writer.newLine();
}
writer.write("}");
writer.newLine();
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(constructor);
}
writer.write("}");
writer.close();
}
} catch (IOException e) {
err.println(e.getMessage());
System.exit(0);
} catch (ParseException e) {
err.println(e.getMessage());
System.exit(0);
} catch (NoSuchFieldException e) {
err.println(e.getMessage());
System.exit(0);
} catch (IllegalAccessException e) {
err.println(e.getMessage());
System.exit(0);
}
}
}
| true | true | public static void main(String[] args) {
try {
//�@�R�}���h���C������������
final Options options = new Options();
{
final Option d = new Option("d", "directory", true, "target directory");
d.setArgName("directory");
d.setArgs(1);
d.setRequired(true);
options.addOption(d);
}
{
final Option l = new Option("l", "language", true,
"programming language of analyzed source code");
l.setArgName("language");
l.setArgs(1);
l.setRequired(true);
options.addOption(l);
}
{
final Option c = new Option("c", "ControlFlowGraph", true, "control flow graph");
c.setArgName("file");
c.setArgs(1);
c.setRequired(false);
options.addOption(c);
}
{
final Option p = new Option("p", "ProgramDepencenceGraph", true,
"program dependence graph");
p.setArgName("file");
p.setArgs(1);
p.setRequired(false);
options.addOption(p);
}
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// ��͗p�ݒ�
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d"));
Settings.getInstance().setVerbose(true);
// ���\���p�ݒ�
{
final Class<?> metricstool = MetricsTool.class;
final Field out = metricstool.getDeclaredField("out");
out.setAccessible(true);
out.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "scdetector";
}
}, MESSAGE_TYPE.OUT));
final Field err = metricstool.getDeclaredField("err");
err.setAccessible(true);
err.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "main";
}
}, MESSAGE_TYPE.ERROR));
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(
new MessageListener() {
public void messageReceived(MessageEvent event) {
System.err.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
}
// �Ώۃf�B���N�g���ȉ���Java�t�@�C����o�^���C���
{
final GraphViewer viewer = new GraphViewer();
viewer.readTargetFiles();
viewer.analyzeTargetFiles();
}
if (cmd.hasOption("c")) {
out.println("building and outputing CFGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("c")));
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(method);
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(constructor);
}
writer.close();
}
if (cmd.hasOption("p")) {
out.println("building and outputing PDGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("p")));
writer.write("digraph XXX {");
writer.newLine();
int createdGraphNumber = 0;
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(method);
writer.write("subgraph cluster");
writer.write(Integer.toString(createdGraphNumber++));
writer.write(" {");
writer.newLine();
writer.write("label = \"");
writer.write(method.getMethodName());
writer.write("\";");
final Map<PDGNode<?>, Integer> nodeLabels = new HashMap<PDGNode<?>, Integer>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
nodeLabels.put(node, nodeLabels.size());
}
for (final Map.Entry<PDGNode<?>, Integer> entry : nodeLabels.entrySet()) {
writer.write(Integer.toString(entry.getValue()));
writer.write(" [label = \"");
writer.write(entry.getKey().getText());
writer.write("\"];");
writer.newLine();
}
final Set<PDGEdge> edges = new HashSet<PDGEdge>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
edges.addAll(node.getBackwardEdges());
edges.addAll(node.getForwardEdges());
}
for (final PDGEdge edge : edges) {
writer.write(Integer.toString(nodeLabels.get(edge.getFromNode())));
writer.write(" -> ");
writer.write(Integer.toString(nodeLabels.get(edge.getToNode())));
if (edge instanceof DataDependenceEdge) {
writer.write(" [style = solid]");
} else if (edge instanceof ControlDependenceEdge) {
writer.write(" [style = dotted]");
}
writer.write(";");
writer.newLine();
}
writer.write("}");
writer.newLine();
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(constructor);
}
writer.write("}");
writer.close();
}
} catch (IOException e) {
err.println(e.getMessage());
System.exit(0);
} catch (ParseException e) {
err.println(e.getMessage());
System.exit(0);
} catch (NoSuchFieldException e) {
err.println(e.getMessage());
System.exit(0);
} catch (IllegalAccessException e) {
err.println(e.getMessage());
System.exit(0);
}
}
| public static void main(String[] args) {
try {
//�@�R�}���h���C������������
final Options options = new Options();
{
final Option d = new Option("d", "directory", true, "target directory");
d.setArgName("directory");
d.setArgs(1);
d.setRequired(true);
options.addOption(d);
}
{
final Option l = new Option("l", "language", true,
"programming language of analyzed source code");
l.setArgName("language");
l.setArgs(1);
l.setRequired(true);
options.addOption(l);
}
{
final Option c = new Option("c", "ControlFlowGraph", true, "control flow graph");
c.setArgName("file");
c.setArgs(1);
c.setRequired(false);
options.addOption(c);
}
{
final Option p = new Option("p", "ProgramDepencenceGraph", true,
"program dependence graph");
p.setArgName("file");
p.setArgs(1);
p.setRequired(false);
options.addOption(p);
}
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// ��͗p�ݒ�
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d"));
Settings.getInstance().setVerbose(true);
// ���\���p�ݒ�
{
final Class<?> metricstool = MetricsTool.class;
final Field out = metricstool.getDeclaredField("out");
out.setAccessible(true);
out.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "scdetector";
}
}, MESSAGE_TYPE.OUT));
final Field err = metricstool.getDeclaredField("err");
err.setAccessible(true);
err.set(null, new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "main";
}
}, MESSAGE_TYPE.ERROR));
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(
new MessageListener() {
public void messageReceived(MessageEvent event) {
System.err.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
});
}
// �Ώۃf�B���N�g���ȉ���Java�t�@�C����o�^���C���
{
final GraphViewer viewer = new GraphViewer();
viewer.readTargetFiles();
viewer.analyzeTargetFiles();
}
if (cmd.hasOption("c")) {
out.println("building and outputing CFGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("c")));
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(method);
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralCFG cfg = new IntraProceduralCFG(constructor);
}
writer.close();
}
if (cmd.hasOption("p")) {
out.println("building and outputing PDGs ...");
final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd
.getOptionValue("p")));
writer.write("digraph XXX {");
writer.newLine();
int createdGraphNumber = 0;
for (final TargetMethodInfo method : DataManager.getInstance()
.getMethodInfoManager().getTargetMethodInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(method);
writer.write("subgraph cluster");
writer.write(Integer.toString(createdGraphNumber++));
writer.write(" {");
writer.newLine();
writer.write("label = \"");
writer.write(method.getMethodName());
writer.write("\";");
writer.newLine();
final Map<PDGNode<?>, Integer> nodeLabels = new HashMap<PDGNode<?>, Integer>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
nodeLabels.put(node, nodeLabels.size());
}
for (final Map.Entry<PDGNode<?>, Integer> entry : nodeLabels.entrySet()) {
writer.write(Integer.toString(entry.getValue()));
writer.write(" [label = \"");
writer.write(entry.getKey().getText());
writer.write("\"];");
writer.newLine();
}
final Set<PDGEdge> edges = new HashSet<PDGEdge>();
for (final PDGNode<?> node : pdg.getAllNodes()) {
edges.addAll(node.getBackwardEdges());
edges.addAll(node.getForwardEdges());
}
for (final PDGEdge edge : edges) {
writer.write(Integer.toString(nodeLabels.get(edge.getFromNode())));
writer.write(" -> ");
writer.write(Integer.toString(nodeLabels.get(edge.getToNode())));
if (edge instanceof DataDependenceEdge) {
writer.write(" [style = solid]");
} else if (edge instanceof ControlDependenceEdge) {
writer.write(" [style = dotted]");
}
writer.write(";");
writer.newLine();
}
writer.write("}");
writer.newLine();
}
for (final TargetConstructorInfo constructor : DataManager.getInstance()
.getMethodInfoManager().getTargetConstructorInfos()) {
final IntraProceduralPDG pdg = new IntraProceduralPDG(constructor);
}
writer.write("}");
writer.close();
}
} catch (IOException e) {
err.println(e.getMessage());
System.exit(0);
} catch (ParseException e) {
err.println(e.getMessage());
System.exit(0);
} catch (NoSuchFieldException e) {
err.println(e.getMessage());
System.exit(0);
} catch (IllegalAccessException e) {
err.println(e.getMessage());
System.exit(0);
}
}
|
diff --git a/src/com/android/mms/ui/ConversationListItem.java b/src/com/android/mms/ui/ConversationListItem.java
index b7f6de72..1d407473 100644
--- a/src/com/android/mms/ui/ConversationListItem.java
+++ b/src/com/android/mms/ui/ConversationListItem.java
@@ -1,231 +1,231 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 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.mms.ui;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import com.android.mms.data.Conversation;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.QuickContactBadge;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* This class manages the view for given conversation.
*/
public class ConversationListItem extends RelativeLayout implements Contact.UpdateListener {
private static final String TAG = "ConversationListItem";
private static final boolean DEBUG = false;
private TextView mSubjectView;
private TextView mFromView;
private TextView mDateView;
private View mAttachmentView;
private View mErrorIndicator;
private QuickContactBadge mAvatarView;
static private Drawable sDefaultContactImage;
// For posting UI update Runnables from other threads:
private Handler mHandler = new Handler();
private Conversation mConversation;
private static final StyleSpan STYLE_BOLD = new StyleSpan(Typeface.BOLD);
public ConversationListItem(Context context) {
super(context);
}
public ConversationListItem(Context context, AttributeSet attrs) {
super(context, attrs);
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mFromView = (TextView) findViewById(R.id.from);
mSubjectView = (TextView) findViewById(R.id.subject);
mDateView = (TextView) findViewById(R.id.date);
mAttachmentView = findViewById(R.id.attachment);
mErrorIndicator = findViewById(R.id.error);
mAvatarView = (QuickContactBadge) findViewById(R.id.avatar);
}
public Conversation getConversation() {
return mConversation;
}
/**
* Only used for header binding.
*/
public void bind(String title, String explain) {
mFromView.setText(title);
mSubjectView.setText(explain);
}
private CharSequence formatMessage() {
final int color = android.R.styleable.Theme_textColorSecondary;
String from = mConversation.getRecipients().formatNames(", ");
SpannableStringBuilder buf = new SpannableStringBuilder(from);
if (mConversation.getMessageCount() > 1) {
int before = buf.length();
buf.append(mContext.getResources().getString(R.string.message_count_format,
mConversation.getMessageCount()));
buf.setSpan(new ForegroundColorSpan(
mContext.getResources().getColor(R.color.message_count_color)),
before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (mConversation.hasDraft()) {
buf.append(mContext.getResources().getString(R.string.draft_separator));
int before = buf.length();
int size;
buf.append(mContext.getResources().getString(R.string.has_draft));
size = android.R.style.TextAppearance_Small;
buf.setSpan(new TextAppearanceSpan(mContext, size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
buf.setSpan(new ForegroundColorSpan(
mContext.getResources().getColor(R.drawable.text_color_red)),
before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
// Unread messages are shown in bold
if (mConversation.hasUnreadMessages()) {
buf.setSpan(STYLE_BOLD, 0, buf.length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
return buf;
}
private void updateAvatarView() {
Drawable avatarDrawable;
if (mConversation.getRecipients().size() == 1) {
Contact contact = mConversation.getRecipients().get(0);
avatarDrawable = contact.getAvatar(mContext, sDefaultContactImage);
if (contact.existsInDatabase()) {
mAvatarView.assignContactUri(contact.getUri());
} else {
mAvatarView.assignContactFromPhone(contact.getNumber(), true);
}
} else {
// TODO get a multiple recipients asset (or do something else)
avatarDrawable = sDefaultContactImage;
mAvatarView.assignContactUri(null);
}
mAvatarView.setImageDrawable(avatarDrawable);
mAvatarView.setVisibility(View.VISIBLE);
}
private void updateFromView() {
mFromView.setText(formatMessage());
updateAvatarView();
}
public void onUpdate(Contact updated) {
mHandler.post(new Runnable() {
public void run() {
updateFromView();
}
});
}
public final void bind(Context context, final Conversation conversation) {
//if (DEBUG) Log.v(TAG, "bind()");
mConversation = conversation;
int backgroundId;
if (conversation.isChecked()) {
- backgroundId = R.drawable.list_selected_holo;
+ backgroundId = R.drawable.list_selected_holo_light;
} else if (conversation.hasUnreadMessages()) {
backgroundId = R.drawable.conversation_item_background_unread;
} else {
backgroundId = R.drawable.conversation_item_background_read;
}
Drawable background = mContext.getResources().getDrawable(backgroundId);
setBackgroundDrawable(background);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = conversation.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = conversation.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(MessageUtils.formatTimeStampString(context, conversation.getDate()));
// From.
mFromView.setText(formatMessage());
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = conversation.getRecipients();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
Contact.addListener(this);
// Subject
mSubjectView.setText(conversation.getSnippet());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
public final void unbind() {
if (DEBUG) Log.v(TAG, "unbind: contacts.removeListeners " + this);
// Unregister contact update callbacks.
Contact.removeListener(this);
}
}
| true | true | public final void bind(Context context, final Conversation conversation) {
//if (DEBUG) Log.v(TAG, "bind()");
mConversation = conversation;
int backgroundId;
if (conversation.isChecked()) {
backgroundId = R.drawable.list_selected_holo;
} else if (conversation.hasUnreadMessages()) {
backgroundId = R.drawable.conversation_item_background_unread;
} else {
backgroundId = R.drawable.conversation_item_background_read;
}
Drawable background = mContext.getResources().getDrawable(backgroundId);
setBackgroundDrawable(background);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = conversation.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = conversation.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(MessageUtils.formatTimeStampString(context, conversation.getDate()));
// From.
mFromView.setText(formatMessage());
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = conversation.getRecipients();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
Contact.addListener(this);
// Subject
mSubjectView.setText(conversation.getSnippet());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
| public final void bind(Context context, final Conversation conversation) {
//if (DEBUG) Log.v(TAG, "bind()");
mConversation = conversation;
int backgroundId;
if (conversation.isChecked()) {
backgroundId = R.drawable.list_selected_holo_light;
} else if (conversation.hasUnreadMessages()) {
backgroundId = R.drawable.conversation_item_background_unread;
} else {
backgroundId = R.drawable.conversation_item_background_read;
}
Drawable background = mContext.getResources().getDrawable(backgroundId);
setBackgroundDrawable(background);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = conversation.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = conversation.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(MessageUtils.formatTimeStampString(context, conversation.getDate()));
// From.
mFromView.setText(formatMessage());
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = conversation.getRecipients();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
Contact.addListener(this);
// Subject
mSubjectView.setText(conversation.getSnippet());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
|
diff --git a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
index 7684ddd50..dfce2d4ce 100644
--- a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
+++ b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java
@@ -1,260 +1,260 @@
/**
* 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.mahout.utils.vectors.lucene;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.apache.commons.cli2.CommandLine;
import org.apache.commons.cli2.Group;
import org.apache.commons.cli2.Option;
import org.apache.commons.cli2.OptionException;
import org.apache.commons.cli2.builder.ArgumentBuilder;
import org.apache.commons.cli2.builder.DefaultOptionBuilder;
import org.apache.commons.cli2.builder.GroupBuilder;
import org.apache.commons.cli2.commandline.Parser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.mahout.common.CommandLineUtil;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.utils.vectors.TF;
import org.apache.mahout.utils.vectors.TFIDF;
import org.apache.mahout.utils.vectors.TermInfo;
import org.apache.mahout.utils.vectors.Weight;
import org.apache.mahout.utils.vectors.io.JWriterTermInfoWriter;
import org.apache.mahout.utils.vectors.io.JWriterVectorWriter;
import org.apache.mahout.utils.vectors.io.SequenceFileVectorWriter;
import org.apache.mahout.utils.vectors.io.VectorWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Driver {
private static final Logger log = LoggerFactory.getLogger(Driver.class);
private Driver() { }
public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
"The delimiter for outputing the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
- throw new IllegalArgumentException("Lucene directory: " + file.getName() +
+ throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath() +
" does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if (wString.equalsIgnoreCase("tf")) {
weight = new TF();
} else if (wString.equalsIgnoreCase("tfidf")) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if (power.equals("INF")) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if (outWriter.equals("file")) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
private static VectorWriter getSeqFileWriter(String outFile) throws IOException {
Path path = new Path(outFile);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
// TODO: Make this parameter driven
SequenceFile.Writer seqWriter = SequenceFile.createWriter(fs, conf, path, LongWritable.class,
VectorWritable.class);
return new SequenceFileVectorWriter(seqWriter);
}
}
| true | true | public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
"The delimiter for outputing the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
throw new IllegalArgumentException("Lucene directory: " + file.getName() +
" does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if (wString.equalsIgnoreCase("tf")) {
weight = new TF();
} else if (wString.equalsIgnoreCase("tfidf")) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if (power.equals("INF")) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if (outWriter.equals("file")) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
| public static void main(String[] args) throws IOException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument(
abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
.withDescription("The Lucene directory").withShortName("d").create();
Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument(
abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file")
.withShortName("o").create();
Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument(
abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index").withShortName("f").create();
Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument(
abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription(
"The field in the index containing the index. If null, then the Lucene internal doc "
+ "id is used which is prone to error if the underlying index changes").withShortName("i").create();
Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument(
abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription(
"The output of the dictionary").withShortName("t").create();
Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument(
abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription(
"The kind of weight to use. Currently TF or TFIDF").withShortName("w").create();
Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument(
abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription(
"The delimiter for outputing the dictionary").withShortName("l").create();
Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument(
abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription(
"The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. "
+ "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create();
Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument(
abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription(
"The maximum number of vectors to output. If not specified, then it will loop over all docs")
.withShortName("m").create();
Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument(
abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription(
"The VectorWriter to use, either seq "
+ "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)")
.withShortName("e").create();
Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument(
abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription(
"The minimum document frequency. Default is 1").withShortName("md").create();
Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument(
abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription(
"The max percentage of docs for the DF. Can be used to remove really high frequency terms."
+ " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create();
Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
.create();
Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption(
outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt)
.withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt)
.withOption(weightOpt).withOption(minDFOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
// Springify all this
if (cmdLine.hasOption(inputOpt)) { // Lucene case
File file = new File(cmdLine.getValue(inputOpt).toString());
if (!file.isDirectory()) {
throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath() +
" does not exist or is not a directory");
}
long maxDocs = Long.MAX_VALUE;
if (cmdLine.hasOption(maxOpt)) {
maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
}
if (maxDocs < 0) {
throw new IllegalArgumentException("maxDocs must be >= 0");
}
Directory dir = FSDirectory.open(file);
IndexReader reader = IndexReader.open(dir, true);
Weight weight;
if (cmdLine.hasOption(weightOpt)) {
String wString = cmdLine.getValue(weightOpt).toString();
if (wString.equalsIgnoreCase("tf")) {
weight = new TF();
} else if (wString.equalsIgnoreCase("tfidf")) {
weight = new TFIDF();
} else {
throw new OptionException(weightOpt);
}
} else {
weight = new TFIDF();
}
String field = cmdLine.getValue(fieldOpt).toString();
int minDf = 1;
if (cmdLine.hasOption(minDFOpt)) {
minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString());
}
int maxDFPercent = 99;
if (cmdLine.hasOption(maxDFPercentOpt)) {
maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString());
}
TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent);
VectorMapper mapper = new TFDFMapper(reader, weight, termInfo);
double norm = LuceneIterable.NO_NORMALIZING;
if (cmdLine.hasOption(powerOpt)) {
String power = cmdLine.getValue(powerOpt).toString();
if (power.equals("INF")) {
norm = Double.POSITIVE_INFINITY;
} else {
norm = Double.parseDouble(power);
}
}
String idField = null;
if (cmdLine.hasOption(idFieldOpt)) {
idField = cmdLine.getValue(idFieldOpt).toString();
}
LuceneIterable iterable;
if (norm == LuceneIterable.NO_NORMALIZING) {
iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING);
} else {
iterable = new LuceneIterable(reader, idField, field, mapper, norm);
}
String outFile = cmdLine.getValue(outputOpt).toString();
log.info("Output File: {}", outFile);
VectorWriter vectorWriter;
if (cmdLine.hasOption(outWriterOpt)) {
String outWriter = cmdLine.getValue(outWriterOpt).toString();
if (outWriter.equals("file")) {
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
vectorWriter = new JWriterVectorWriter(writer);
} else {
vectorWriter = getSeqFileWriter(outFile);
}
} else {
vectorWriter = getSeqFileWriter(outFile);
}
long numDocs = vectorWriter.write(iterable, maxDocs);
vectorWriter.close();
log.info("Wrote: {} vectors", numDocs);
String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t";
File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString());
log.info("Dictionary Output file: {}", dictOutFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dictOutFile), Charset.forName("UTF8")));
JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field);
tiWriter.write(termInfo);
tiWriter.close();
writer.close();
}
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
}
}
|
diff --git a/src/java/com/google/android/mms/pdu/PduComposer.java b/src/java/com/google/android/mms/pdu/PduComposer.java
index d426f89..bb44bab 100644
--- a/src/java/com/google/android/mms/pdu/PduComposer.java
+++ b/src/java/com/google/android/mms/pdu/PduComposer.java
@@ -1,1179 +1,1186 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 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.google.android.mms.pdu;
import android.content.ContentResolver;
import android.content.Context;
import android.util.Log;
import android.text.TextUtils;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
public class PduComposer {
/**
* Address type.
*/
static private final int PDU_PHONE_NUMBER_ADDRESS_TYPE = 1;
static private final int PDU_EMAIL_ADDRESS_TYPE = 2;
static private final int PDU_IPV4_ADDRESS_TYPE = 3;
static private final int PDU_IPV6_ADDRESS_TYPE = 4;
static private final int PDU_UNKNOWN_ADDRESS_TYPE = 5;
/**
* Address regular expression string.
*/
static final String REGEXP_PHONE_NUMBER_ADDRESS_TYPE = "\\+?[0-9|\\.|\\-]+";
static final String REGEXP_EMAIL_ADDRESS_TYPE = "[a-zA-Z| ]*\\<{0,1}[a-zA-Z| ]+@{1}" +
"[a-zA-Z| ]+\\.{1}[a-zA-Z| ]+\\>{0,1}";
static final String REGEXP_IPV6_ADDRESS_TYPE =
"[a-fA-F]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" +
"[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" +
"[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}";
static final String REGEXP_IPV4_ADDRESS_TYPE = "[0-9]{1,3}\\.{1}[0-9]{1,3}\\.{1}" +
"[0-9]{1,3}\\.{1}[0-9]{1,3}";
/**
* The postfix strings of address.
*/
static final String STRING_PHONE_NUMBER_ADDRESS_TYPE = "/TYPE=PLMN";
static final String STRING_IPV4_ADDRESS_TYPE = "/TYPE=IPV4";
static final String STRING_IPV6_ADDRESS_TYPE = "/TYPE=IPV6";
/**
* Error values.
*/
static private final int PDU_COMPOSE_SUCCESS = 0;
static private final int PDU_COMPOSE_CONTENT_ERROR = 1;
static private final int PDU_COMPOSE_FIELD_NOT_SET = 2;
static private final int PDU_COMPOSE_FIELD_NOT_SUPPORTED = 3;
/**
* WAP values defined in WSP spec.
*/
static private final int QUOTED_STRING_FLAG = 34;
static private final int END_STRING_FLAG = 0;
static private final int LENGTH_QUOTE = 31;
static private final int TEXT_MAX = 127;
static private final int SHORT_INTEGER_MAX = 127;
static private final int LONG_INTEGER_LENGTH_MAX = 8;
/**
* Block size when read data from InputStream.
*/
static private final int PDU_COMPOSER_BLOCK_SIZE = 1024;
/**
* The output message.
*/
protected ByteArrayOutputStream mMessage = null;
/**
* The PDU.
*/
private GenericPdu mPdu = null;
/**
* Current visiting position of the mMessage.
*/
protected int mPosition = 0;
/**
* Message compose buffer stack.
*/
private BufferStack mStack = null;
/**
* Content resolver.
*/
private final ContentResolver mResolver;
/**
* Header of this pdu.
*/
private PduHeaders mPduHeader = null;
/**
* Map of all content type
*/
private static HashMap<String, Integer> mContentTypeMap = null;
static {
mContentTypeMap = new HashMap<String, Integer>();
int i;
for (i = 0; i < PduContentTypes.contentTypes.length; i++) {
mContentTypeMap.put(PduContentTypes.contentTypes[i], i);
}
}
/**
* Constructor.
*
* @param context the context
* @param pdu the pdu to be composed
*/
public PduComposer(Context context, GenericPdu pdu) {
mPdu = pdu;
mResolver = context.getContentResolver();
mPduHeader = pdu.getPduHeaders();
mStack = new BufferStack();
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
/**
* Make the message. No need to check whether mandatory fields are set,
* because the constructors of outgoing pdus are taking care of this.
*
* @return OutputStream of maked message. Return null if
* the PDU is invalid.
*/
public byte[] make() {
// Get Message-type.
int type = mPdu.getMessageType();
/* make the message */
switch (type) {
case PduHeaders.MESSAGE_TYPE_SEND_REQ:
if (makeSendReqPdu() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
if (makeNotifyResp() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
if (makeAckInd() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
if (makeReadRecInd() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
default:
return null;
}
return mMessage.toByteArray();
}
/**
* Copy buf to mMessage.
*/
protected void arraycopy(byte[] buf, int pos, int length) {
mMessage.write(buf, pos, length);
mPosition = mPosition + length;
}
/**
* Append a byte to mMessage.
*/
protected void append(int value) {
mMessage.write(value);
mPosition ++;
}
/**
* Append short integer value to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendShortInteger(int value) {
/*
* From WAP-230-WSP-20010705-a:
* Short-integer = OCTET
* ; Integers in range 0-127 shall be encoded as a one octet value
* ; with the most significant bit set to one (1xxx xxxx) and with
* ; the value in the remaining least significant bits.
* In our implementation, only low 7 bits are stored and otherwise
* bits are ignored.
*/
append((value | 0x80) & 0xff);
}
/**
* Append an octet number between 128 and 255 into mMessage.
* NOTE:
* A value between 0 and 127 should be appended by using appendShortInteger.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendOctet(int number) {
append(number);
}
/**
* Append a short length into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendShortLength(int value) {
/*
* From WAP-230-WSP-20010705-a:
* Short-length = <Any octet 0-30>
*/
append(value);
}
/**
* Append long integer into mMessage. it's used for really long integers.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendLongInteger(long longInt) {
/*
* From WAP-230-WSP-20010705-a:
* Long-integer = Short-length Multi-octet-integer
* ; The Short-length indicates the length of the Multi-octet-integer
* Multi-octet-integer = 1*30 OCTET
* ; The content octets shall be an unsigned integer value with the
* ; most significant octet encoded first (big-endian representation).
* ; The minimum number of octets must be used to encode the value.
*/
int size;
long temp = longInt;
// Count the length of the long integer.
for(size = 0; (temp != 0) && (size < LONG_INTEGER_LENGTH_MAX); size++) {
temp = (temp >>> 8);
}
// Set Length.
appendShortLength(size);
// Count and set the long integer.
int i;
int shift = (size -1) * 8;
for (i = 0; i < size; i++) {
append((int)((longInt >>> shift) & 0xff));
shift = shift - 8;
}
}
/**
* Append text string into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendTextString(byte[] text) {
/*
* From WAP-230-WSP-20010705-a:
* Text-string = [Quote] *TEXT End-of-string
* ; If the first character in the TEXT is in the range of 128-255,
* ; a Quote character must precede it. Otherwise the Quote character
* ;must be omitted. The Quote is not part of the contents.
*/
if (((text[0])&0xff) > TEXT_MAX) { // No need to check for <= 255
append(TEXT_MAX);
}
arraycopy(text, 0, text.length);
append(0);
}
/**
* Append text string into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendTextString(String str) {
/*
* From WAP-230-WSP-20010705-a:
* Text-string = [Quote] *TEXT End-of-string
* ; If the first character in the TEXT is in the range of 128-255,
* ; a Quote character must precede it. Otherwise the Quote character
* ;must be omitted. The Quote is not part of the contents.
*/
appendTextString(str.getBytes());
}
/**
* Append encoded string value to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendEncodedString(EncodedStringValue enStr) {
/*
* From OMA-TS-MMS-ENC-V1_3-20050927-C:
* Encoded-string-value = Text-string | Value-length Char-set Text-string
*/
assert(enStr != null);
int charset = enStr.getCharacterSet();
byte[] textString = enStr.getTextString();
if (null == textString) {
return;
}
/*
* In the implementation of EncodedStringValue, the charset field will
* never be 0. It will always be composed as
* Encoded-string-value = Value-length Char-set Text-string
*/
mStack.newbuf();
PositionMarker start = mStack.mark();
appendShortInteger(charset);
appendTextString(textString);
int len = start.getLength();
mStack.pop();
appendValueLength(len);
mStack.copy();
}
/**
* Append uintvar integer into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendUintvarInteger(long value) {
/*
* From WAP-230-WSP-20010705-a:
* To encode a large unsigned integer, split it into 7-bit fragments
* and place them in the payloads of multiple octets. The most significant
* bits are placed in the first octets with the least significant bits
* ending up in the last octet. All octets MUST set the Continue bit to 1
* except the last octet, which MUST set the Continue bit to 0.
*/
int i;
long max = SHORT_INTEGER_MAX;
for (i = 0; i < 5; i++) {
if (value < max) {
break;
}
max = (max << 7) | 0x7fl;
}
while(i > 0) {
long temp = value >>> (i * 7);
temp = temp & 0x7f;
append((int)((temp | 0x80) & 0xff));
i--;
}
append((int)(value & 0x7f));
}
/**
* Append date value into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendDateValue(long date) {
/*
* From OMA-TS-MMS-ENC-V1_3-20050927-C:
* Date-value = Long-integer
*/
appendLongInteger(date);
}
/**
* Append value length to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendValueLength(long value) {
/*
* From WAP-230-WSP-20010705-a:
* Value-length = Short-length | (Length-quote Length)
* ; Value length is used to indicate the length of the value to follow
* Short-length = <Any octet 0-30>
* Length-quote = <Octet 31>
* Length = Uintvar-integer
*/
if (value < LENGTH_QUOTE) {
appendShortLength((int) value);
return;
}
append(LENGTH_QUOTE);
appendUintvarInteger(value);
}
/**
* Append quoted string to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendQuotedString(byte[] text) {
/*
* From WAP-230-WSP-20010705-a:
* Quoted-string = <Octet 34> *TEXT End-of-string
* ;The TEXT encodes an RFC2616 Quoted-string with the enclosing
* ;quotation-marks <"> removed.
*/
append(QUOTED_STRING_FLAG);
arraycopy(text, 0, text.length);
append(END_STRING_FLAG);
}
/**
* Append quoted string to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendQuotedString(String str) {
/*
* From WAP-230-WSP-20010705-a:
* Quoted-string = <Octet 34> *TEXT End-of-string
* ;The TEXT encodes an RFC2616 Quoted-string with the enclosing
* ;quotation-marks <"> removed.
*/
appendQuotedString(str.getBytes());
}
private EncodedStringValue appendAddressType(EncodedStringValue address) {
EncodedStringValue temp = null;
try {
int addressType = checkAddressType(address.getString());
temp = EncodedStringValue.copy(address);
if (PDU_PHONE_NUMBER_ADDRESS_TYPE == addressType) {
// Phone number.
temp.appendTextString(STRING_PHONE_NUMBER_ADDRESS_TYPE.getBytes());
} else if (PDU_IPV4_ADDRESS_TYPE == addressType) {
// Ipv4 address.
temp.appendTextString(STRING_IPV4_ADDRESS_TYPE.getBytes());
} else if (PDU_IPV6_ADDRESS_TYPE == addressType) {
// Ipv6 address.
temp.appendTextString(STRING_IPV6_ADDRESS_TYPE.getBytes());
}
} catch (NullPointerException e) {
return null;
}
return temp;
}
/**
* Append header to mMessage.
*/
private int appendHeader(int field) {
switch (field) {
case PduHeaders.MMS_VERSION:
appendOctet(field);
int version = mPduHeader.getOctet(field);
if (0 == version) {
appendShortInteger(PduHeaders.CURRENT_MMS_VERSION);
} else {
appendShortInteger(version);
}
break;
case PduHeaders.MESSAGE_ID:
case PduHeaders.TRANSACTION_ID:
byte[] textString = mPduHeader.getTextString(field);
if (null == textString) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendTextString(textString);
break;
case PduHeaders.TO:
case PduHeaders.BCC:
case PduHeaders.CC:
EncodedStringValue[] addr = mPduHeader.getEncodedStringValues(field);
if (null == addr) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
EncodedStringValue temp;
for (int i = 0; i < addr.length; i++) {
temp = appendAddressType(addr[i]);
if (temp == null) {
return PDU_COMPOSE_CONTENT_ERROR;
}
appendOctet(field);
appendEncodedString(temp);
}
break;
case PduHeaders.FROM:
// Value-length (Address-present-token Encoded-string-value | Insert-address-token)
appendOctet(field);
EncodedStringValue from = mPduHeader.getEncodedStringValue(field);
if ((from == null)
|| TextUtils.isEmpty(from.getString())
|| new String(from.getTextString()).equals(
PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR)) {
// Length of from = 1
append(1);
// Insert-address-token = <Octet 129>
append(PduHeaders.FROM_INSERT_ADDRESS_TOKEN);
} else {
mStack.newbuf();
PositionMarker fstart = mStack.mark();
// Address-present-token = <Octet 128>
append(PduHeaders.FROM_ADDRESS_PRESENT_TOKEN);
temp = appendAddressType(from);
if (temp == null) {
return PDU_COMPOSE_CONTENT_ERROR;
}
appendEncodedString(temp);
int flen = fstart.getLength();
mStack.pop();
appendValueLength(flen);
mStack.copy();
}
break;
case PduHeaders.READ_STATUS:
case PduHeaders.STATUS:
case PduHeaders.REPORT_ALLOWED:
case PduHeaders.PRIORITY:
case PduHeaders.DELIVERY_REPORT:
case PduHeaders.READ_REPORT:
int octet = mPduHeader.getOctet(field);
if (0 == octet) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendOctet(octet);
break;
case PduHeaders.DATE:
long date = mPduHeader.getLongInteger(field);
if (-1 == date) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendDateValue(date);
break;
case PduHeaders.SUBJECT:
EncodedStringValue enString =
mPduHeader.getEncodedStringValue(field);
if (null == enString) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendEncodedString(enString);
break;
case PduHeaders.MESSAGE_CLASS:
byte[] messageClass = mPduHeader.getTextString(field);
if (null == messageClass) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_ADVERTISEMENT);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_AUTO);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_PERSONAL);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_INFORMATIONAL);
} else {
appendTextString(messageClass);
}
break;
case PduHeaders.EXPIRY:
long expiry = mPduHeader.getLongInteger(field);
if (-1 == expiry) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
mStack.newbuf();
PositionMarker expiryStart = mStack.mark();
append(PduHeaders.VALUE_RELATIVE_TOKEN);
appendLongInteger(expiry);
int expiryLength = expiryStart.getLength();
mStack.pop();
appendValueLength(expiryLength);
mStack.copy();
break;
default:
return PDU_COMPOSE_FIELD_NOT_SUPPORTED;
}
return PDU_COMPOSE_SUCCESS;
}
/**
* Make ReadRec.Ind.
*/
private int makeReadRecInd() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Message-ID
if (appendHeader(PduHeaders.MESSAGE_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// To
if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// From
if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Date Optional
appendHeader(PduHeaders.DATE);
// X-Mms-Read-Status
if (appendHeader(PduHeaders.READ_STATUS) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Applic-ID Optional(not support)
// X-Mms-Reply-Applic-ID Optional(not support)
// X-Mms-Aux-Applic-Info Optional(not support)
return PDU_COMPOSE_SUCCESS;
}
/**
* Make NotifyResp.Ind.
*/
private int makeNotifyResp() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND);
// X-Mms-Transaction-ID
if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Status
if (appendHeader(PduHeaders.STATUS) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Report-Allowed Optional (not support)
return PDU_COMPOSE_SUCCESS;
}
/**
* Make Acknowledge.Ind.
*/
private int makeAckInd() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND);
// X-Mms-Transaction-ID
if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Report-Allowed Optional
appendHeader(PduHeaders.REPORT_ALLOWED);
return PDU_COMPOSE_SUCCESS;
}
/**
* Make Send.req.
*/
private int makeSendReqPdu() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_SEND_REQ);
// X-Mms-Transaction-ID
appendOctet(PduHeaders.TRANSACTION_ID);
byte[] trid = mPduHeader.getTextString(PduHeaders.TRANSACTION_ID);
if (trid == null) {
// Transaction-ID should be set(by Transaction) before make().
throw new IllegalArgumentException("Transaction-ID is null.");
}
appendTextString(trid);
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Date Date-value Optional.
appendHeader(PduHeaders.DATE);
// From
if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
boolean recipient = false;
// To
if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Cc
if (appendHeader(PduHeaders.CC) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Bcc
if (appendHeader(PduHeaders.BCC) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Need at least one of "cc", "bcc" and "to".
if (false == recipient) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Subject Optional
appendHeader(PduHeaders.SUBJECT);
// X-Mms-Message-Class Optional
// Message-class-value = Class-identifier | Token-text
appendHeader(PduHeaders.MESSAGE_CLASS);
// X-Mms-Expiry Optional
appendHeader(PduHeaders.EXPIRY);
// X-Mms-Priority Optional
appendHeader(PduHeaders.PRIORITY);
// X-Mms-Delivery-Report Optional
appendHeader(PduHeaders.DELIVERY_REPORT);
// X-Mms-Read-Report Optional
appendHeader(PduHeaders.READ_REPORT);
// Content-Type
appendOctet(PduHeaders.CONTENT_TYPE);
// Message body
return makeMessageBody();
}
/**
* Make message body.
*/
private int makeMessageBody() {
// 1. add body informations
mStack.newbuf(); // Switching buffer because we need to
PositionMarker ctStart = mStack.mark();
// This contentTypeIdentifier should be used for type of attachment...
String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE));
Integer contentTypeIdentifier = mContentTypeMap.get(contentType);
if (contentTypeIdentifier == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
appendShortInteger(contentTypeIdentifier.intValue());
// content-type parameter: start
PduBody body = ((SendReq) mPdu).getBody();
if (null == body || body.getPartsNum() == 0) {
// empty message
appendUintvarInteger(0);
mStack.pop();
mStack.copy();
return PDU_COMPOSE_SUCCESS;
}
PduPart part;
try {
part = body.getPart(0);
byte[] start = part.getContentId();
if (start != null) {
appendOctet(PduPart.P_DEP_START);
if (('<' == start[0]) && ('>' == start[start.length - 1])) {
appendTextString(start);
} else {
appendTextString("<" + new String(start) + ">");
}
}
// content-type parameter: type
appendOctet(PduPart.P_CT_MR_TYPE);
appendTextString(part.getContentType());
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
int ctLength = ctStart.getLength();
mStack.pop();
appendValueLength(ctLength);
mStack.copy();
// 3. add content
int partNum = body.getPartsNum();
appendUintvarInteger(partNum);
for (int i = 0; i < partNum; i++) {
part = body.getPart(i);
mStack.newbuf(); // Leaving space for header lengh and data length
PositionMarker attachment = mStack.mark();
mStack.newbuf(); // Leaving space for Content-Type length
PositionMarker contentTypeBegin = mStack.mark();
byte[] partContentType = part.getContentType();
if (partContentType == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
// content-type value
Integer partContentTypeIdentifier =
mContentTypeMap.get(new String(partContentType));
if (partContentTypeIdentifier == null) {
appendTextString(partContentType);
} else {
appendShortInteger(partContentTypeIdentifier.intValue());
}
/* Content-type parameter : name.
* The value of name, filename, content-location is the same.
* Just one of them is enough for this PDU.
*/
byte[] name = part.getName();
if (null == name) {
name = part.getFilename();
if (null == name) {
name = part.getContentLocation();
if (null == name) {
/* at lease one of name, filename, Content-location
* should be available.
*/
return PDU_COMPOSE_CONTENT_ERROR;
}
}
}
appendOctet(PduPart.P_DEP_NAME);
appendTextString(name);
// content-type parameter : charset
int charset = part.getCharset();
if (charset != 0) {
appendOctet(PduPart.P_CHARSET);
appendShortInteger(charset);
}
int contentTypeLength = contentTypeBegin.getLength();
mStack.pop();
appendValueLength(contentTypeLength);
mStack.copy();
// content id
byte[] contentId = part.getContentId();
if (null != contentId) {
appendOctet(PduPart.P_CONTENT_ID);
if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) {
appendQuotedString(contentId);
} else {
appendQuotedString("<" + new String(contentId) + ">");
}
}
// content-location
byte[] contentLocation = part.getContentLocation();
if (null != contentLocation) {
appendOctet(PduPart.P_CONTENT_LOCATION);
appendTextString(contentLocation);
}
// content
int headerLength = attachment.getLength();
int dataLength = 0; // Just for safety...
byte[] partData = part.getData();
if (partData != null) {
arraycopy(partData, 0, partData.length);
dataLength = partData.length;
} else {
- InputStream cr;
+ InputStream cr = null;
try {
byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE];
cr = mResolver.openInputStream(part.getDataUri());
int len = 0;
while ((len = cr.read(buffer)) != -1) {
mMessage.write(buffer, 0, len);
mPosition += len;
dataLength += len;
}
} catch (FileNotFoundException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (IOException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (RuntimeException e) {
return PDU_COMPOSE_CONTENT_ERROR;
+ } finally {
+ if (cr != null) {
+ try {
+ cr.close();
+ } catch (IOException e) {
+ }
+ }
}
}
if (dataLength != (attachment.getLength() - headerLength)) {
throw new RuntimeException("BUG: Length sanity check failed");
}
mStack.pop();
appendUintvarInteger(headerLength);
appendUintvarInteger(dataLength);
mStack.copy();
}
return PDU_COMPOSE_SUCCESS;
}
/**
* Record current message informations.
*/
static private class LengthRecordNode {
ByteArrayOutputStream currentMessage = null;
public int currentPosition = 0;
public LengthRecordNode next = null;
}
/**
* Mark current message position and stact size.
*/
private class PositionMarker {
private int c_pos; // Current position
private int currentStackSize; // Current stack size
int getLength() {
// If these assert fails, likely that you are finding the
// size of buffer that is deep in BufferStack you can only
// find the length of the buffer that is on top
if (currentStackSize != mStack.stackSize) {
throw new RuntimeException("BUG: Invalid call to getLength()");
}
return mPosition - c_pos;
}
}
/**
* This implementation can be OPTIMIZED to use only
* 2 buffers. This optimization involves changing BufferStack
* only... Its usage (interface) will not change.
*/
private class BufferStack {
private LengthRecordNode stack = null;
private LengthRecordNode toCopy = null;
int stackSize = 0;
/**
* Create a new message buffer and push it into the stack.
*/
void newbuf() {
// You can't create a new buff when toCopy != null
// That is after calling pop() and before calling copy()
// If you do, it is a bug
if (toCopy != null) {
throw new RuntimeException("BUG: Invalid newbuf() before copy()");
}
LengthRecordNode temp = new LengthRecordNode();
temp.currentMessage = mMessage;
temp.currentPosition = mPosition;
temp.next = stack;
stack = temp;
stackSize = stackSize + 1;
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
/**
* Pop the message before and record current message in the stack.
*/
void pop() {
ByteArrayOutputStream currentMessage = mMessage;
int currentPosition = mPosition;
mMessage = stack.currentMessage;
mPosition = stack.currentPosition;
toCopy = stack;
// Re using the top element of the stack to avoid memory allocation
stack = stack.next;
stackSize = stackSize - 1;
toCopy.currentMessage = currentMessage;
toCopy.currentPosition = currentPosition;
}
/**
* Append current message to the message before.
*/
void copy() {
arraycopy(toCopy.currentMessage.toByteArray(), 0,
toCopy.currentPosition);
toCopy = null;
}
/**
* Mark current message position
*/
PositionMarker mark() {
PositionMarker m = new PositionMarker();
m.c_pos = mPosition;
m.currentStackSize = stackSize;
return m;
}
}
/**
* Check address type.
*
* @param address address string without the postfix stinng type,
* such as "/TYPE=PLMN", "/TYPE=IPv6" and "/TYPE=IPv4"
* @return PDU_PHONE_NUMBER_ADDRESS_TYPE if it is phone number,
* PDU_EMAIL_ADDRESS_TYPE if it is email address,
* PDU_IPV4_ADDRESS_TYPE if it is ipv4 address,
* PDU_IPV6_ADDRESS_TYPE if it is ipv6 address,
* PDU_UNKNOWN_ADDRESS_TYPE if it is unknown.
*/
protected static int checkAddressType(String address) {
/**
* From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf, section 8.
* address = ( e-mail / device-address / alphanum-shortcode / num-shortcode)
* e-mail = mailbox; to the definition of mailbox as described in
* section 3.4 of [RFC2822], but excluding the
* obsolete definitions as indicated by the "obs-" prefix.
* device-address = ( global-phone-number "/TYPE=PLMN" )
* / ( ipv4 "/TYPE=IPv4" ) / ( ipv6 "/TYPE=IPv6" )
* / ( escaped-value "/TYPE=" address-type )
*
* global-phone-number = ["+"] 1*( DIGIT / written-sep )
* written-sep =("-"/".")
*
* ipv4 = 1*3DIGIT 3( "." 1*3DIGIT ) ; IPv4 address value
*
* ipv6 = 4HEXDIG 7( ":" 4HEXDIG ) ; IPv6 address per RFC 2373
*/
if (null == address) {
return PDU_UNKNOWN_ADDRESS_TYPE;
}
if (address.matches(REGEXP_IPV4_ADDRESS_TYPE)) {
// Ipv4 address.
return PDU_IPV4_ADDRESS_TYPE;
}else if (address.matches(REGEXP_PHONE_NUMBER_ADDRESS_TYPE)) {
// Phone number.
return PDU_PHONE_NUMBER_ADDRESS_TYPE;
} else if (address.matches(REGEXP_EMAIL_ADDRESS_TYPE)) {
// Email address.
return PDU_EMAIL_ADDRESS_TYPE;
} else if (address.matches(REGEXP_IPV6_ADDRESS_TYPE)) {
// Ipv6 address.
return PDU_IPV6_ADDRESS_TYPE;
} else {
// Unknown address.
return PDU_UNKNOWN_ADDRESS_TYPE;
}
}
}
| false | true | private int makeMessageBody() {
// 1. add body informations
mStack.newbuf(); // Switching buffer because we need to
PositionMarker ctStart = mStack.mark();
// This contentTypeIdentifier should be used for type of attachment...
String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE));
Integer contentTypeIdentifier = mContentTypeMap.get(contentType);
if (contentTypeIdentifier == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
appendShortInteger(contentTypeIdentifier.intValue());
// content-type parameter: start
PduBody body = ((SendReq) mPdu).getBody();
if (null == body || body.getPartsNum() == 0) {
// empty message
appendUintvarInteger(0);
mStack.pop();
mStack.copy();
return PDU_COMPOSE_SUCCESS;
}
PduPart part;
try {
part = body.getPart(0);
byte[] start = part.getContentId();
if (start != null) {
appendOctet(PduPart.P_DEP_START);
if (('<' == start[0]) && ('>' == start[start.length - 1])) {
appendTextString(start);
} else {
appendTextString("<" + new String(start) + ">");
}
}
// content-type parameter: type
appendOctet(PduPart.P_CT_MR_TYPE);
appendTextString(part.getContentType());
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
int ctLength = ctStart.getLength();
mStack.pop();
appendValueLength(ctLength);
mStack.copy();
// 3. add content
int partNum = body.getPartsNum();
appendUintvarInteger(partNum);
for (int i = 0; i < partNum; i++) {
part = body.getPart(i);
mStack.newbuf(); // Leaving space for header lengh and data length
PositionMarker attachment = mStack.mark();
mStack.newbuf(); // Leaving space for Content-Type length
PositionMarker contentTypeBegin = mStack.mark();
byte[] partContentType = part.getContentType();
if (partContentType == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
// content-type value
Integer partContentTypeIdentifier =
mContentTypeMap.get(new String(partContentType));
if (partContentTypeIdentifier == null) {
appendTextString(partContentType);
} else {
appendShortInteger(partContentTypeIdentifier.intValue());
}
/* Content-type parameter : name.
* The value of name, filename, content-location is the same.
* Just one of them is enough for this PDU.
*/
byte[] name = part.getName();
if (null == name) {
name = part.getFilename();
if (null == name) {
name = part.getContentLocation();
if (null == name) {
/* at lease one of name, filename, Content-location
* should be available.
*/
return PDU_COMPOSE_CONTENT_ERROR;
}
}
}
appendOctet(PduPart.P_DEP_NAME);
appendTextString(name);
// content-type parameter : charset
int charset = part.getCharset();
if (charset != 0) {
appendOctet(PduPart.P_CHARSET);
appendShortInteger(charset);
}
int contentTypeLength = contentTypeBegin.getLength();
mStack.pop();
appendValueLength(contentTypeLength);
mStack.copy();
// content id
byte[] contentId = part.getContentId();
if (null != contentId) {
appendOctet(PduPart.P_CONTENT_ID);
if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) {
appendQuotedString(contentId);
} else {
appendQuotedString("<" + new String(contentId) + ">");
}
}
// content-location
byte[] contentLocation = part.getContentLocation();
if (null != contentLocation) {
appendOctet(PduPart.P_CONTENT_LOCATION);
appendTextString(contentLocation);
}
// content
int headerLength = attachment.getLength();
int dataLength = 0; // Just for safety...
byte[] partData = part.getData();
if (partData != null) {
arraycopy(partData, 0, partData.length);
dataLength = partData.length;
} else {
InputStream cr;
try {
byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE];
cr = mResolver.openInputStream(part.getDataUri());
int len = 0;
while ((len = cr.read(buffer)) != -1) {
mMessage.write(buffer, 0, len);
mPosition += len;
dataLength += len;
}
} catch (FileNotFoundException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (IOException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (RuntimeException e) {
return PDU_COMPOSE_CONTENT_ERROR;
}
}
if (dataLength != (attachment.getLength() - headerLength)) {
throw new RuntimeException("BUG: Length sanity check failed");
}
mStack.pop();
appendUintvarInteger(headerLength);
appendUintvarInteger(dataLength);
mStack.copy();
}
return PDU_COMPOSE_SUCCESS;
}
| private int makeMessageBody() {
// 1. add body informations
mStack.newbuf(); // Switching buffer because we need to
PositionMarker ctStart = mStack.mark();
// This contentTypeIdentifier should be used for type of attachment...
String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE));
Integer contentTypeIdentifier = mContentTypeMap.get(contentType);
if (contentTypeIdentifier == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
appendShortInteger(contentTypeIdentifier.intValue());
// content-type parameter: start
PduBody body = ((SendReq) mPdu).getBody();
if (null == body || body.getPartsNum() == 0) {
// empty message
appendUintvarInteger(0);
mStack.pop();
mStack.copy();
return PDU_COMPOSE_SUCCESS;
}
PduPart part;
try {
part = body.getPart(0);
byte[] start = part.getContentId();
if (start != null) {
appendOctet(PduPart.P_DEP_START);
if (('<' == start[0]) && ('>' == start[start.length - 1])) {
appendTextString(start);
} else {
appendTextString("<" + new String(start) + ">");
}
}
// content-type parameter: type
appendOctet(PduPart.P_CT_MR_TYPE);
appendTextString(part.getContentType());
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
int ctLength = ctStart.getLength();
mStack.pop();
appendValueLength(ctLength);
mStack.copy();
// 3. add content
int partNum = body.getPartsNum();
appendUintvarInteger(partNum);
for (int i = 0; i < partNum; i++) {
part = body.getPart(i);
mStack.newbuf(); // Leaving space for header lengh and data length
PositionMarker attachment = mStack.mark();
mStack.newbuf(); // Leaving space for Content-Type length
PositionMarker contentTypeBegin = mStack.mark();
byte[] partContentType = part.getContentType();
if (partContentType == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
// content-type value
Integer partContentTypeIdentifier =
mContentTypeMap.get(new String(partContentType));
if (partContentTypeIdentifier == null) {
appendTextString(partContentType);
} else {
appendShortInteger(partContentTypeIdentifier.intValue());
}
/* Content-type parameter : name.
* The value of name, filename, content-location is the same.
* Just one of them is enough for this PDU.
*/
byte[] name = part.getName();
if (null == name) {
name = part.getFilename();
if (null == name) {
name = part.getContentLocation();
if (null == name) {
/* at lease one of name, filename, Content-location
* should be available.
*/
return PDU_COMPOSE_CONTENT_ERROR;
}
}
}
appendOctet(PduPart.P_DEP_NAME);
appendTextString(name);
// content-type parameter : charset
int charset = part.getCharset();
if (charset != 0) {
appendOctet(PduPart.P_CHARSET);
appendShortInteger(charset);
}
int contentTypeLength = contentTypeBegin.getLength();
mStack.pop();
appendValueLength(contentTypeLength);
mStack.copy();
// content id
byte[] contentId = part.getContentId();
if (null != contentId) {
appendOctet(PduPart.P_CONTENT_ID);
if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) {
appendQuotedString(contentId);
} else {
appendQuotedString("<" + new String(contentId) + ">");
}
}
// content-location
byte[] contentLocation = part.getContentLocation();
if (null != contentLocation) {
appendOctet(PduPart.P_CONTENT_LOCATION);
appendTextString(contentLocation);
}
// content
int headerLength = attachment.getLength();
int dataLength = 0; // Just for safety...
byte[] partData = part.getData();
if (partData != null) {
arraycopy(partData, 0, partData.length);
dataLength = partData.length;
} else {
InputStream cr = null;
try {
byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE];
cr = mResolver.openInputStream(part.getDataUri());
int len = 0;
while ((len = cr.read(buffer)) != -1) {
mMessage.write(buffer, 0, len);
mPosition += len;
dataLength += len;
}
} catch (FileNotFoundException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (IOException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (RuntimeException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} finally {
if (cr != null) {
try {
cr.close();
} catch (IOException e) {
}
}
}
}
if (dataLength != (attachment.getLength() - headerLength)) {
throw new RuntimeException("BUG: Length sanity check failed");
}
mStack.pop();
appendUintvarInteger(headerLength);
appendUintvarInteger(dataLength);
mStack.copy();
}
return PDU_COMPOSE_SUCCESS;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
index 234a2e998..2ab2ccbe3 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
@@ -1,422 +1,421 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.editors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.internal.tasks.ui.AddExistingTaskJob;
import org.eclipse.mylar.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylar.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylar.internal.tasks.ui.actions.AttachFileAction;
import org.eclipse.mylar.internal.tasks.ui.actions.CopyTaskDetailsAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenWithBrowserAction;
import org.eclipse.mylar.internal.tasks.ui.actions.SynchronizeEditorAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskActivateAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskDeactivateAction;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.AbstractTaskContainer;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.ITaskListElement;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.tasks.ui.editors.AbstractRepositoryTaskEditor;
import org.eclipse.mylar.tasks.ui.editors.NewTaskEditorInput;
import org.eclipse.mylar.tasks.ui.editors.RepositoryTaskEditorInput;
import org.eclipse.mylar.tasks.ui.editors.TaskEditor;
import org.eclipse.mylar.tasks.ui.editors.TaskFormPage;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.SubActionBars;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.internal.ObjectActionContributorManager;
import org.eclipse.ui.internal.WorkbenchImages;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class TaskEditorActionContributor extends MultiPageEditorActionBarContributor implements
ISelectionChangedListener {
private SubActionBars sourceActionBars;
private TaskEditor editor;
private OpenWithBrowserAction openWithBrowserAction = new OpenWithBrowserAction();
private CopyTaskDetailsAction copyTaskDetailsAction = new CopyTaskDetailsAction(false);
private AttachFileAction attachFileAction = new AttachFileAction();
private SynchronizeEditorAction synchronizeEditorAction = new SynchronizeEditorAction();
private GlobalAction cutAction;
private GlobalAction undoAction;
private GlobalAction redoAction;
private GlobalAction copyAction;
private GlobalAction pasteAction;
private GlobalAction selectAllAction;
public TaskEditorActionContributor() {
cutAction = new GlobalAction(ActionFactory.CUT.getId());
cutAction.setText(WorkbenchMessages.Workbench_cut);
cutAction.setToolTipText(WorkbenchMessages.Workbench_cutToolTip);
cutAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
cutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT);
pasteAction = new GlobalAction(ActionFactory.PASTE.getId());
pasteAction.setText(WorkbenchMessages.Workbench_paste);
pasteAction.setToolTipText(WorkbenchMessages.Workbench_pasteToolTip);
pasteAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setDisabledImageDescriptor(WorkbenchImages
.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
pasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
copyAction = new GlobalAction(ActionFactory.COPY.getId());
copyAction.setText(WorkbenchMessages.Workbench_copy);
copyAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
undoAction = new GlobalAction(ActionFactory.UNDO.getId());
undoAction.setText(WorkbenchMessages.Workbench_undo);
undoAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO));
undoAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO));
undoAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO_DISABLED));
undoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.UNDO);
redoAction = new GlobalAction(ActionFactory.REDO.getId());
redoAction.setText(WorkbenchMessages.Workbench_redo);
redoAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
redoAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
redoAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO_DISABLED));
redoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.REDO);
selectAllAction = new GlobalAction(ActionFactory.SELECT_ALL.getId());
selectAllAction.setText(WorkbenchMessages.Workbench_selectAll);
selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL);
selectAllAction.setEnabled(true);
}
public void addClipboardActions(IMenuManager manager) {
manager.add(undoAction);
manager.add(redoAction);
manager.add(new Separator());
manager.add(cutAction);
manager.add(copyAction);
manager.add(copyTaskDetailsAction);
manager.add(pasteAction);
manager.add(selectAllAction);
manager.add(new Separator());
}
public void contextMenuAboutToShow(IMenuManager mng) {
boolean addClipboard = this.getEditor().getActivePageInstance() != null
&& (this.getEditor().getActivePageInstance() instanceof TaskPlanningEditor || this.getEditor()
.getActivePageInstance() instanceof AbstractRepositoryTaskEditor);
contextMenuAboutToShow(mng, addClipboard);
}
public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskContainer> categories = new ArrayList<AbstractTaskContainer>(TasksUiPlugin
.getTaskListManager().getTaskList().getCategories());
// This is added to solve Bug 180252
- categories.add(TasksUiPlugin.getTaskListManager().getTaskList().getUncategorizedCategory());
Collections.sort(categories);
for (final AbstractTaskContainer category : categories) {
if (!category.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final ITask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachFileAction.selectionChanged(selection);
attachFileAction.setEditor(editor);
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
manager.add(openWithBrowserAction);
if (task instanceof AbstractRepositoryTask) {
manager.add(attachFileAction);
manager.add(synchronizeEditorAction);
}
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
List<ITaskListElement> selectedElements = new ArrayList<ITaskListElement>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void moveToCategory(AbstractTaskContainer category) {
IEditorInput input = getEditor().getEditorInput();
if (input instanceof RepositoryTaskEditorInput) {
RepositoryTaskEditorInput repositoryTaskEditorInput = (RepositoryTaskEditorInput) input;
final IProgressService svc = PlatformUI.getWorkbench().getProgressService();
final AddExistingTaskJob job = new AddExistingTaskJob(repositoryTaskEditorInput.getRepository(),
repositoryTaskEditorInput.getId(), category);
job.schedule();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
svc.showInDialog(getEditor().getSite().getShell(), job);
}
});
}
}
public void updateSelectableActions(ISelection selection) {
if (editor != null) {
cutAction.selectionChanged(selection);
copyAction.selectionChanged(selection);
pasteAction.selectionChanged(selection);
undoAction.selectionChanged(selection);
redoAction.selectionChanged(selection);
selectAllAction.selectionChanged(selection);
}
}
@Override
public void contributeToMenu(IMenuManager mm) {
}
@Override
public void contributeToStatusLine(IStatusLineManager slm) {
}
@Override
public void contributeToToolBar(IToolBarManager tbm) {
}
@Override
public void contributeToCoolBar(ICoolBarManager cbm) {
}
@Override
public void dispose() {
sourceActionBars.dispose();
super.dispose();
}
@Override
public void init(IActionBars bars) {
super.init(bars);
sourceActionBars = new SubActionBars(bars);
}
@Override
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
registerGlobalHandlers(bars);
}
public TaskEditor getEditor() {
return editor;
}
public IStatusLineManager getStatusLineManager() {
return getActionBars().getStatusLineManager();
}
@Override
public void setActiveEditor(IEditorPart targetEditor) {
if (targetEditor instanceof TaskEditor) {
editor = (TaskEditor) targetEditor;
updateSelectableActions(editor.getSelection());
}
}
@Override
public void setActivePage(IEditorPart newEditor) {
if (getEditor() != null) {
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(SelectionChangedEvent event) {
updateSelectableActions(event.getSelection());
}
private class GlobalAction extends Action {
private String actionId;
public GlobalAction(String actionId) {
this.actionId = actionId;
}
@Override
public void run() {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
editor.doAction(actionId);
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(ISelection selection) {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
setEnabled(editor.canDoAction(actionId));
}
}
}
public void registerGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), cutAction);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), pasteAction);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), undoAction);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), redoAction);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), selectAllAction);
bars.updateActionBars();
}
public void unregisterGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
bars.updateActionBars();
}
public void forceActionsEnabled() {
cutAction.setEnabled(true);
copyAction.setEnabled(true);
pasteAction.setEnabled(true);
selectAllAction.setEnabled(true);
undoAction.setEnabled(false);
redoAction.setEnabled(false);
}
}
| true | true | public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskContainer> categories = new ArrayList<AbstractTaskContainer>(TasksUiPlugin
.getTaskListManager().getTaskList().getCategories());
// This is added to solve Bug 180252
categories.add(TasksUiPlugin.getTaskListManager().getTaskList().getUncategorizedCategory());
Collections.sort(categories);
for (final AbstractTaskContainer category : categories) {
if (!category.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final ITask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachFileAction.selectionChanged(selection);
attachFileAction.setEditor(editor);
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
manager.add(openWithBrowserAction);
if (task instanceof AbstractRepositoryTask) {
manager.add(attachFileAction);
manager.add(synchronizeEditorAction);
}
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
List<ITaskListElement> selectedElements = new ArrayList<ITaskListElement>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
| public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskContainer> categories = new ArrayList<AbstractTaskContainer>(TasksUiPlugin
.getTaskListManager().getTaskList().getCategories());
// This is added to solve Bug 180252
Collections.sort(categories);
for (final AbstractTaskContainer category : categories) {
if (!category.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final ITask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachFileAction.selectionChanged(selection);
attachFileAction.setEditor(editor);
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
manager.add(openWithBrowserAction);
if (task instanceof AbstractRepositoryTask) {
manager.add(attachFileAction);
manager.add(synchronizeEditorAction);
}
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
List<ITaskListElement> selectedElements = new ArrayList<ITaskListElement>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
|
diff --git a/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java b/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
index 67c816f..d13711e 100644
--- a/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
+++ b/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
@@ -1,153 +1,163 @@
/*
* Copyright 2010 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 com.google.appengine.tools.mapreduce;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An iterator iterating over records in an input stream.
*
* @author [email protected] (Igor Kushnirskiy)
*/
class InputStreamIterator implements Iterator<InputStreamIterator.OffsetRecordPair> {
public static class OffsetRecordPair {
final private long offset;
final private byte[] record;
public OffsetRecordPair(long offset, byte[] record) {
this.offset = offset;
this.record = record;
}
public long getOffset() {
return offset;
}
public byte[] getRecord() {
return record;
}
public boolean equals(Object rhs) {
if (!(rhs instanceof OffsetRecordPair)) {
return false;
}
OffsetRecordPair rhsPair = (OffsetRecordPair) rhs;
return offset == rhsPair.getOffset()
&& Arrays.equals(record, rhsPair.getRecord());
}
public int hashCode() {
return new Long(offset).hashCode() ^ Arrays.hashCode(record);
}
}
private static final Logger log = Logger.getLogger(InputStreamIterator.class.getName());
private static final int READ_LIMIT = 1024 * 1024;
private final CountingInputStream input;
private final long length;
private final boolean skipFirstTerminator;
private final byte terminator;
private OffsetRecordPair currentValue;
// Note: length may be a negative value when we are reading beyond the split boundary.
InputStreamIterator(CountingInputStream input, long length,
boolean skipFirstTerminator, byte terminator) {
this.input = Preconditions.checkNotNull(input);
this.length = length;
this.skipFirstTerminator = skipFirstTerminator;
this.terminator = terminator;
}
// Returns false if the end of stream is reached and no characters have been
// read since the last terminator.
private boolean skipUntilNextRecord(InputStream stream) throws IOException {
boolean readCharSinceTerminator = false;
int value;
do {
value = stream.read();
if (value == -1) {
return readCharSinceTerminator;
}
readCharSinceTerminator = true;
} while (value != (terminator & 0xff));
return true;
}
@Override
public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
+ } else if (byteValue.length > 0
+ && byteValue[byteValue.length - 1] == terminator) {
+ // Lop the terminator off the end if we got the sequence
+ // {record} {terminator} EOF.
+ // Unfortunately, due to our underlying interface, we don't have
+ // enough information to do this without the possibility of a copy
+ // in one of the terminator/non-terminator before EOF cases.
+ byte[] newByteValue = new byte[byteValueLen - 1];
+ System.arraycopy(byteValue, 0, newByteValue, 0, byteValueLen - 1);
+ byteValue = newByteValue;
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
@Override
public OffsetRecordPair next() {
return currentValue;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| true | true | public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
| public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
} else if (byteValue.length > 0
&& byteValue[byteValue.length - 1] == terminator) {
// Lop the terminator off the end if we got the sequence
// {record} {terminator} EOF.
// Unfortunately, due to our underlying interface, we don't have
// enough information to do this without the possibility of a copy
// in one of the terminator/non-terminator before EOF cases.
byte[] newByteValue = new byte[byteValueLen - 1];
System.arraycopy(byteValue, 0, newByteValue, 0, byteValueLen - 1);
byteValue = newByteValue;
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
|
diff --git a/src/com/google/doclava/ClassInfo.java b/src/com/google/doclava/ClassInfo.java
index 77863fd..b97c494 100644
--- a/src/com/google/doclava/ClassInfo.java
+++ b/src/com/google/doclava/ClassInfo.java
@@ -1,1716 +1,1714 @@
/*
* Copyright (C) 2010 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 com.google.doclava;
import com.google.clearsilver.jsilver.data.Data;
import com.google.doclava.apicheck.ApiInfo;
import com.sun.javadoc.*;
import java.util.*;
public class ClassInfo extends DocInfo implements ContainerInfo, Comparable, Scoped {
public static final Comparator<ClassInfo> comparator = new Comparator<ClassInfo>() {
public int compare(ClassInfo a, ClassInfo b) {
return a.name().compareTo(b.name());
}
};
public static final Comparator<ClassInfo> qualifiedComparator = new Comparator<ClassInfo>() {
public int compare(ClassInfo a, ClassInfo b) {
return a.qualifiedName().compareTo(b.qualifiedName());
}
};
/**
* Constructs a stub representation of a class.
*/
public ClassInfo(String qualifiedName) {
super("", SourcePositionInfo.UNKNOWN);
mQualifiedName = qualifiedName;
if (qualifiedName.lastIndexOf('.') != -1) {
mName = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
} else {
mName = qualifiedName;
}
}
public ClassInfo(ClassDoc cl, String rawCommentText, SourcePositionInfo position,
boolean isPublic, boolean isProtected, boolean isPackagePrivate, boolean isPrivate,
boolean isStatic, boolean isInterface, boolean isAbstract, boolean isOrdinaryClass,
boolean isException, boolean isError, boolean isEnum, boolean isAnnotation, boolean isFinal,
boolean isIncluded, String name, String qualifiedName, String qualifiedTypeName,
boolean isPrimitive) {
super(rawCommentText, position);
mClass = cl;
mIsPublic = isPublic;
mIsProtected = isProtected;
mIsPackagePrivate = isPackagePrivate;
mIsPrivate = isPrivate;
mIsStatic = isStatic;
mIsInterface = isInterface;
mIsAbstract = isAbstract;
mIsOrdinaryClass = isOrdinaryClass;
mIsException = isException;
mIsError = isError;
mIsEnum = isEnum;
mIsAnnotation = isAnnotation;
mIsFinal = isFinal;
mIsIncluded = isIncluded;
mName = name;
mQualifiedName = qualifiedName;
mQualifiedTypeName = qualifiedTypeName;
mIsPrimitive = isPrimitive;
mNameParts = name.split("\\.");
}
public void init(TypeInfo typeInfo, ClassInfo[] interfaces, TypeInfo[] interfaceTypes,
ClassInfo[] innerClasses, MethodInfo[] constructors, MethodInfo[] methods,
MethodInfo[] annotationElements, FieldInfo[] fields, FieldInfo[] enumConstants,
PackageInfo containingPackage, ClassInfo containingClass, ClassInfo superclass,
TypeInfo superclassType, AnnotationInstanceInfo[] annotations) {
mTypeInfo = typeInfo;
mRealInterfaces = new ArrayList<ClassInfo>();
for (ClassInfo cl : interfaces) {
mRealInterfaces.add(cl);
}
mRealInterfaceTypes = interfaceTypes;
mInnerClasses = innerClasses;
mAllConstructors = constructors;
mAllSelfMethods = methods;
mAnnotationElements = annotationElements;
mAllSelfFields = fields;
mEnumConstants = enumConstants;
mContainingPackage = containingPackage;
mContainingClass = containingClass;
mRealSuperclass = superclass;
mRealSuperclassType = superclassType;
mAnnotations = annotations;
// after providing new methods and new superclass info,clear any cached
// lists of self + superclass methods, ctors, etc.
mSuperclassInit = false;
mConstructors = null;
mMethods = null;
mSelfMethods = null;
mFields = null;
mSelfFields = null;
mSelfAttributes = null;
mDeprecatedKnown = false;
Arrays.sort(mEnumConstants, FieldInfo.comparator);
Arrays.sort(mInnerClasses, ClassInfo.comparator);
}
public void init2() {
// calling this here forces the AttrTagInfo objects to be linked to the AttribtueInfo
// objects
selfAttributes();
}
public void init3(TypeInfo[] types, ClassInfo[] realInnerClasses) {
mTypeParameters = types;
mRealInnerClasses = realInnerClasses;
}
public ClassInfo[] getRealInnerClasses() {
return mRealInnerClasses;
}
public TypeInfo[] getTypeParameters() {
return mTypeParameters;
}
public boolean checkLevel() {
int val = mCheckLevel;
if (val >= 0) {
return val != 0;
} else {
boolean v =
Doclava.checkLevel(mIsPublic, mIsProtected, mIsPackagePrivate, mIsPrivate, isHidden());
mCheckLevel = v ? 1 : 0;
return v;
}
}
public int compareTo(Object that) {
if (that instanceof ClassInfo) {
return mQualifiedName.compareTo(((ClassInfo) that).mQualifiedName);
} else {
return this.hashCode() - that.hashCode();
}
}
@Override
public ContainerInfo parent() {
return this;
}
public boolean isPublic() {
return mIsPublic;
}
public boolean isProtected() {
return mIsProtected;
}
public boolean isPackagePrivate() {
return mIsPackagePrivate;
}
public boolean isPrivate() {
return mIsPrivate;
}
public boolean isStatic() {
return mIsStatic;
}
public boolean isInterface() {
return mIsInterface;
}
public boolean isAbstract() {
return mIsAbstract;
}
public PackageInfo containingPackage() {
return mContainingPackage;
}
public ClassInfo containingClass() {
return mContainingClass;
}
public boolean isOrdinaryClass() {
return mIsOrdinaryClass;
}
public boolean isException() {
return mIsException;
}
public boolean isError() {
return mIsError;
}
public boolean isEnum() {
return mIsEnum;
}
public boolean isAnnotation() {
return mIsAnnotation;
}
public boolean isFinal() {
return mIsFinal;
}
public boolean isIncluded() {
return mIsIncluded;
}
public HashSet<String> typeVariables() {
HashSet<String> result = TypeInfo.typeVariables(mTypeInfo.typeArguments());
ClassInfo cl = containingClass();
while (cl != null) {
TypeInfo[] types = cl.asTypeInfo().typeArguments();
if (types != null) {
TypeInfo.typeVariables(types, result);
}
cl = cl.containingClass();
}
return result;
}
private static void gatherHiddenInterfaces(ClassInfo cl, HashSet<ClassInfo> interfaces) {
for (ClassInfo iface : cl.mRealInterfaces) {
if (iface.checkLevel()) {
interfaces.add(iface);
} else {
gatherHiddenInterfaces(iface, interfaces);
}
}
}
public ClassInfo[] interfaces() {
if (mInterfaces == null) {
if (checkLevel()) {
HashSet<ClassInfo> interfaces = new HashSet<ClassInfo>();
ClassInfo superclass = mRealSuperclass;
while (superclass != null && !superclass.checkLevel()) {
gatherHiddenInterfaces(superclass, interfaces);
superclass = superclass.mRealSuperclass;
}
gatherHiddenInterfaces(this, interfaces);
mInterfaces = interfaces.toArray(new ClassInfo[interfaces.size()]);
} else {
// put something here in case someone uses it
mInterfaces = new ClassInfo[mRealInterfaces.size()];
mRealInterfaces.toArray(mInterfaces);
}
Arrays.sort(mInterfaces, ClassInfo.qualifiedComparator);
}
return mInterfaces;
}
public ClassInfo[] realInterfaces() {
ClassInfo[] classInfos = new ClassInfo[mRealInterfaces.size()];
return mRealInterfaces.toArray(classInfos);
}
TypeInfo[] realInterfaceTypes() {
return mRealInterfaceTypes;
}
public String name() {
return mName;
}
public String[] nameParts() {
return mNameParts;
}
public String leafName() {
return mNameParts[mNameParts.length - 1];
}
public String qualifiedName() {
return mQualifiedName;
}
public String qualifiedTypeName() {
return mQualifiedTypeName;
}
public boolean isPrimitive() {
return mIsPrimitive;
}
public MethodInfo[] allConstructors() {
return mAllConstructors;
}
public MethodInfo[] constructors() {
if (mConstructors == null) {
MethodInfo[] methods = mAllConstructors;
ArrayList<MethodInfo> ctors = new ArrayList<MethodInfo>();
for (int i = 0; i < methods.length; i++) {
MethodInfo m = methods[i];
if (!m.isHidden()) {
ctors.add(m);
}
}
mConstructors = ctors.toArray(new MethodInfo[ctors.size()]);
Arrays.sort(mConstructors, MethodInfo.comparator);
}
return mConstructors;
}
public ClassInfo[] innerClasses() {
return mInnerClasses;
}
public TagInfo[] inlineTags() {
return comment().tags();
}
public TagInfo[] firstSentenceTags() {
return comment().briefTags();
}
public boolean isDeprecated() {
boolean deprecated = false;
if (!mDeprecatedKnown) {
boolean commentDeprecated = comment().isDeprecated();
boolean annotationDeprecated = false;
for (AnnotationInstanceInfo annotation : annotations()) {
if (annotation.type().qualifiedName().equals("java.lang.Deprecated")) {
annotationDeprecated = true;
break;
}
}
if (commentDeprecated != annotationDeprecated) {
Errors.error(Errors.DEPRECATION_MISMATCH, position(), "Class " + qualifiedName()
+ ": @Deprecated annotation and @deprecated comment do not match");
}
mIsDeprecated = commentDeprecated | annotationDeprecated;
mDeprecatedKnown = true;
}
return mIsDeprecated;
}
public TagInfo[] deprecatedTags() {
// Should we also do the interfaces?
return comment().deprecatedTags();
}
public MethodInfo[] methods() {
if (mMethods == null) {
TreeMap<String, MethodInfo> all = new TreeMap<String, MethodInfo>();
ClassInfo[] ifaces = interfaces();
for (ClassInfo iface : ifaces) {
if (iface != null) {
MethodInfo[] inhereted = iface.methods();
for (MethodInfo method : inhereted) {
String key = method.getHashableName();
all.put(key, method);
}
}
}
ClassInfo superclass = superclass();
if (superclass != null) {
MethodInfo[] inhereted = superclass.methods();
for (MethodInfo method : inhereted) {
String key = method.getHashableName();
all.put(key, method);
}
}
MethodInfo[] methods = selfMethods();
for (MethodInfo method : methods) {
String key = method.getHashableName();
all.put(key, method);
}
mMethods = all.values().toArray(new MethodInfo[all.size()]);
Arrays.sort(mMethods, MethodInfo.comparator);
}
return mMethods;
}
public MethodInfo[] annotationElements() {
return mAnnotationElements;
}
public AnnotationInstanceInfo[] annotations() {
return mAnnotations;
}
private static void addFields(ClassInfo cl, TreeMap<String, FieldInfo> all) {
FieldInfo[] fields = cl.fields();
int N = fields.length;
for (int i = 0; i < N; i++) {
FieldInfo f = fields[i];
all.put(f.name(), f);
}
}
public FieldInfo[] fields() {
if (mFields == null) {
int N;
TreeMap<String, FieldInfo> all = new TreeMap<String, FieldInfo>();
ClassInfo[] interfaces = interfaces();
N = interfaces.length;
for (int i = 0; i < N; i++) {
addFields(interfaces[i], all);
}
ClassInfo superclass = superclass();
if (superclass != null) {
addFields(superclass, all);
}
FieldInfo[] fields = selfFields();
N = fields.length;
for (int i = 0; i < N; i++) {
FieldInfo f = fields[i];
if (!f.isHidden()) {
String key = f.name();
all.put(key, f);
}
}
mFields = all.values().toArray(new FieldInfo[0]);
}
return mFields;
}
public void gatherFields(ClassInfo owner, ClassInfo cl, HashMap<String, FieldInfo> fields) {
FieldInfo[] flds = cl.selfFields();
for (FieldInfo f : flds) {
if (f.checkLevel()) {
fields.put(f.name(), f.cloneForClass(owner));
}
}
}
public FieldInfo[] selfFields() {
if (mSelfFields == null) {
HashMap<String, FieldInfo> fields = new HashMap<String, FieldInfo>();
// our hidden parents
if (mRealSuperclass != null && !mRealSuperclass.checkLevel()) {
gatherFields(this, mRealSuperclass, fields);
}
for (ClassInfo iface : mRealInterfaces) {
if (!iface.checkLevel()) {
gatherFields(this, iface, fields);
}
}
// mine
FieldInfo[] selfFields = mAllSelfFields;
for (int i = 0; i < selfFields.length; i++) {
FieldInfo f = selfFields[i];
if (!f.isHidden()) {
fields.put(f.name(), f);
}
}
// combine and return in
mSelfFields = fields.values().toArray(new FieldInfo[fields.size()]);
Arrays.sort(mSelfFields, FieldInfo.comparator);
}
return mSelfFields;
}
public FieldInfo[] allSelfFields() {
return mAllSelfFields;
}
private void gatherMethods(ClassInfo owner, ClassInfo cl, HashMap<String, MethodInfo> methods) {
MethodInfo[] meth = cl.selfMethods();
for (MethodInfo m : meth) {
if (m.checkLevel()) {
methods.put(m.name() + m.signature(), m.cloneForClass(owner));
}
}
}
public MethodInfo[] selfMethods() {
if (mSelfMethods == null) {
HashMap<String, MethodInfo> methods = new HashMap<String, MethodInfo>();
// our hidden parents
if (mRealSuperclass != null && !mRealSuperclass.checkLevel()) {
gatherMethods(this, mRealSuperclass, methods);
}
for (ClassInfo iface : mRealInterfaces) {
if (!iface.checkLevel()) {
gatherMethods(this, iface, methods);
}
}
// mine
if (mAllSelfMethods != null) {
for (int i = 0; i < mAllSelfMethods.length; i++) {
MethodInfo m = mAllSelfMethods[i];
if (m.checkLevel()) {
methods.put(m.name() + m.signature(), m);
}
}
}
// combine and return it
mSelfMethods = methods.values().toArray(new MethodInfo[methods.size()]);
Arrays.sort(mSelfMethods, MethodInfo.comparator);
}
return mSelfMethods;
}
public MethodInfo[] allSelfMethods() {
return mAllSelfMethods;
}
public void addMethod(MethodInfo method) {
mApiCheckMethods.put(method.getHashableName(), method);
if (mAllSelfMethods == null) {
mAllSelfMethods = new MethodInfo[] { method };
return;
}
MethodInfo[] methods = new MethodInfo[mAllSelfMethods.length + 1];
int i = 0;
for (MethodInfo m : mAllSelfMethods) {
methods[i++] = m;
}
methods[i] = method;
mAllSelfMethods = methods;
}
public void setContainingPackage(PackageInfo pkg) {
mContainingPackage = pkg;
}
public AttributeInfo[] selfAttributes() {
if (mSelfAttributes == null) {
TreeMap<FieldInfo, AttributeInfo> attrs = new TreeMap<FieldInfo, AttributeInfo>();
// the ones in the class comment won't have any methods
for (AttrTagInfo tag : comment().attrTags()) {
FieldInfo field = tag.reference();
if (field != null) {
AttributeInfo attr = attrs.get(field);
if (attr == null) {
attr = new AttributeInfo(this, field);
attrs.put(field, attr);
}
tag.setAttribute(attr);
}
}
// in the methods
for (MethodInfo m : selfMethods()) {
for (AttrTagInfo tag : m.comment().attrTags()) {
FieldInfo field = tag.reference();
if (field != null) {
AttributeInfo attr = attrs.get(field);
if (attr == null) {
attr = new AttributeInfo(this, field);
attrs.put(field, attr);
}
tag.setAttribute(attr);
attr.methods.add(m);
}
}
}
// constructors too
for (MethodInfo m : constructors()) {
for (AttrTagInfo tag : m.comment().attrTags()) {
FieldInfo field = tag.reference();
if (field != null) {
AttributeInfo attr = attrs.get(field);
if (attr == null) {
attr = new AttributeInfo(this, field);
attrs.put(field, attr);
}
tag.setAttribute(attr);
attr.methods.add(m);
}
}
}
mSelfAttributes = attrs.values().toArray(new AttributeInfo[attrs.size()]);
Arrays.sort(mSelfAttributes, AttributeInfo.comparator);
}
return mSelfAttributes;
}
public FieldInfo[] enumConstants() {
return mEnumConstants;
}
public ClassInfo superclass() {
if (!mSuperclassInit) {
if (this.checkLevel()) {
// rearrange our little inheritance hierarchy, because we need to hide classes that
// don't pass checkLevel
ClassInfo superclass = mRealSuperclass;
while (superclass != null && !superclass.checkLevel()) {
superclass = superclass.mRealSuperclass;
}
mSuperclass = superclass;
} else {
mSuperclass = mRealSuperclass;
}
}
return mSuperclass;
}
public ClassInfo realSuperclass() {
return mRealSuperclass;
}
/**
* always the real superclass, not the collapsed one we get through superclass(), also has the
* type parameter info if it's generic.
*/
public TypeInfo superclassType() {
return mRealSuperclassType;
}
public TypeInfo asTypeInfo() {
return mTypeInfo;
}
TypeInfo[] interfaceTypes() {
ClassInfo[] infos = interfaces();
int len = infos.length;
TypeInfo[] types = new TypeInfo[len];
for (int i = 0; i < len; i++) {
types[i] = infos[i].asTypeInfo();
}
return types;
}
public String htmlPage() {
String s = containingPackage().name();
s = s.replace('.', '/');
s += '/';
s += name();
s += ".html";
s = Doclava.javadocDir + s;
return s;
}
/** Even indirectly */
public boolean isDerivedFrom(ClassInfo cl) {
ClassInfo dad = this.superclass();
if (dad != null) {
if (dad.equals(cl)) {
return true;
} else {
if (dad.isDerivedFrom(cl)) {
return true;
}
}
}
for (ClassInfo iface : interfaces()) {
if (iface.equals(cl)) {
return true;
} else {
if (iface.isDerivedFrom(cl)) {
return true;
}
}
}
return false;
}
public void makeKeywordEntries(List<KeywordEntry> keywords) {
if (!checkLevel()) {
return;
}
String htmlPage = htmlPage();
String qualifiedName = qualifiedName();
keywords.add(new KeywordEntry(name(), htmlPage, "class in " + containingPackage().name()));
FieldInfo[] fields = selfFields();
FieldInfo[] enumConstants = enumConstants();
MethodInfo[] ctors = constructors();
MethodInfo[] methods = selfMethods();
// enum constants
for (FieldInfo field : enumConstants()) {
if (field.checkLevel()) {
keywords.add(new KeywordEntry(field.name(), htmlPage + "#" + field.anchor(),
"enum constant in " + qualifiedName));
}
}
// constants
for (FieldInfo field : fields) {
if (field.isConstant() && field.checkLevel()) {
keywords.add(new KeywordEntry(field.name(), htmlPage + "#" + field.anchor(), "constant in "
+ qualifiedName));
}
}
// fields
for (FieldInfo field : fields) {
if (!field.isConstant() && field.checkLevel()) {
keywords.add(new KeywordEntry(field.name(), htmlPage + "#" + field.anchor(), "field in "
+ qualifiedName));
}
}
// public constructors
for (MethodInfo m : ctors) {
if (m.isPublic() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.prettySignature(), htmlPage + "#" + m.anchor(),
"constructor in " + qualifiedName));
}
}
// protected constructors
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
for (MethodInfo m : ctors) {
if (m.isProtected() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.prettySignature(),
htmlPage + "#" + m.anchor(), "constructor in " + qualifiedName));
}
}
}
// package private constructors
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
for (MethodInfo m : ctors) {
if (m.isPackagePrivate() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.prettySignature(),
htmlPage + "#" + m.anchor(), "constructor in " + qualifiedName));
}
}
}
// private constructors
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
for (MethodInfo m : ctors) {
if (m.isPrivate() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.name() + m.prettySignature(),
htmlPage + "#" + m.anchor(), "constructor in " + qualifiedName));
}
}
}
// public methods
for (MethodInfo m : methods) {
if (m.isPublic() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.name() + m.prettySignature(), htmlPage + "#" + m.anchor(),
"method in " + qualifiedName));
}
}
// protected methods
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
for (MethodInfo m : methods) {
if (m.isProtected() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.name() + m.prettySignature(),
htmlPage + "#" + m.anchor(), "method in " + qualifiedName));
}
}
}
// package private methods
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
for (MethodInfo m : methods) {
if (m.isPackagePrivate() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.name() + m.prettySignature(),
htmlPage + "#" + m.anchor(), "method in " + qualifiedName));
}
}
}
// private methods
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
for (MethodInfo m : methods) {
if (m.isPrivate() && m.checkLevel()) {
keywords.add(new KeywordEntry(m.name() + m.prettySignature(),
htmlPage + "#" + m.anchor(), "method in " + qualifiedName));
}
}
}
}
public void makeLink(Data data, String base) {
data.setValue(base + ".label", this.name());
if (!this.isPrimitive() && this.isIncluded() && this.checkLevel()) {
data.setValue(base + ".link", this.htmlPage());
}
}
public static void makeLinkListHDF(Data data, String base, ClassInfo[] classes) {
final int N = classes.length;
for (int i = 0; i < N; i++) {
ClassInfo cl = classes[i];
if (cl.checkLevel()) {
cl.asTypeInfo().makeHDF(data, base + "." + i);
}
}
}
/**
* Used in lists of this class (packages, nested classes, known subclasses)
*/
public void makeShortDescrHDF(Data data, String base) {
mTypeInfo.makeHDF(data, base + ".type");
data.setValue(base + ".kind", this.kind());
TagInfo.makeHDF(data, base + ".shortDescr", this.firstSentenceTags());
TagInfo.makeHDF(data, base + ".deprecated", deprecatedTags());
data.setValue(base + ".since", getSince());
setFederatedReferences(data, base);
}
/**
* Turns into the main class page
*/
public void makeHDF(Data data) {
int i, j, n;
String name = name();
String qualified = qualifiedName();
AttributeInfo[] selfAttributes = selfAttributes();
MethodInfo[] methods = selfMethods();
FieldInfo[] fields = selfFields();
FieldInfo[] enumConstants = enumConstants();
MethodInfo[] ctors = constructors();
ClassInfo[] inners = innerClasses();
// class name
mTypeInfo.makeHDF(data, "class.type");
mTypeInfo.makeQualifiedHDF(data, "class.qualifiedType");
data.setValue("class.name", name);
data.setValue("class.qualified", qualified);
String scope = "";
if (isProtected()) {
data.setValue("class.scope", "protected");
} else if (isPublic()) {
data.setValue("class.scope", "public");
}
if (isStatic()) {
data.setValue("class.static", "static");
}
if (isFinal()) {
data.setValue("class.final", "final");
}
if (isAbstract() && !isInterface()) {
data.setValue("class.abstract", "abstract");
}
// class info
String kind = kind();
if (kind != null) {
data.setValue("class.kind", kind);
}
data.setValue("class.since", getSince());
setFederatedReferences(data, "class");
// the containing package -- note that this can be passed to type_link,
// but it also contains the list of all of the packages
containingPackage().makeClassLinkListHDF(data, "class.package");
// inheritance hierarchy
Vector<ClassInfo> superClasses = new Vector<ClassInfo>();
superClasses.add(this);
ClassInfo supr = superclass();
while (supr != null) {
superClasses.add(supr);
supr = supr.superclass();
}
n = superClasses.size();
for (i = 0; i < n; i++) {
supr = superClasses.elementAt(n - i - 1);
supr.asTypeInfo().makeQualifiedHDF(data, "class.inheritance." + i + ".class");
supr.asTypeInfo().makeHDF(data, "class.inheritance." + i + ".short_class");
j = 0;
for (TypeInfo t : supr.interfaceTypes()) {
t.makeHDF(data, "class.inheritance." + i + ".interfaces." + j);
j++;
}
}
// class description
TagInfo.makeHDF(data, "class.descr", inlineTags());
TagInfo.makeHDF(data, "class.seeAlso", comment().seeTags());
TagInfo.makeHDF(data, "class.deprecated", deprecatedTags());
// known subclasses
TreeMap<String, ClassInfo> direct = new TreeMap<String, ClassInfo>();
TreeMap<String, ClassInfo> indirect = new TreeMap<String, ClassInfo>();
ClassInfo[] all = Converter.rootClasses();
for (ClassInfo cl : all) {
if (cl.superclass() != null && cl.superclass().equals(this)) {
direct.put(cl.name(), cl);
} else if (cl.isDerivedFrom(this)) {
indirect.put(cl.name(), cl);
}
}
// direct
i = 0;
for (ClassInfo cl : direct.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.direct." + i);
}
i++;
}
// indirect
i = 0;
for (ClassInfo cl : indirect.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.indirect." + i);
}
i++;
}
// hide special cases
if ("java.lang.Object".equals(qualified) || "java.io.Serializable".equals(qualified)) {
data.setValue("class.subclasses.hidden", "1");
} else {
data.setValue("class.subclasses.hidden", "0");
}
// nested classes
i = 0;
for (ClassInfo inner : inners) {
if (inner.checkLevel()) {
inner.makeShortDescrHDF(data, "class.inners." + i);
}
i++;
}
// enum constants
i = 0;
for (FieldInfo field : enumConstants) {
- if (field.isConstant()) {
- field.makeHDF(data, "class.enumConstants." + i);
- i++;
- }
+ field.makeHDF(data, "class.enumConstants." + i);
+ i++;
}
// constants
i = 0;
for (FieldInfo field : fields) {
if (field.isConstant()) {
field.makeHDF(data, "class.constants." + i);
i++;
}
}
// fields
i = 0;
for (FieldInfo field : fields) {
if (!field.isConstant()) {
field.makeHDF(data, "class.fields." + i);
i++;
}
}
// public constructors
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPublic()) {
ctor.makeHDF(data, "class.ctors.public." + i);
i++;
}
}
// protected constructors
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isProtected()) {
ctor.makeHDF(data, "class.ctors.protected." + i);
i++;
}
}
}
// package private constructors
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPackagePrivate()) {
ctor.makeHDF(data, "class.ctors.package." + i);
i++;
}
}
}
// private constructors
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPrivate()) {
ctor.makeHDF(data, "class.ctors.private." + i);
i++;
}
}
}
// public methods
i = 0;
for (MethodInfo method : methods) {
if (method.isPublic()) {
method.makeHDF(data, "class.methods.public." + i);
i++;
}
}
// protected methods
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isProtected()) {
method.makeHDF(data, "class.methods.protected." + i);
i++;
}
}
}
// package private methods
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPackagePrivate()) {
method.makeHDF(data, "class.methods.package." + i);
i++;
}
}
}
// private methods
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPrivate()) {
method.makeHDF(data, "class.methods.private." + i);
i++;
}
}
}
// xml attributes
i = 0;
for (AttributeInfo attr : selfAttributes) {
if (attr.checkLevel()) {
attr.makeHDF(data, "class.attrs." + i);
i++;
}
}
// inherited methods
Set<ClassInfo> interfaces = new TreeSet<ClassInfo>();
addInterfaces(interfaces(), interfaces);
ClassInfo cl = superclass();
i = 0;
while (cl != null) {
addInterfaces(cl.interfaces(), interfaces);
makeInheritedHDF(data, i, cl);
cl = cl.superclass();
i++;
}
for (ClassInfo iface : interfaces) {
makeInheritedHDF(data, i, iface);
i++;
}
}
private static void addInterfaces(ClassInfo[] ifaces, Set<ClassInfo> out) {
for (ClassInfo cl : ifaces) {
out.add(cl);
addInterfaces(cl.interfaces(), out);
}
}
private static void makeInheritedHDF(Data data, int index, ClassInfo cl) {
int i;
String base = "class.inherited." + index;
data.setValue(base + ".qualified", cl.qualifiedName());
if (cl.checkLevel()) {
data.setValue(base + ".link", cl.htmlPage());
}
String kind = cl.kind();
if (kind != null) {
data.setValue(base + ".kind", kind);
}
if (cl.mIsIncluded) {
data.setValue(base + ".included", "true");
} else {
Doclava.federationTagger.tagAll(new ClassInfo[] {cl});
if (!cl.getFederatedReferences().isEmpty()) {
FederatedSite site = cl.getFederatedReferences().iterator().next();
data.setValue(base + ".link", site.linkFor(cl.htmlPage()));
data.setValue(base + ".federated", site.name());
}
}
// xml attributes
i = 0;
for (AttributeInfo attr : cl.selfAttributes()) {
attr.makeHDF(data, base + ".attrs." + i);
i++;
}
// methods
i = 0;
for (MethodInfo method : cl.selfMethods()) {
method.makeHDF(data, base + ".methods." + i);
i++;
}
// fields
i = 0;
for (FieldInfo field : cl.selfFields()) {
if (!field.isConstant()) {
field.makeHDF(data, base + ".fields." + i);
i++;
}
}
// constants
i = 0;
for (FieldInfo field : cl.selfFields()) {
if (field.isConstant()) {
field.makeHDF(data, base + ".constants." + i);
i++;
}
}
}
@Override
public boolean isHidden() {
int val = mHidden;
if (val >= 0) {
return val != 0;
} else {
boolean v = isHiddenImpl();
mHidden = v ? 1 : 0;
return v;
}
}
public boolean isHiddenImpl() {
ClassInfo cl = this;
while (cl != null) {
PackageInfo pkg = cl.containingPackage();
if (pkg != null && pkg.isHidden()) {
return true;
}
if (cl.comment().isHidden()) {
return true;
}
cl = cl.containingClass();
}
return false;
}
private MethodInfo matchMethod(MethodInfo[] methods, String name, String[] params,
String[] dimensions, boolean varargs) {
int len = methods.length;
for (int i = 0; i < len; i++) {
MethodInfo method = methods[i];
if (method.name().equals(name)) {
if (params == null) {
return method;
} else {
if (method.matchesParams(params, dimensions, varargs)) {
return method;
}
}
}
}
return null;
}
public MethodInfo findMethod(String name, String[] params, String[] dimensions, boolean varargs) {
// first look on our class, and our superclasses
// for methods
MethodInfo rv;
rv = matchMethod(methods(), name, params, dimensions, varargs);
if (rv != null) {
return rv;
}
// for constructors
rv = matchMethod(constructors(), name, params, dimensions, varargs);
if (rv != null) {
return rv;
}
// then recursively look at our containing class
ClassInfo containing = containingClass();
if (containing != null) {
return containing.findMethod(name, params, dimensions, varargs);
}
return null;
}
public boolean supportsMethod(MethodInfo method) {
for (MethodInfo m : methods()) {
if (m.getHashableName().equals(method.getHashableName())) {
return true;
}
}
return false;
}
private ClassInfo searchInnerClasses(String[] nameParts, int index) {
String part = nameParts[index];
ClassInfo[] inners = mInnerClasses;
for (ClassInfo in : inners) {
String[] innerParts = in.nameParts();
if (part.equals(innerParts[innerParts.length - 1])) {
if (index == nameParts.length - 1) {
return in;
} else {
return in.searchInnerClasses(nameParts, index + 1);
}
}
}
return null;
}
public ClassInfo extendedFindClass(String className) {
// ClassDoc.findClass has this bug that we're working around here:
// If you have a class PackageManager with an inner class PackageInfo
// and you call it with "PackageInfo" it doesn't find it.
return searchInnerClasses(className.split("\\."), 0);
}
public ClassInfo findClass(String className) {
return Converter.obtainClass(mClass.findClass(className));
}
public ClassInfo findInnerClass(String className) {
// ClassDoc.findClass won't find inner classes. To deal with that,
// we try what they gave us first, but if that didn't work, then
// we see if there are any periods in className, and start searching
// from there.
String[] nodes = className.split("\\.");
ClassDoc cl = mClass;
for (String n : nodes) {
cl = cl.findClass(n);
if (cl == null) {
return null;
}
}
return Converter.obtainClass(cl);
}
public FieldInfo findField(String name) {
// first look on our class, and our superclasses
for (FieldInfo f : fields()) {
if (f.name().equals(name)) {
return f;
}
}
// then look at our enum constants (these are really fields, maybe
// they should be mixed into fields(). not sure)
for (FieldInfo f : enumConstants()) {
if (f.name().equals(name)) {
return f;
}
}
// then recursively look at our containing class
ClassInfo containing = containingClass();
if (containing != null) {
return containing.findField(name);
}
return null;
}
public static ClassInfo[] sortByName(ClassInfo[] classes) {
int i;
Sorter[] sorted = new Sorter[classes.length];
for (i = 0; i < sorted.length; i++) {
ClassInfo cl = classes[i];
sorted[i] = new Sorter(cl.name(), cl);
}
Arrays.sort(sorted);
ClassInfo[] rv = new ClassInfo[classes.length];
for (i = 0; i < rv.length; i++) {
rv[i] = (ClassInfo) sorted[i].data;
}
return rv;
}
public boolean equals(ClassInfo that) {
if (that != null) {
return this.qualifiedName().equals(that.qualifiedName());
} else {
return false;
}
}
public void setNonWrittenConstructors(MethodInfo[] nonWritten) {
mNonWrittenConstructors = nonWritten;
}
public MethodInfo[] getNonWrittenConstructors() {
return mNonWrittenConstructors;
}
public String kind() {
if (isOrdinaryClass()) {
return "class";
} else if (isInterface()) {
return "interface";
} else if (isEnum()) {
return "enum";
} else if (isError()) {
return "class";
} else if (isException()) {
return "class";
} else if (isAnnotation()) {
return "@interface";
}
return null;
}
public String scope() {
if (isPublic()) {
return "public";
} else if (isProtected()) {
return "protected";
} else if (isPackagePrivate()) {
return "";
} else if (isPrivate()) {
return "private";
} else {
throw new RuntimeException("invalid scope for object " + this);
}
}
public void setHiddenMethods(MethodInfo[] mInfo) {
mHiddenMethods = mInfo;
}
public MethodInfo[] getHiddenMethods() {
return mHiddenMethods;
}
@Override
public String toString() {
return this.qualifiedName();
}
public void setReasonIncluded(String reason) {
mReasonIncluded = reason;
}
public String getReasonIncluded() {
return mReasonIncluded;
}
private ClassDoc mClass;
// ctor
private boolean mIsPublic;
private boolean mIsProtected;
private boolean mIsPackagePrivate;
private boolean mIsPrivate;
private boolean mIsStatic;
private boolean mIsInterface;
private boolean mIsAbstract;
private boolean mIsOrdinaryClass;
private boolean mIsException;
private boolean mIsError;
private boolean mIsEnum;
private boolean mIsAnnotation;
private boolean mIsFinal;
private boolean mIsIncluded;
private String mName;
private String mQualifiedName;
private String mQualifiedTypeName;
private boolean mIsPrimitive;
private TypeInfo mTypeInfo;
private String[] mNameParts;
// init
private List<ClassInfo> mRealInterfaces = new ArrayList<ClassInfo>();
private ClassInfo[] mInterfaces;
private TypeInfo[] mRealInterfaceTypes;
private ClassInfo[] mInnerClasses;
private MethodInfo[] mAllConstructors;
private MethodInfo[] mAllSelfMethods;
private MethodInfo[] mAnnotationElements; // if this class is an annotation
private FieldInfo[] mAllSelfFields;
private FieldInfo[] mEnumConstants;
private PackageInfo mContainingPackage;
private ClassInfo mContainingClass;
private ClassInfo mRealSuperclass;
private TypeInfo mRealSuperclassType;
private ClassInfo mSuperclass;
private AnnotationInstanceInfo[] mAnnotations;
private boolean mSuperclassInit;
private boolean mDeprecatedKnown;
// lazy
private MethodInfo[] mConstructors;
private ClassInfo[] mRealInnerClasses;
private MethodInfo[] mSelfMethods;
private FieldInfo[] mSelfFields;
private AttributeInfo[] mSelfAttributes;
private MethodInfo[] mMethods;
private FieldInfo[] mFields;
private TypeInfo[] mTypeParameters;
private MethodInfo[] mHiddenMethods;
private int mHidden = -1;
private int mCheckLevel = -1;
private String mReasonIncluded;
private MethodInfo[] mNonWrittenConstructors;
private boolean mIsDeprecated;
// TODO: Temporary members from apicheck migration.
private HashMap<String, MethodInfo> mApiCheckMethods = new HashMap<String, MethodInfo>();
private HashMap<String, FieldInfo> mApiCheckFields = new HashMap<String, FieldInfo>();
private HashMap<String, ConstructorInfo> mApiCheckConstructors
= new HashMap<String, ConstructorInfo>();
/**
* Returns true if {@code cl} implements the interface {@code iface} either by either being that
* interface, implementing that interface or extending a type that implements the interface.
*/
private boolean implementsInterface(ClassInfo cl, String iface) {
if (cl.qualifiedName().equals(iface)) {
return true;
}
for (ClassInfo clImplements : cl.interfaces()) {
if (implementsInterface(clImplements, iface)) {
return true;
}
}
if (cl.mSuperclass != null && implementsInterface(cl.mSuperclass, iface)) {
return true;
}
return false;
}
public void addInterface(ClassInfo iface) {
mRealInterfaces.add(iface);
}
public void addConstructor(ConstructorInfo cInfo) {
mApiCheckConstructors.put(cInfo.getHashableName(), cInfo);
}
public void addField(FieldInfo fInfo) {
mApiCheckFields.put(fInfo.name(), fInfo);
}
public void setSuperClass(ClassInfo superclass) {
mSuperclass = superclass;
}
public Map<String, ConstructorInfo> allConstructorsMap() {
return mApiCheckConstructors;
}
public Map<String, FieldInfo> allFields() {
return mApiCheckFields;
}
/**
* Returns all methods defined directly in this class. For a list of all
* methods supported by this class, see {@link #methods()}.
*/
public Map<String, MethodInfo> allMethods() {
return mApiCheckMethods;
}
/**
* Returns the class hierarchy for this class, starting with this class.
*/
public Iterable<ClassInfo> hierarchy() {
List<ClassInfo> result = new ArrayList<ClassInfo>(4);
for (ClassInfo c = this; c != null; c = c.mSuperclass) {
result.add(c);
}
return result;
}
public String superclassName() {
if (mSuperclass == null) {
if (mQualifiedName.equals("java.lang.Object")) {
return null;
}
throw new UnsupportedOperationException("Superclass not set for " + qualifiedName());
}
return mSuperclass.mQualifiedName;
}
public void setAnnotations(AnnotationInstanceInfo[] annotations) {
mAnnotations = annotations;
}
public boolean isConsistent(ClassInfo cl) {
boolean consistent = true;
if (isInterface() != cl.isInterface()) {
Errors.error(Errors.CHANGED_CLASS, cl.position(), "Class " + cl.qualifiedName()
+ " changed class/interface declaration");
consistent = false;
}
for (ClassInfo iface : mRealInterfaces) {
if (!implementsInterface(cl, iface.mQualifiedName)) {
Errors.error(Errors.REMOVED_INTERFACE, cl.position(), "Class " + qualifiedName()
+ " no longer implements " + iface);
}
}
for (ClassInfo iface : cl.mRealInterfaces) {
if (!implementsInterface(this, iface.mQualifiedName)) {
Errors.error(Errors.ADDED_INTERFACE, cl.position(), "Added interface " + iface
+ " to class " + qualifiedName());
consistent = false;
}
}
for (MethodInfo mInfo : mApiCheckMethods.values()) {
if (cl.mApiCheckMethods.containsKey(mInfo.getHashableName())) {
if (!mInfo.isConsistent(cl.mApiCheckMethods.get(mInfo.getHashableName()))) {
consistent = false;
}
} else {
/*
* This class formerly provided this method directly, and now does not. Check our ancestry
* to see if there's an inherited version that still fulfills the API requirement.
*/
MethodInfo mi = ClassInfo.overriddenMethod(mInfo, cl);
if (mi == null) {
mi = ClassInfo.interfaceMethod(mInfo, cl);
}
if (mi == null) {
Errors.error(Errors.REMOVED_METHOD, mInfo.position(), "Removed public method "
+ mInfo.qualifiedName());
consistent = false;
}
}
}
for (MethodInfo mInfo : cl.mApiCheckMethods.values()) {
if (!mApiCheckMethods.containsKey(mInfo.getHashableName())) {
/*
* Similarly to the above, do not fail if this "new" method is really an override of an
* existing superclass method.
*/
MethodInfo mi = ClassInfo.overriddenMethod(mInfo, this);
if (mi == null) {
Errors.error(Errors.ADDED_METHOD, mInfo.position(), "Added public method "
+ mInfo.qualifiedName());
consistent = false;
}
}
}
for (ConstructorInfo mInfo : mApiCheckConstructors.values()) {
if (cl.mApiCheckConstructors.containsKey(mInfo.getHashableName())) {
if (!mInfo.isConsistent(cl.mApiCheckConstructors.get(mInfo.getHashableName()))) {
consistent = false;
}
} else {
Errors.error(Errors.REMOVED_METHOD, mInfo.position(), "Removed public constructor "
+ mInfo.prettySignature());
consistent = false;
}
}
for (ConstructorInfo mInfo : cl.mApiCheckConstructors.values()) {
if (!mApiCheckConstructors.containsKey(mInfo.getHashableName())) {
Errors.error(Errors.ADDED_METHOD, mInfo.position(), "Added public constructor "
+ mInfo.prettySignature());
consistent = false;
}
}
for (FieldInfo mInfo : mApiCheckFields.values()) {
if (cl.mApiCheckFields.containsKey(mInfo.name())) {
if (!mInfo.isConsistent(cl.mApiCheckFields.get(mInfo.name()))) {
consistent = false;
}
} else {
Errors.error(Errors.REMOVED_FIELD, mInfo.position(), "Removed field "
+ mInfo.qualifiedName());
consistent = false;
}
}
for (FieldInfo mInfo : cl.mApiCheckFields.values()) {
if (!mApiCheckFields.containsKey(mInfo.name())) {
Errors.error(Errors.ADDED_FIELD, mInfo.position(), "Added public field "
+ mInfo.qualifiedName());
consistent = false;
}
}
if (mIsAbstract != cl.mIsAbstract) {
consistent = false;
Errors.error(Errors.CHANGED_ABSTRACT, cl.position(), "Class " + cl.qualifiedName()
+ " changed abstract qualifier");
}
if (mIsFinal != cl.mIsFinal) {
consistent = false;
Errors.error(Errors.CHANGED_FINAL, cl.position(), "Class " + cl.qualifiedName()
+ " changed final qualifier");
}
if (mIsStatic != cl.mIsStatic) {
consistent = false;
Errors.error(Errors.CHANGED_STATIC, cl.position(), "Class " + cl.qualifiedName()
+ " changed static qualifier");
}
if (!scope().equals(cl.scope())) {
consistent = false;
Errors.error(Errors.CHANGED_SCOPE, cl.position(), "Class " + cl.qualifiedName()
+ " scope changed from " + scope() + " to " + cl.scope());
}
if (!isDeprecated() == cl.isDeprecated()) {
consistent = false;
Errors.error(Errors.CHANGED_DEPRECATED, cl.position(), "Class " + cl.qualifiedName()
+ " has changed deprecation state");
}
if (superclassName() != null) {
if (cl.superclassName() == null || !superclassName().equals(cl.superclassName())) {
consistent = false;
Errors.error(Errors.CHANGED_SUPERCLASS, cl.position(), "Class " + qualifiedName()
+ " superclass changed from " + superclassName() + " to " + cl.superclassName());
}
} else if (cl.superclassName() != null) {
consistent = false;
Errors.error(Errors.CHANGED_SUPERCLASS, cl.position(), "Class " + qualifiedName()
+ " superclass changed from " + "null to " + cl.superclassName());
}
return consistent;
}
// Find a superclass implementation of the given method.
public static MethodInfo overriddenMethod(MethodInfo candidate, ClassInfo newClassObj) {
if (newClassObj == null) {
return null;
}
for (MethodInfo mi : newClassObj.mApiCheckMethods.values()) {
if (mi.matches(candidate)) {
// found it
return mi;
}
}
// not found here. recursively search ancestors
return ClassInfo.overriddenMethod(candidate, newClassObj.mSuperclass);
}
// Find a superinterface declaration of the given method.
public static MethodInfo interfaceMethod(MethodInfo candidate, ClassInfo newClassObj) {
if (newClassObj == null) {
return null;
}
for (ClassInfo interfaceInfo : newClassObj.interfaces()) {
for (MethodInfo mi : interfaceInfo.mApiCheckMethods.values()) {
if (mi.matches(candidate)) {
return mi;
}
}
}
return ClassInfo.interfaceMethod(candidate, newClassObj.mSuperclass);
}
public boolean hasConstructor(MethodInfo constructor) {
String name = constructor.getHashableName();
for (ConstructorInfo ctor : mApiCheckConstructors.values()) {
if (name.equals(ctor.getHashableName())) {
return true;
}
}
return false;
}
public void setTypeInfo(TypeInfo typeInfo) {
mTypeInfo = typeInfo;
}
}
| true | true | public void makeHDF(Data data) {
int i, j, n;
String name = name();
String qualified = qualifiedName();
AttributeInfo[] selfAttributes = selfAttributes();
MethodInfo[] methods = selfMethods();
FieldInfo[] fields = selfFields();
FieldInfo[] enumConstants = enumConstants();
MethodInfo[] ctors = constructors();
ClassInfo[] inners = innerClasses();
// class name
mTypeInfo.makeHDF(data, "class.type");
mTypeInfo.makeQualifiedHDF(data, "class.qualifiedType");
data.setValue("class.name", name);
data.setValue("class.qualified", qualified);
String scope = "";
if (isProtected()) {
data.setValue("class.scope", "protected");
} else if (isPublic()) {
data.setValue("class.scope", "public");
}
if (isStatic()) {
data.setValue("class.static", "static");
}
if (isFinal()) {
data.setValue("class.final", "final");
}
if (isAbstract() && !isInterface()) {
data.setValue("class.abstract", "abstract");
}
// class info
String kind = kind();
if (kind != null) {
data.setValue("class.kind", kind);
}
data.setValue("class.since", getSince());
setFederatedReferences(data, "class");
// the containing package -- note that this can be passed to type_link,
// but it also contains the list of all of the packages
containingPackage().makeClassLinkListHDF(data, "class.package");
// inheritance hierarchy
Vector<ClassInfo> superClasses = new Vector<ClassInfo>();
superClasses.add(this);
ClassInfo supr = superclass();
while (supr != null) {
superClasses.add(supr);
supr = supr.superclass();
}
n = superClasses.size();
for (i = 0; i < n; i++) {
supr = superClasses.elementAt(n - i - 1);
supr.asTypeInfo().makeQualifiedHDF(data, "class.inheritance." + i + ".class");
supr.asTypeInfo().makeHDF(data, "class.inheritance." + i + ".short_class");
j = 0;
for (TypeInfo t : supr.interfaceTypes()) {
t.makeHDF(data, "class.inheritance." + i + ".interfaces." + j);
j++;
}
}
// class description
TagInfo.makeHDF(data, "class.descr", inlineTags());
TagInfo.makeHDF(data, "class.seeAlso", comment().seeTags());
TagInfo.makeHDF(data, "class.deprecated", deprecatedTags());
// known subclasses
TreeMap<String, ClassInfo> direct = new TreeMap<String, ClassInfo>();
TreeMap<String, ClassInfo> indirect = new TreeMap<String, ClassInfo>();
ClassInfo[] all = Converter.rootClasses();
for (ClassInfo cl : all) {
if (cl.superclass() != null && cl.superclass().equals(this)) {
direct.put(cl.name(), cl);
} else if (cl.isDerivedFrom(this)) {
indirect.put(cl.name(), cl);
}
}
// direct
i = 0;
for (ClassInfo cl : direct.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.direct." + i);
}
i++;
}
// indirect
i = 0;
for (ClassInfo cl : indirect.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.indirect." + i);
}
i++;
}
// hide special cases
if ("java.lang.Object".equals(qualified) || "java.io.Serializable".equals(qualified)) {
data.setValue("class.subclasses.hidden", "1");
} else {
data.setValue("class.subclasses.hidden", "0");
}
// nested classes
i = 0;
for (ClassInfo inner : inners) {
if (inner.checkLevel()) {
inner.makeShortDescrHDF(data, "class.inners." + i);
}
i++;
}
// enum constants
i = 0;
for (FieldInfo field : enumConstants) {
if (field.isConstant()) {
field.makeHDF(data, "class.enumConstants." + i);
i++;
}
}
// constants
i = 0;
for (FieldInfo field : fields) {
if (field.isConstant()) {
field.makeHDF(data, "class.constants." + i);
i++;
}
}
// fields
i = 0;
for (FieldInfo field : fields) {
if (!field.isConstant()) {
field.makeHDF(data, "class.fields." + i);
i++;
}
}
// public constructors
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPublic()) {
ctor.makeHDF(data, "class.ctors.public." + i);
i++;
}
}
// protected constructors
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isProtected()) {
ctor.makeHDF(data, "class.ctors.protected." + i);
i++;
}
}
}
// package private constructors
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPackagePrivate()) {
ctor.makeHDF(data, "class.ctors.package." + i);
i++;
}
}
}
// private constructors
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPrivate()) {
ctor.makeHDF(data, "class.ctors.private." + i);
i++;
}
}
}
// public methods
i = 0;
for (MethodInfo method : methods) {
if (method.isPublic()) {
method.makeHDF(data, "class.methods.public." + i);
i++;
}
}
// protected methods
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isProtected()) {
method.makeHDF(data, "class.methods.protected." + i);
i++;
}
}
}
// package private methods
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPackagePrivate()) {
method.makeHDF(data, "class.methods.package." + i);
i++;
}
}
}
// private methods
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPrivate()) {
method.makeHDF(data, "class.methods.private." + i);
i++;
}
}
}
// xml attributes
i = 0;
for (AttributeInfo attr : selfAttributes) {
if (attr.checkLevel()) {
attr.makeHDF(data, "class.attrs." + i);
i++;
}
}
// inherited methods
Set<ClassInfo> interfaces = new TreeSet<ClassInfo>();
addInterfaces(interfaces(), interfaces);
ClassInfo cl = superclass();
i = 0;
while (cl != null) {
addInterfaces(cl.interfaces(), interfaces);
makeInheritedHDF(data, i, cl);
cl = cl.superclass();
i++;
}
for (ClassInfo iface : interfaces) {
makeInheritedHDF(data, i, iface);
i++;
}
}
| public void makeHDF(Data data) {
int i, j, n;
String name = name();
String qualified = qualifiedName();
AttributeInfo[] selfAttributes = selfAttributes();
MethodInfo[] methods = selfMethods();
FieldInfo[] fields = selfFields();
FieldInfo[] enumConstants = enumConstants();
MethodInfo[] ctors = constructors();
ClassInfo[] inners = innerClasses();
// class name
mTypeInfo.makeHDF(data, "class.type");
mTypeInfo.makeQualifiedHDF(data, "class.qualifiedType");
data.setValue("class.name", name);
data.setValue("class.qualified", qualified);
String scope = "";
if (isProtected()) {
data.setValue("class.scope", "protected");
} else if (isPublic()) {
data.setValue("class.scope", "public");
}
if (isStatic()) {
data.setValue("class.static", "static");
}
if (isFinal()) {
data.setValue("class.final", "final");
}
if (isAbstract() && !isInterface()) {
data.setValue("class.abstract", "abstract");
}
// class info
String kind = kind();
if (kind != null) {
data.setValue("class.kind", kind);
}
data.setValue("class.since", getSince());
setFederatedReferences(data, "class");
// the containing package -- note that this can be passed to type_link,
// but it also contains the list of all of the packages
containingPackage().makeClassLinkListHDF(data, "class.package");
// inheritance hierarchy
Vector<ClassInfo> superClasses = new Vector<ClassInfo>();
superClasses.add(this);
ClassInfo supr = superclass();
while (supr != null) {
superClasses.add(supr);
supr = supr.superclass();
}
n = superClasses.size();
for (i = 0; i < n; i++) {
supr = superClasses.elementAt(n - i - 1);
supr.asTypeInfo().makeQualifiedHDF(data, "class.inheritance." + i + ".class");
supr.asTypeInfo().makeHDF(data, "class.inheritance." + i + ".short_class");
j = 0;
for (TypeInfo t : supr.interfaceTypes()) {
t.makeHDF(data, "class.inheritance." + i + ".interfaces." + j);
j++;
}
}
// class description
TagInfo.makeHDF(data, "class.descr", inlineTags());
TagInfo.makeHDF(data, "class.seeAlso", comment().seeTags());
TagInfo.makeHDF(data, "class.deprecated", deprecatedTags());
// known subclasses
TreeMap<String, ClassInfo> direct = new TreeMap<String, ClassInfo>();
TreeMap<String, ClassInfo> indirect = new TreeMap<String, ClassInfo>();
ClassInfo[] all = Converter.rootClasses();
for (ClassInfo cl : all) {
if (cl.superclass() != null && cl.superclass().equals(this)) {
direct.put(cl.name(), cl);
} else if (cl.isDerivedFrom(this)) {
indirect.put(cl.name(), cl);
}
}
// direct
i = 0;
for (ClassInfo cl : direct.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.direct." + i);
}
i++;
}
// indirect
i = 0;
for (ClassInfo cl : indirect.values()) {
if (cl.checkLevel()) {
cl.makeShortDescrHDF(data, "class.subclasses.indirect." + i);
}
i++;
}
// hide special cases
if ("java.lang.Object".equals(qualified) || "java.io.Serializable".equals(qualified)) {
data.setValue("class.subclasses.hidden", "1");
} else {
data.setValue("class.subclasses.hidden", "0");
}
// nested classes
i = 0;
for (ClassInfo inner : inners) {
if (inner.checkLevel()) {
inner.makeShortDescrHDF(data, "class.inners." + i);
}
i++;
}
// enum constants
i = 0;
for (FieldInfo field : enumConstants) {
field.makeHDF(data, "class.enumConstants." + i);
i++;
}
// constants
i = 0;
for (FieldInfo field : fields) {
if (field.isConstant()) {
field.makeHDF(data, "class.constants." + i);
i++;
}
}
// fields
i = 0;
for (FieldInfo field : fields) {
if (!field.isConstant()) {
field.makeHDF(data, "class.fields." + i);
i++;
}
}
// public constructors
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPublic()) {
ctor.makeHDF(data, "class.ctors.public." + i);
i++;
}
}
// protected constructors
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isProtected()) {
ctor.makeHDF(data, "class.ctors.protected." + i);
i++;
}
}
}
// package private constructors
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPackagePrivate()) {
ctor.makeHDF(data, "class.ctors.package." + i);
i++;
}
}
}
// private constructors
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo ctor : ctors) {
if (ctor.isPrivate()) {
ctor.makeHDF(data, "class.ctors.private." + i);
i++;
}
}
}
// public methods
i = 0;
for (MethodInfo method : methods) {
if (method.isPublic()) {
method.makeHDF(data, "class.methods.public." + i);
i++;
}
}
// protected methods
if (Doclava.checkLevel(Doclava.SHOW_PROTECTED)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isProtected()) {
method.makeHDF(data, "class.methods.protected." + i);
i++;
}
}
}
// package private methods
if (Doclava.checkLevel(Doclava.SHOW_PACKAGE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPackagePrivate()) {
method.makeHDF(data, "class.methods.package." + i);
i++;
}
}
}
// private methods
if (Doclava.checkLevel(Doclava.SHOW_PRIVATE)) {
i = 0;
for (MethodInfo method : methods) {
if (method.isPrivate()) {
method.makeHDF(data, "class.methods.private." + i);
i++;
}
}
}
// xml attributes
i = 0;
for (AttributeInfo attr : selfAttributes) {
if (attr.checkLevel()) {
attr.makeHDF(data, "class.attrs." + i);
i++;
}
}
// inherited methods
Set<ClassInfo> interfaces = new TreeSet<ClassInfo>();
addInterfaces(interfaces(), interfaces);
ClassInfo cl = superclass();
i = 0;
while (cl != null) {
addInterfaces(cl.interfaces(), interfaces);
makeInheritedHDF(data, i, cl);
cl = cl.superclass();
i++;
}
for (ClassInfo iface : interfaces) {
makeInheritedHDF(data, i, iface);
i++;
}
}
|
diff --git a/odcleanstore/engine/src/main/java/cz/cuni/mff/odcleanstore/engine/db/model/DbOdcsContext.java b/odcleanstore/engine/src/main/java/cz/cuni/mff/odcleanstore/engine/db/model/DbOdcsContext.java
index b2c003af..88724fa5 100644
--- a/odcleanstore/engine/src/main/java/cz/cuni/mff/odcleanstore/engine/db/model/DbOdcsContext.java
+++ b/odcleanstore/engine/src/main/java/cz/cuni/mff/odcleanstore/engine/db/model/DbOdcsContext.java
@@ -1,222 +1,223 @@
package cz.cuni.mff.odcleanstore.engine.db.model;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import cz.cuni.mff.odcleanstore.configuration.ConfigLoader;
import cz.cuni.mff.odcleanstore.connection.WrappedResultSet;
import cz.cuni.mff.odcleanstore.connection.exceptions.ConnectionException;
import cz.cuni.mff.odcleanstore.connection.exceptions.QueryException;
import cz.cuni.mff.odcleanstore.engine.db.DbContext;
public class DbOdcsContext extends DbContext {
private static final String ERROR_CREATE_ODCS_CONTEXT = "Error during creating DbOdcsContext";
public DbOdcsContext() throws DbOdcsException {
try {
setConnection(ConfigLoader.getConfig().getBackendGroup().getCleanDBJDBCConnectionCredentials());
execute(SQL.USE_ODCS_SCHEMA);
}
catch(Exception e) {
throw new DbOdcsException(ERROR_CREATE_ODCS_CONTEXT, e);
}
}
public Graph selectOldestEngineWorkingGraph(String engineUuid) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
return createDbGraph(resultSet, SQL.SELECT_WORKING_GRAPH, engineUuid);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_WORKING_GRAPH, e);
} finally {
close(resultSet);
}
}
public Graph selectOldestEngineQueuedGraph(String engineUuid) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
return createDbGraph(resultSet, SQL.SELECT_QUEUD_GRAPH, engineUuid);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_QUEUD_GRAPH, e);
} finally {
close(resultSet);
}
}
private Graph createDbGraph(WrappedResultSet resultSet, String query, String engineUuid) throws ConnectionException, QueryException, DbOdcsException, SQLException {
resultSet = select(query, engineUuid);
if(resultSet.next()) {
Graph dbGraph = new Graph();
dbGraph.pipeline = new Pipeline();
dbGraph.id = resultSet.getInt(1);
dbGraph.uuid = resultSet.getString(2);
dbGraph.state = GraphStates.fromId(resultSet.getInt(3));
dbGraph.pipeline.id = resultSet.getInt(4);
dbGraph.pipeline.label = resultSet.getString(5);
dbGraph.isInCleanDb = resultSet.getInt(6) != 0;
dbGraph.engineUuid = resultSet.getString(7);
return dbGraph;
}
return null;
}
public boolean updateAttachedEngine(int graphId, String engineUuid) throws DbOdcsException {
try {
int updatedRowCount = execute(SQL.UPDATE_ATTACHED_ENGINE, engineUuid, graphId, engineUuid);
return updatedRowCount > 0;
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_UPDATE_ATTACHED_ENGINE, e);
}
}
public boolean updateState( int graphId, GraphStates newState) throws DbOdcsException {
try {
int updatedRowCount = execute(SQL.UPDATE_GRAPH_STATE, newState.toId(), graphId);
return updatedRowCount > 0;
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_UPDATE_GRAPH_STATE, e);
}
}
public boolean updateStateAndIsInCleanDb( int graphId, GraphStates newState, boolean isInCleanDb) throws DbOdcsException {
try {
int updatedRowCount = execute(SQL.UPDATE_GRAPH_STATE_AND_ISINCLEANDB, newState.toId(), isInCleanDb ? 1 : 0, graphId);
return updatedRowCount > 0;
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_UPDATE_GRAPH_STATE_AND_ISINCLEANDB, e);
}
}
public HashSet<String> selectAttachedGraphs(int graphId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
HashSet<String> graphNames = new HashSet<String>();
resultSet = select(SQL.SELECT_ATTACHED_GRAPHS, graphId);
while(resultSet.next()) {
graphNames.add(resultSet.getString(1));
}
return graphNames;
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_ATTACHED_GRAPHS, e);
} finally {
close(resultSet);
}
}
public void insertAttachedGraph(int graphId, String name) throws DbOdcsException {
try {
execute(SQL.INSERT_ATTACHED_GRAPH, graphId, name);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_INSERT_ATTACHED_GRAPH, e);
}
}
public void deleteAttachedGraphs(int graphId) throws DbOdcsException {
try {
execute(SQL.DELETE_ATTACHED_GRAPHS, graphId);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_DELETE_ATTACHED_GRAPHS, e);
}
}
public PipelineCommand[] selectPipelineCommands(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<PipelineCommand> dbPipelineCommands = new ArrayList<PipelineCommand>();
resultSet = select(SQL.SELECT_PIPELINE_COMMANDS, pipelineId);
while(resultSet.next()) {
PipelineCommand mbr = new PipelineCommand();
mbr.jarPath = resultSet.getString(1);
mbr.fullClassName = resultSet.getString(2);
mbr.workDirPath = resultSet.getString(3);
- mbr.configuration = resultSet.getNString(4);
+ String configuration = resultSet.getNString(4); // configuration should not be null
+ mbr.configuration = configuration != null ? configuration : "";
mbr.runOnCleanDB = resultSet.getInt(5) != 0;
mbr.transformerInstanceID = resultSet.getInt(6);
mbr.transformerLabel = resultSet.getString(7);
dbPipelineCommands.add(mbr);
}
return dbPipelineCommands.toArray( new PipelineCommand[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_PIPELINE_COMMANDS, e);
}
}
public GroupRule[] selectDnRules(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<GroupRule> groupRules = new ArrayList<GroupRule>();
resultSet = select(SQL.SELECT_DN_GROUPS, pipelineId);
while(resultSet.next()) {
GroupRule mbr = new GroupRule();
mbr.transformerInstanceId = resultSet.getInt(1);
mbr.groupId = resultSet.getInt(2);
groupRules.add(mbr);
}
return groupRules.toArray(new GroupRule[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_DN_GROUPS, e);
}
}
public GroupRule[] selectQaRules(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<GroupRule> groupRules = new ArrayList<GroupRule>();
resultSet = select(SQL.SELECT_QA_GROUPS, pipelineId);
while(resultSet.next()) {
GroupRule mbr = new GroupRule();
mbr.transformerInstanceId = resultSet.getInt(1);
mbr.groupId = resultSet.getInt(2);
groupRules.add(mbr);
}
return groupRules.toArray(new GroupRule[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_QA_GROUPS, e);
}
}
public GroupRule[] selectOiRules(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<GroupRule> groupRules = new ArrayList<GroupRule>();
resultSet = select(SQL.SELECT_OI_GROUPS, pipelineId);
while(resultSet.next()) {
GroupRule mbr = new GroupRule();
mbr.transformerInstanceId = resultSet.getInt(1);
mbr.groupId = resultSet.getInt(2);
groupRules.add(mbr);
}
return groupRules.toArray(new GroupRule[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_OI_GROUPS, e);
}
}
public Pipeline selectDefaultPipeline() throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
resultSet = select(SQL.SELECT_DEFAULT_PIPELINE);
if(resultSet.next()) {
Pipeline pipeline = new Pipeline();
pipeline.id = resultSet.getInt(1);
pipeline.label = resultSet.getString(2);
return pipeline;
}
return null;
} catch (Exception e) {
throw new DbOdcsException(SQL.SELECT_DEFAULT_PIPELINE, e);
}
}
public void insertGraphInError(int graphId, PipelineErrorTypes type, String message) throws DbOdcsException {
try {
execute(SQL.INSERT_GRAPH_IN_ERROR, graphId, type.toId(), message);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_INSERT_GRAPH_IN_ERROR, e);
}
}
}
| true | true | public PipelineCommand[] selectPipelineCommands(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<PipelineCommand> dbPipelineCommands = new ArrayList<PipelineCommand>();
resultSet = select(SQL.SELECT_PIPELINE_COMMANDS, pipelineId);
while(resultSet.next()) {
PipelineCommand mbr = new PipelineCommand();
mbr.jarPath = resultSet.getString(1);
mbr.fullClassName = resultSet.getString(2);
mbr.workDirPath = resultSet.getString(3);
mbr.configuration = resultSet.getNString(4);
mbr.runOnCleanDB = resultSet.getInt(5) != 0;
mbr.transformerInstanceID = resultSet.getInt(6);
mbr.transformerLabel = resultSet.getString(7);
dbPipelineCommands.add(mbr);
}
return dbPipelineCommands.toArray( new PipelineCommand[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_PIPELINE_COMMANDS, e);
}
}
| public PipelineCommand[] selectPipelineCommands(int pipelineId) throws DbOdcsException {
WrappedResultSet resultSet = null;
try {
ArrayList<PipelineCommand> dbPipelineCommands = new ArrayList<PipelineCommand>();
resultSet = select(SQL.SELECT_PIPELINE_COMMANDS, pipelineId);
while(resultSet.next()) {
PipelineCommand mbr = new PipelineCommand();
mbr.jarPath = resultSet.getString(1);
mbr.fullClassName = resultSet.getString(2);
mbr.workDirPath = resultSet.getString(3);
String configuration = resultSet.getNString(4); // configuration should not be null
mbr.configuration = configuration != null ? configuration : "";
mbr.runOnCleanDB = resultSet.getInt(5) != 0;
mbr.transformerInstanceID = resultSet.getInt(6);
mbr.transformerLabel = resultSet.getString(7);
dbPipelineCommands.add(mbr);
}
return dbPipelineCommands.toArray( new PipelineCommand[0]);
} catch (Exception e) {
throw new DbOdcsException(SQL.ERROR_SELECT_PIPELINE_COMMANDS, e);
}
}
|
diff --git a/src/soot/jimple/toolkits/callgraph/CallGraphBuilder.java b/src/soot/jimple/toolkits/callgraph/CallGraphBuilder.java
index 3228fd89..a6274d37 100644
--- a/src/soot/jimple/toolkits/callgraph/CallGraphBuilder.java
+++ b/src/soot/jimple/toolkits/callgraph/CallGraphBuilder.java
@@ -1,382 +1,384 @@
/* Soot - a J*va Optimization Framework
* Copyright (C) 2002 Ondrej Lhotak
*
* This library 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 library 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 this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.jimple.toolkits.callgraph;
import soot.*;
import soot.options.*;
import soot.jimple.*;
import java.util.*;
import soot.util.*;
import soot.util.queue.*;
/** Models the call graph.
* @author Ondrej Lhotak
*/
public final class CallGraphBuilder
{
private QueueReader worklist;
private HashMap invokeExprToVCS = new HashMap();
private LargeNumberedMap localToVCS = new LargeNumberedMap( Scene.v().getLocalNumberer() );
private PointsToAnalysis pa;
private CGOptions options;
private ReachableMethods reachables;
private boolean appOnly = false;
public ReachableMethods reachables() { return reachables; }
public CallGraphBuilder( PointsToAnalysis pa ) {
this.pa = pa;
options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
cg = new CallGraph();
Scene.v().setCallGraph( cg );
reachables = Scene.v().getReachableMethods();
worklist = reachables.listener();
if( !options.verbose() ) {
G.v().out.println( "[Call Graph] For information on where the call graph may be incomplete, use the verbose option to the cg phase." );
}
}
public CallGraphBuilder() {
G.v().out.println( "Warning: using incomplete callgraph containing "+
"only application classes." );
pa = soot.jimple.toolkits.pointer.DumbPointerAnalysis.v();
options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
cg = new CallGraph();
Scene.v().setCallGraph(cg);
reachables = Scene.v().getReachableMethods();
worklist = reachables.listener();
appOnly = true;
}
public void build() {
processWorklist();
}
private void processWorklist() {
while(true) {
SootMethod m = (SootMethod) worklist.next();
if( m == null ) {
reachables.update();
m = (SootMethod) worklist.next();
if( m == null ) break;
}
if( appOnly && !m.getDeclaringClass().isApplicationClass() )
continue;
processNewMethod( m );
}
}
private void handleClassName( VirtualCallSite vcs, String name ) {
if( name == null ) {
if( options.verbose() ) {
G.v().out.println( "Warning: Method "+vcs.getContainer()+
" is reachable, and calls Class.forName on a"+
" non-constant String; graph will be incomplete!"+
" Use safe-forname option for a conservative result." );
}
} else {
constantForName( name, vcs.getContainer(), vcs.getStmt() );
}
}
private void processNewMethod( SootMethod m ) {
if( m.isNative() ) {
return;
}
Body b = m.retrieveActiveBody();
HashSet receivers = new HashSet();
getImplicitTargets( m );
findReceivers(m, b, receivers);
processReceivers(receivers);
}
private void processReceivers(HashSet receivers) {
for( Iterator receiverIt = receivers.iterator(); receiverIt.hasNext(); ) {
final Local receiver = (Local) receiverIt.next();
Set types = pa.reachingObjects( receiver ).possibleTypes();
HashSet vcss = (HashSet) localToVCS.get( receiver );
for( Iterator vcsIt = vcss.iterator(); vcsIt.hasNext(); ) {
final VirtualCallSite vcs = (VirtualCallSite) vcsIt.next();
final Type t;
SootMethod target;
resolveInvokes(types, vcs);
if( vcs.getInstanceInvokeExpr().getMethod().getNumberedSubSignature() == sigStart ) {
resolveThreadInvokes(types, vcs);
}
}
}
}
private void resolveThreadInvokes(Set types, final VirtualCallSite vcs) {
for( Iterator tIt = types.iterator(); tIt.hasNext(); ) {
final Type t = (Type) tIt.next();
VirtualCalls.v().resolveThread( t, vcs.getInstanceInvokeExpr(), vcs.getContainer(),
targetsQueue );
}
while(true) {
SootMethod target = (SootMethod) targets.next();
if( target == null ) break;
cg.addEdge(
new Edge( vcs.getContainer(), vcs.getStmt(), target,
Edge.THREAD ) );
}
}
private void resolveInvokes(Set types, final VirtualCallSite vcs) {
for( Iterator tIt = types.iterator(); tIt.hasNext(); ) {
final Type t = (Type) tIt.next();
VirtualCalls.v().resolve( t, vcs.getInstanceInvokeExpr(), vcs.getContainer(),
targetsQueue );
}
while(true) {
SootMethod target = (SootMethod) targets.next();
if( target == null ) break;
cg.addEdge(
new Edge( vcs.getContainer(), vcs.getStmt(), target ) );
}
}
private void findReceivers(SootMethod m, Body b, HashSet receivers) {
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if (s.containsInvokeExpr()) {
InvokeExpr ie = (InvokeExpr) s.getInvokeExpr();
if (ie instanceof InstanceInvokeExpr) {
VirtualCallSite vcs = new VirtualCallSite(s, m);
invokeExprToVCS.put(ie, vcs);
Local receiver =
(Local) ((InstanceInvokeExpr) ie).getBase();
HashSet vcss = (HashSet) localToVCS.get(receiver);
if (vcss == null) {
localToVCS.put(receiver, vcss = new HashSet());
}
vcss.add(vcs);
receivers.add(receiver);
} else {
SootMethod tgt = ((StaticInvokeExpr) ie).getMethod();
cg.addEdge(new Edge(m, s, tgt));
}
}
}
}
HashSet currentvcss = null;
public boolean wantTypes( Local l ) {
currentvcss = (HashSet) localToVCS.get( l );
return currentvcss != null && !currentvcss.isEmpty();
}
public void addType( Type t ) {
for( Iterator vcsIt = currentvcss.iterator(); vcsIt.hasNext(); ) {
final VirtualCallSite vcs = (VirtualCallSite) vcsIt.next();
VirtualCalls.v().resolve( t, vcs.getInstanceInvokeExpr(), vcs.getContainer(),
targetsQueue );
while(true) {
SootMethod target = (SootMethod) targets.next();
if( target == null ) break;
cg.addEdge(
new Edge( vcs.getContainer(), vcs.getStmt(), target ) );
}
if( vcs.getInstanceInvokeExpr().getMethod().getNumberedSubSignature() == sigStart ) {
VirtualCalls.v().resolve( t, vcs.getInstanceInvokeExpr(), vcs.getContainer(),
targetsQueue );
while(true) {
SootMethod target = (SootMethod) targets.next();
if( target == null ) break;
cg.addEdge(
new Edge( vcs.getContainer(), vcs.getStmt(), target,
Edge.THREAD ) );
}
}
}
}
public void doneTypes() {
currentvcss = null;
processWorklist();
}
public boolean wantStringConstants( Local l ) {
return wantedStringConstants.keySet().contains( l );
}
public void newStringConstant( Local l, String name ) {
for( Iterator vcsIt = wantedStringConstants.get( l ).iterator(); vcsIt.hasNext(); ) {
final VirtualCallSite vcs = (VirtualCallSite) vcsIt.next();
handleClassName( vcs, name );
}
if( name == null ) wantedStringConstants.remove( l );
}
public void doneStringConstants() {
processWorklist();
}
public CallGraph getCallGraph() {
return cg;
}
private final void addEdge( SootMethod src, Stmt stmt, SootClass cls, NumberedString methodSubSig, int type ) {
if( cls.declaresMethod( methodSubSig ) ) {
cg.addEdge(
new Edge( src, stmt, cls.getMethod( methodSubSig ), type ) );
}
}
private final void addEdge( SootMethod src, Stmt stmt, String methodSig, int type ) {
if( Scene.v().containsMethod( methodSig ) ) {
cg.addEdge(
new Edge( src, stmt, Scene.v().getMethod( methodSig ), type ) );
}
}
private void constantForName( String cls, SootMethod src, Stmt srcUnit ) {
if( cls.charAt(0) == '[' ) {
if( cls.charAt(1) == 'L' && cls.charAt(cls.length()-1) == ';' ) {
cls = cls.substring(2,cls.length()-1);
constantForName( cls, src, srcUnit );
}
} else {
if( !Scene.v().containsClass( cls ) ) {
if( options.verbose() ) {
G.v().out.println( "Warning: Class "+cls+" is"+
" a dynamic class, and you did not specify"+
" it as such; graph will be incomplete!" );
}
} else {
SootClass sootcls = Scene.v().getSootClass( cls );
if( !sootcls.isApplicationClass() ) {
sootcls.setLibraryClass();
}
addEdge( src, srcUnit, sootcls, sigClinit, Edge.CLINIT );
}
}
}
public void getImplicitTargets( SootMethod source ) {
final SootClass scl = source.getDeclaringClass();
if( source.isNative() ) return;
if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) {
handleInit(source, scl);
}
Body b = source.retrieveActiveBody();
boolean warnedAlready = false;
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if( s.containsInvokeExpr() ) {
InvokeExpr ie = (InvokeExpr) s.getInvokeExpr();
if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) {
if( !warnedAlready ) {
if( options.verbose() ) {
G.v().out.println( "Warning: call to "+
"java.lang.reflect.Method: invoke() from "+source+
"; graph will be incomplete!" );
}
warnedAlready = true;
}
}
+ if( ie instanceof StaticInvokeExpr ) {
+ addEdge( source, s, ie.getMethod().getDeclaringClass(),
+ sigClinit, Edge.CLINIT );
+ }
if( ie.getMethod().getNumberedSubSignature() == sigForName ) {
Value name = ie.getArg(0);
if( name instanceof StringConstant ) {
String cls = ((StringConstant) name ).value;
constantForName( cls, source, s );
} else {
if( options.safe_forname() ) {
for( Iterator tgtIt = EntryPoints.v().clinits().iterator(); tgtIt.hasNext(); ) {
final SootMethod tgt = (SootMethod) tgtIt.next();
cg.addEdge( new Edge( source, s, tgt, Edge.CLINIT ) );
}
} else {
VirtualCallSite vcs = new VirtualCallSite( s, source );
wantedStringConstants.put( name, vcs );
Set names = pa.reachingObjects( (Local) name ).possibleStringConstants();
if( names == null ) {
handleClassName( vcs, null );
wantedStringConstants.remove( name );
} else {
for( Iterator nameStrIt = names.iterator(); nameStrIt.hasNext(); ) {
final String nameStr = (String) nameStrIt.next();
handleClassName( vcs, nameStr );
}
}
}
}
}
- addEdge( source, s, ie.getMethod().getDeclaringClass(),
- sigClinit, Edge.CLINIT );
}
if( s.containsFieldRef() ) {
FieldRef fr = (FieldRef) s.getFieldRef();
if( fr instanceof StaticFieldRef ) {
SootClass cl = fr.getField().getDeclaringClass();
addEdge( source, s, cl, sigClinit, Edge.CLINIT );
}
}
if( s instanceof AssignStmt ) {
Value rhs = ((AssignStmt)s).getRightOp();
if( rhs instanceof NewExpr ) {
NewExpr r = (NewExpr) rhs;
addEdge( source, s, r.getBaseType().getSootClass(),
sigClinit, Edge.CLINIT );
} else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) {
Type t = rhs.getType();
if( t instanceof ArrayType ) t = ((ArrayType)t).baseType;
if( t instanceof RefType ) {
addEdge( source, s, ((RefType) t).getSootClass(),
sigClinit, Edge.CLINIT );
}
}
}
}
}
private void handleInit(SootMethod source, final SootClass scl) {
addEdge( source, null, scl, sigFinalize, Edge.FINALIZE );
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
if( fh.canStoreType( scl.getType(), clPrivilegedAction )
|| fh.canStoreType( scl.getType(), clPrivilegedExceptionAction ) ) {
addEdge( source, null, scl, sigObjRun, Edge.PRIVILEGED );
}
if( fh.canStoreType( scl.getType(), clRunnable ) ) {
addEdge( source, null, scl, sigExit, Edge.EXIT );
}
}
private HashMultiMap wantedStringConstants = new HashMultiMap();
private HashMap stmtToMethod = new HashMap();
private CallGraph cg;
private ChunkedQueue targetsQueue = new ChunkedQueue();
private QueueReader targets = targetsQueue.reader();
private final NumberedString sigMain = Scene.v().getSubSigNumberer().
findOrAdd( "void main(java.lang.String[])" );
private final NumberedString sigFinalize = Scene.v().getSubSigNumberer().
findOrAdd( "void finalize()" );
private final NumberedString sigExit = Scene.v().getSubSigNumberer().
findOrAdd( "void exit()" );
private final NumberedString sigClinit = Scene.v().getSubSigNumberer().
findOrAdd( "void <clinit>()" );
private final NumberedString sigStart = Scene.v().getSubSigNumberer().
findOrAdd( "void start()" );
private final NumberedString sigRun = Scene.v().getSubSigNumberer().
findOrAdd( "void run()" );
private final NumberedString sigObjRun = Scene.v().getSubSigNumberer().
findOrAdd( "java.lang.Object run()" );
private final NumberedString sigForName = Scene.v().getSubSigNumberer().
findOrAdd( "java.lang.Class forName(java.lang.String)" );
private final RefType clPrivilegedAction = RefType.v("java.security.PrivilegedAction");
private final RefType clPrivilegedExceptionAction = RefType.v("java.security.PrivilegedExceptionAction");
private final RefType clRunnable = RefType.v("java.lang.Runnable");
}
| false | true | public void getImplicitTargets( SootMethod source ) {
final SootClass scl = source.getDeclaringClass();
if( source.isNative() ) return;
if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) {
handleInit(source, scl);
}
Body b = source.retrieveActiveBody();
boolean warnedAlready = false;
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if( s.containsInvokeExpr() ) {
InvokeExpr ie = (InvokeExpr) s.getInvokeExpr();
if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) {
if( !warnedAlready ) {
if( options.verbose() ) {
G.v().out.println( "Warning: call to "+
"java.lang.reflect.Method: invoke() from "+source+
"; graph will be incomplete!" );
}
warnedAlready = true;
}
}
if( ie.getMethod().getNumberedSubSignature() == sigForName ) {
Value name = ie.getArg(0);
if( name instanceof StringConstant ) {
String cls = ((StringConstant) name ).value;
constantForName( cls, source, s );
} else {
if( options.safe_forname() ) {
for( Iterator tgtIt = EntryPoints.v().clinits().iterator(); tgtIt.hasNext(); ) {
final SootMethod tgt = (SootMethod) tgtIt.next();
cg.addEdge( new Edge( source, s, tgt, Edge.CLINIT ) );
}
} else {
VirtualCallSite vcs = new VirtualCallSite( s, source );
wantedStringConstants.put( name, vcs );
Set names = pa.reachingObjects( (Local) name ).possibleStringConstants();
if( names == null ) {
handleClassName( vcs, null );
wantedStringConstants.remove( name );
} else {
for( Iterator nameStrIt = names.iterator(); nameStrIt.hasNext(); ) {
final String nameStr = (String) nameStrIt.next();
handleClassName( vcs, nameStr );
}
}
}
}
}
addEdge( source, s, ie.getMethod().getDeclaringClass(),
sigClinit, Edge.CLINIT );
}
if( s.containsFieldRef() ) {
FieldRef fr = (FieldRef) s.getFieldRef();
if( fr instanceof StaticFieldRef ) {
SootClass cl = fr.getField().getDeclaringClass();
addEdge( source, s, cl, sigClinit, Edge.CLINIT );
}
}
if( s instanceof AssignStmt ) {
Value rhs = ((AssignStmt)s).getRightOp();
if( rhs instanceof NewExpr ) {
NewExpr r = (NewExpr) rhs;
addEdge( source, s, r.getBaseType().getSootClass(),
sigClinit, Edge.CLINIT );
} else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) {
Type t = rhs.getType();
if( t instanceof ArrayType ) t = ((ArrayType)t).baseType;
if( t instanceof RefType ) {
addEdge( source, s, ((RefType) t).getSootClass(),
sigClinit, Edge.CLINIT );
}
}
}
}
}
| public void getImplicitTargets( SootMethod source ) {
final SootClass scl = source.getDeclaringClass();
if( source.isNative() ) return;
if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) {
handleInit(source, scl);
}
Body b = source.retrieveActiveBody();
boolean warnedAlready = false;
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if( s.containsInvokeExpr() ) {
InvokeExpr ie = (InvokeExpr) s.getInvokeExpr();
if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) {
if( !warnedAlready ) {
if( options.verbose() ) {
G.v().out.println( "Warning: call to "+
"java.lang.reflect.Method: invoke() from "+source+
"; graph will be incomplete!" );
}
warnedAlready = true;
}
}
if( ie instanceof StaticInvokeExpr ) {
addEdge( source, s, ie.getMethod().getDeclaringClass(),
sigClinit, Edge.CLINIT );
}
if( ie.getMethod().getNumberedSubSignature() == sigForName ) {
Value name = ie.getArg(0);
if( name instanceof StringConstant ) {
String cls = ((StringConstant) name ).value;
constantForName( cls, source, s );
} else {
if( options.safe_forname() ) {
for( Iterator tgtIt = EntryPoints.v().clinits().iterator(); tgtIt.hasNext(); ) {
final SootMethod tgt = (SootMethod) tgtIt.next();
cg.addEdge( new Edge( source, s, tgt, Edge.CLINIT ) );
}
} else {
VirtualCallSite vcs = new VirtualCallSite( s, source );
wantedStringConstants.put( name, vcs );
Set names = pa.reachingObjects( (Local) name ).possibleStringConstants();
if( names == null ) {
handleClassName( vcs, null );
wantedStringConstants.remove( name );
} else {
for( Iterator nameStrIt = names.iterator(); nameStrIt.hasNext(); ) {
final String nameStr = (String) nameStrIt.next();
handleClassName( vcs, nameStr );
}
}
}
}
}
}
if( s.containsFieldRef() ) {
FieldRef fr = (FieldRef) s.getFieldRef();
if( fr instanceof StaticFieldRef ) {
SootClass cl = fr.getField().getDeclaringClass();
addEdge( source, s, cl, sigClinit, Edge.CLINIT );
}
}
if( s instanceof AssignStmt ) {
Value rhs = ((AssignStmt)s).getRightOp();
if( rhs instanceof NewExpr ) {
NewExpr r = (NewExpr) rhs;
addEdge( source, s, r.getBaseType().getSootClass(),
sigClinit, Edge.CLINIT );
} else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) {
Type t = rhs.getType();
if( t instanceof ArrayType ) t = ((ArrayType)t).baseType;
if( t instanceof RefType ) {
addEdge( source, s, ((RefType) t).getSootClass(),
sigClinit, Edge.CLINIT );
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.