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/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
index 94aa00ed..cfc91ac6 100644
--- a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
+++ b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
@@ -1,137 +1,137 @@
/**
* $Revision: 22540 $
* $Date: 2005-10-10 08:44:25 -0700 (Mon, 10 Oct 2005) $
*
* Copyright (C) 1999-2005 Jive Software. All rights reserved.
*
* This software is the proprietary information of Jive Software.
* Use is subject to license terms.
*/
package com.jivesoftware.spark.plugin.apple;
import com.apple.eawt.Application;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import javax.swing.*;
import java.awt.*;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.MainWindow;
import org.jivesoftware.Spark;
/**
* Plugins for handling Mac OS X specific functionality
*
* @author Andrew Wright
*/
public class ApplePlugin implements Plugin {
private ChatRoomListener roomListener;
public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
- //connectMenu.remove(item);
+ connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
- // application.setEnabledPreferencesMenu(true);
- // application.addPreferencesMenuItem();
+ application.setEnabledPreferencesMenu(true);
+ application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
public void shutdown() {
if (Spark.isMac()) {
SparkManager.getChatManager().removeChatRoomListener(roomListener);
roomListener = null;
}
}
public boolean canShutDown() {
return false;
}
public void uninstall() {
// No need, since this is internal
}
}
| false | true |
public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
//connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
// application.setEnabledPreferencesMenu(true);
// application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
|
public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
application.setEnabledPreferencesMenu(true);
application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
|
diff --git a/src/gov/nih/nci/nautilus/ui/report/ClinicalSampleReport.java b/src/gov/nih/nci/nautilus/ui/report/ClinicalSampleReport.java
index 252f1e05..57943677 100755
--- a/src/gov/nih/nci/nautilus/ui/report/ClinicalSampleReport.java
+++ b/src/gov/nih/nci/nautilus/ui/report/ClinicalSampleReport.java
@@ -1,206 +1,206 @@
package gov.nih.nci.nautilus.ui.report;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Iterator;
import gov.nih.nci.nautilus.resultset.DimensionalViewContainer;
import gov.nih.nci.nautilus.resultset.Resultant;
import gov.nih.nci.nautilus.resultset.ResultsContainer;
import gov.nih.nci.nautilus.resultset.sample.SampleResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleViewResultsContainer;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author LandyR
* Feb 8, 2005
*
*/
public class ClinicalSampleReport implements ReportGenerator {
/**
*
*/
public ClinicalSampleReport () {
super();
}
/* (non-Javadoc)
* @see gov.nih.nci.nautilus.ui.report.ReportGenerator#getTemplate(gov.nih.nci.nautilus.resultset.Resultant, java.lang.String)
*/
public Document getReportXML(Resultant resultant) {
// have setter or put in props file
String theColors[] = { "B6C5F2","F2E3B5","DAE1F9","C4F2B5","819BE9", "E9CF81" };
DecimalFormat resultFormat = new DecimalFormat("0.0000");
Document document = DocumentHelper.createDocument();
Element report = document.addElement( "Report" );
Element cell = null;
Element data = null;
Element dataRow = null;
//add the atts
report.addAttribute("reportType", "Copy Number");
//fudge these for now
report.addAttribute("groupBy", "none");
report.addAttribute("queryName", "the query name");
report.addAttribute("sessionId", "the session id");
report.addAttribute("creationTime", "right now");
boolean gLinks = false;
boolean cLinks = false;
StringBuffer sb = new StringBuffer();
ResultsContainer resultsContainer = resultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
// Are we making hyperlinks?
if(dimensionalViewContainer.getGeneExprSingleViewContainer() != null) {
// show the geneExprHyperlinks
gLinks = true;
}
if(dimensionalViewContainer.getCopyNumberSingleViewContainer() != null) {
// show the copyNumberHyperlinks
cLinks = true;
}
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
else if (resultsContainer instanceof SampleViewResultsContainer) {
sampleViewContainer = (SampleViewResultsContainer) resultsContainer;
}
Collection samples = sampleViewContainer.getBioSpecimenResultsets();
/*
sb.append("<div class=\"rowCount\">"+helpFul+samples.size()+" records returned " + links + "</div>\n");
sb.append("<table cellpadding=\"0\" cellspacing=\"0\">\n");
*/
// set up the headers for this table
Element headerRow = report.addElement("Row").addAttribute("name", "headerRow");
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SAMPLE");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("AGE at Dx (years)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GENDER");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SURVIVAL (months)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("DISEASE");
data = null;
cell = null;
//sb.append("<Tr><Td id=\"header\">SAMPLE</td><td id=\"header\">AGE at Dx (years)</td><td id=\"header\">GENDER</td><td id=\"header\">SURVIVAL (months)</td><td id=\"header\">DISEASE</td>");
Iterator si = samples.iterator();
if(si.hasNext()) {
SampleResultset sampleResultset = (SampleResultset)si.next();
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GeneExp");
data = null;
cell = null;
//sb.append("<Td id=\"header\">GeneExp</td>");
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("CopyNumber");
data = null;
cell = null;
//sb.append("<td id=\"header\">CopyNumber</td>");
}
//sb.append("</tr>\n");
}
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset)sampleIterator.next();
String sampleName = sampleResultset.getBiospecimen().getValue().toString();
dataRow = report.addElement("Row").addAttribute("name", "dataRow");
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getBiospecimen().getValue().toString().substring(2));
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getAgeGroup().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getGenderCode().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
- data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getGenderCode().getValue().toString());
+ data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getSurvivalLengthRange().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getDisease().getValue().toString());
data = null;
cell = null;
/*
sb.append("<tr><td>"+sampleResultset.getBiospecimen().getValue().toString().substring(2)+ "</td>" +
"<Td>"+sampleResultset.getAgeGroup().getValue()+ "</td>" +
"<td>"+sampleResultset.getGenderCode().getValue()+ "</td>" +
"<td>"+sampleResultset.getSurvivalLengthRange().getValue()+ "</td>" +
"<Td>"+sampleResultset.getDisease().getValue() + "</td>");
*/
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
//TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("G");
data = null;
cell = null;
//sb.append("<td><a href=\"report.do?s="+sampleName+"_gene&report=gene\">G</a></td>");
}
else if (gLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
// TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("C");
data = null;
cell = null;
//sb.append("<Td><a href=\"report.do?s="+sampleName +"_copy&report=copy\">C</a></td>");
}
else if (cLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
//report.append("row", row);
//sb.append("</tr>\n");
}
//sb.append("</table>\n<br>");
//return sb.toString();
return document;
}
}
| true | true |
public Document getReportXML(Resultant resultant) {
// have setter or put in props file
String theColors[] = { "B6C5F2","F2E3B5","DAE1F9","C4F2B5","819BE9", "E9CF81" };
DecimalFormat resultFormat = new DecimalFormat("0.0000");
Document document = DocumentHelper.createDocument();
Element report = document.addElement( "Report" );
Element cell = null;
Element data = null;
Element dataRow = null;
//add the atts
report.addAttribute("reportType", "Copy Number");
//fudge these for now
report.addAttribute("groupBy", "none");
report.addAttribute("queryName", "the query name");
report.addAttribute("sessionId", "the session id");
report.addAttribute("creationTime", "right now");
boolean gLinks = false;
boolean cLinks = false;
StringBuffer sb = new StringBuffer();
ResultsContainer resultsContainer = resultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
// Are we making hyperlinks?
if(dimensionalViewContainer.getGeneExprSingleViewContainer() != null) {
// show the geneExprHyperlinks
gLinks = true;
}
if(dimensionalViewContainer.getCopyNumberSingleViewContainer() != null) {
// show the copyNumberHyperlinks
cLinks = true;
}
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
else if (resultsContainer instanceof SampleViewResultsContainer) {
sampleViewContainer = (SampleViewResultsContainer) resultsContainer;
}
Collection samples = sampleViewContainer.getBioSpecimenResultsets();
/*
sb.append("<div class=\"rowCount\">"+helpFul+samples.size()+" records returned " + links + "</div>\n");
sb.append("<table cellpadding=\"0\" cellspacing=\"0\">\n");
*/
// set up the headers for this table
Element headerRow = report.addElement("Row").addAttribute("name", "headerRow");
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SAMPLE");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("AGE at Dx (years)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GENDER");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SURVIVAL (months)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("DISEASE");
data = null;
cell = null;
//sb.append("<Tr><Td id=\"header\">SAMPLE</td><td id=\"header\">AGE at Dx (years)</td><td id=\"header\">GENDER</td><td id=\"header\">SURVIVAL (months)</td><td id=\"header\">DISEASE</td>");
Iterator si = samples.iterator();
if(si.hasNext()) {
SampleResultset sampleResultset = (SampleResultset)si.next();
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GeneExp");
data = null;
cell = null;
//sb.append("<Td id=\"header\">GeneExp</td>");
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("CopyNumber");
data = null;
cell = null;
//sb.append("<td id=\"header\">CopyNumber</td>");
}
//sb.append("</tr>\n");
}
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset)sampleIterator.next();
String sampleName = sampleResultset.getBiospecimen().getValue().toString();
dataRow = report.addElement("Row").addAttribute("name", "dataRow");
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getBiospecimen().getValue().toString().substring(2));
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getAgeGroup().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getGenderCode().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getGenderCode().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getDisease().getValue().toString());
data = null;
cell = null;
/*
sb.append("<tr><td>"+sampleResultset.getBiospecimen().getValue().toString().substring(2)+ "</td>" +
"<Td>"+sampleResultset.getAgeGroup().getValue()+ "</td>" +
"<td>"+sampleResultset.getGenderCode().getValue()+ "</td>" +
"<td>"+sampleResultset.getSurvivalLengthRange().getValue()+ "</td>" +
"<Td>"+sampleResultset.getDisease().getValue() + "</td>");
*/
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
//TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("G");
data = null;
cell = null;
//sb.append("<td><a href=\"report.do?s="+sampleName+"_gene&report=gene\">G</a></td>");
}
else if (gLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
// TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("C");
data = null;
cell = null;
//sb.append("<Td><a href=\"report.do?s="+sampleName +"_copy&report=copy\">C</a></td>");
}
else if (cLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
//report.append("row", row);
//sb.append("</tr>\n");
}
//sb.append("</table>\n<br>");
//return sb.toString();
return document;
}
|
public Document getReportXML(Resultant resultant) {
// have setter or put in props file
String theColors[] = { "B6C5F2","F2E3B5","DAE1F9","C4F2B5","819BE9", "E9CF81" };
DecimalFormat resultFormat = new DecimalFormat("0.0000");
Document document = DocumentHelper.createDocument();
Element report = document.addElement( "Report" );
Element cell = null;
Element data = null;
Element dataRow = null;
//add the atts
report.addAttribute("reportType", "Copy Number");
//fudge these for now
report.addAttribute("groupBy", "none");
report.addAttribute("queryName", "the query name");
report.addAttribute("sessionId", "the session id");
report.addAttribute("creationTime", "right now");
boolean gLinks = false;
boolean cLinks = false;
StringBuffer sb = new StringBuffer();
ResultsContainer resultsContainer = resultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
// Are we making hyperlinks?
if(dimensionalViewContainer.getGeneExprSingleViewContainer() != null) {
// show the geneExprHyperlinks
gLinks = true;
}
if(dimensionalViewContainer.getCopyNumberSingleViewContainer() != null) {
// show the copyNumberHyperlinks
cLinks = true;
}
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
else if (resultsContainer instanceof SampleViewResultsContainer) {
sampleViewContainer = (SampleViewResultsContainer) resultsContainer;
}
Collection samples = sampleViewContainer.getBioSpecimenResultsets();
/*
sb.append("<div class=\"rowCount\">"+helpFul+samples.size()+" records returned " + links + "</div>\n");
sb.append("<table cellpadding=\"0\" cellspacing=\"0\">\n");
*/
// set up the headers for this table
Element headerRow = report.addElement("Row").addAttribute("name", "headerRow");
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SAMPLE");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("AGE at Dx (years)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GENDER");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("SURVIVAL (months)");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("DISEASE");
data = null;
cell = null;
//sb.append("<Tr><Td id=\"header\">SAMPLE</td><td id=\"header\">AGE at Dx (years)</td><td id=\"header\">GENDER</td><td id=\"header\">SURVIVAL (months)</td><td id=\"header\">DISEASE</td>");
Iterator si = samples.iterator();
if(si.hasNext()) {
SampleResultset sampleResultset = (SampleResultset)si.next();
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GeneExp");
data = null;
cell = null;
//sb.append("<Td id=\"header\">GeneExp</td>");
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("CopyNumber");
data = null;
cell = null;
//sb.append("<td id=\"header\">CopyNumber</td>");
}
//sb.append("</tr>\n");
}
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset)sampleIterator.next();
String sampleName = sampleResultset.getBiospecimen().getValue().toString();
dataRow = report.addElement("Row").addAttribute("name", "dataRow");
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getBiospecimen().getValue().toString().substring(2));
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getAgeGroup().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getGenderCode().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getSurvivalLengthRange().getValue().toString());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(sampleResultset.getDisease().getValue().toString());
data = null;
cell = null;
/*
sb.append("<tr><td>"+sampleResultset.getBiospecimen().getValue().toString().substring(2)+ "</td>" +
"<Td>"+sampleResultset.getAgeGroup().getValue()+ "</td>" +
"<td>"+sampleResultset.getGenderCode().getValue()+ "</td>" +
"<td>"+sampleResultset.getSurvivalLengthRange().getValue()+ "</td>" +
"<Td>"+sampleResultset.getDisease().getValue() + "</td>");
*/
if(sampleResultset.getGeneExprSingleViewResultsContainer() != null) {
//TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("G");
data = null;
cell = null;
//sb.append("<td><a href=\"report.do?s="+sampleName+"_gene&report=gene\">G</a></td>");
}
else if (gLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
if(sampleResultset.getCopyNumberSingleViewResultsContainer()!= null) {
// TODO: create the links
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText("C");
data = null;
cell = null;
//sb.append("<Td><a href=\"report.do?s="+sampleName +"_copy&report=copy\">C</a></td>");
}
else if (cLinks){
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "data").addText(" ");
data = null;
cell = null;
//sb.append("<td> </td>"); //empty cell
}
//report.append("row", row);
//sb.append("</tr>\n");
}
//sb.append("</table>\n<br>");
//return sb.toString();
return document;
}
|
diff --git a/core/src/playn/core/gl/GL20Program.java b/core/src/playn/core/gl/GL20Program.java
index 22911c44..80ea4057 100644
--- a/core/src/playn/core/gl/GL20Program.java
+++ b/core/src/playn/core/gl/GL20Program.java
@@ -1,190 +1,190 @@
/**
* Copyright 2012 The PlayN 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 playn.core.gl;
import java.nio.FloatBuffer;
import static playn.core.PlayN.log;
/**
* A shader program implementation built on the {@link GL20} API.
*/
public class GL20Program implements GLProgram {
private final GL20 gl;
private final int vertexShader, fragmentShader, program;
public GL20Program(GLContext ctx, GL20 gl, String vertexSource, String fragmentSource) {
this.gl = gl;
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = gl.glCreateProgram();
if (program == 0) {
throw new RuntimeException("Failed to create program: " + gl.glGetError());
}
vertexShader = compileShader(GL20.GL_VERTEX_SHADER, vertexSource);
gl.glAttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(GL20.GL_FRAGMENT_SHADER, fragmentSource);
gl.glAttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
gl.glLinkProgram(program);
int[] linkStatus = new int[1];
gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] == GL20.GL_FALSE) {
String log = gl.glGetProgramInfoLog(program);
gl.glDeleteProgram(program);
throw new RuntimeException("Failed to link program: " + log);
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
gl.glDeleteProgram(program);
if (vertexShader != 0)
gl.glDeleteShader(vertexShader);
if (fragmentShader != 0)
- gl.glDeleteShader(program);
+ gl.glDeleteShader(fragmentShader);
}
}
@Override
public GLShader.Uniform1f getUniform1f(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform1f() {
public void bind(float a) {
gl.glUniform1f(loc, a);
}
};
}
@Override
public GLShader.Uniform2f getUniform2f(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2f() {
public void bind(float a, float b) {
gl.glUniform2f(loc, a, b);
}
};
}
@Override
public GLShader.Uniform3f getUniform3f(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform3f() {
public void bind(float a, float b, float c) {
gl.glUniform3f(loc, a, b, c);
}
};
}
@Override
public GLShader.Uniform4f getUniform4f(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform4f() {
public void bind(float a, float b, float c, float d) {
gl.glUniform4f(loc, a, b, c, d);
}
};
}
@Override
public GLShader.Uniform1i getUniform1i(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform1i() {
public void bind(int a) {
gl.glUniform1i(loc, a);
}
};
}
@Override
public GLShader.Uniform2i getUniform2i(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2i() {
public void bind(int a, int b) {
gl.glUniform2i(loc, a, b);
}
};
}
@Override
public GLShader.Uniform2fv getUniform2fv(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2fv() {
public void bind(GLBuffer.Float data, int count) {
FloatBuffer buffer = ((GL20Buffer.FloatImpl)data).buffer;
buffer.position(0);
gl.glUniform2fv(loc, count, buffer);
}
};
}
@Override
public GLShader.UniformMatrix4fv getUniformMatrix4fv(String name) {
final int loc = gl.glGetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.UniformMatrix4fv() {
public void bind(GLBuffer.Float data, int count) {
FloatBuffer buffer = ((GL20Buffer.FloatImpl)data).buffer;
buffer.position(0);
gl.glUniformMatrix4fv(loc, count, false, buffer);
}
};
}
@Override
public GLShader.Attrib getAttrib(String name, final int size, final int type) {
final int loc = gl.glGetAttribLocation(program, name);
return (loc < 0) ? null : new GLShader.Attrib() {
public void bind(int stride, int offset) {
gl.glEnableVertexAttribArray(loc);
gl.glVertexAttribPointer(loc, size, type, false, stride, offset);
}
};
}
@Override
public void bind() {
gl.glUseProgram(program);
}
@Override
public void destroy() {
gl.glDeleteShader(vertexShader);
gl.glDeleteShader(fragmentShader);
gl.glDeleteProgram(program);
}
private int compileShader(int type, final String shaderSource) {
int shader = gl.glCreateShader(type);
if (shader == 0)
throw new RuntimeException("Failed to create shader (" + type + "): " + gl.glGetError());
gl.glShaderSource(shader, shaderSource);
gl.glCompileShader(shader);
int[] compiled = new int[1];
gl.glGetShaderiv(shader, GL20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == GL20.GL_FALSE) {
String log = gl.glGetShaderInfoLog(shader);
gl.glDeleteShader(shader);
throw new RuntimeException("Failed to compile shader (" + type + "): " + log);
}
return shader;
}
}
| true | true |
public GL20Program(GLContext ctx, GL20 gl, String vertexSource, String fragmentSource) {
this.gl = gl;
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = gl.glCreateProgram();
if (program == 0) {
throw new RuntimeException("Failed to create program: " + gl.glGetError());
}
vertexShader = compileShader(GL20.GL_VERTEX_SHADER, vertexSource);
gl.glAttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(GL20.GL_FRAGMENT_SHADER, fragmentSource);
gl.glAttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
gl.glLinkProgram(program);
int[] linkStatus = new int[1];
gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] == GL20.GL_FALSE) {
String log = gl.glGetProgramInfoLog(program);
gl.glDeleteProgram(program);
throw new RuntimeException("Failed to link program: " + log);
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
gl.glDeleteProgram(program);
if (vertexShader != 0)
gl.glDeleteShader(vertexShader);
if (fragmentShader != 0)
gl.glDeleteShader(program);
}
}
|
public GL20Program(GLContext ctx, GL20 gl, String vertexSource, String fragmentSource) {
this.gl = gl;
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = gl.glCreateProgram();
if (program == 0) {
throw new RuntimeException("Failed to create program: " + gl.glGetError());
}
vertexShader = compileShader(GL20.GL_VERTEX_SHADER, vertexSource);
gl.glAttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(GL20.GL_FRAGMENT_SHADER, fragmentSource);
gl.glAttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
gl.glLinkProgram(program);
int[] linkStatus = new int[1];
gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] == GL20.GL_FALSE) {
String log = gl.glGetProgramInfoLog(program);
gl.glDeleteProgram(program);
throw new RuntimeException("Failed to link program: " + log);
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
gl.glDeleteProgram(program);
if (vertexShader != 0)
gl.glDeleteShader(vertexShader);
if (fragmentShader != 0)
gl.glDeleteShader(fragmentShader);
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java
index c9901821..d5e3571d 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java
@@ -1,45 +1,51 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.Locale;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandrealname extends EssentialsCommand
{
public Commandrealname()
{
super("realname");
}
@Override
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
final String whois = args[0].toLowerCase(Locale.ENGLISH);
+ boolean foundUser = false;
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User u = ess.getUser(onlinePlayer);
if (u.isHidden())
{
continue;
}
u.setDisplayNick();
final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (!whois.equals(displayName)
&& !displayName.equals(Util.stripFormat(ess.getSettings().getNicknamePrefix()) + whois)
&& !whois.equalsIgnoreCase(u.getName()))
{
continue;
}
+ foundUser = true;
sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName());
}
+ if (!foundUser)
+ {
+ throw new NoSuchFieldException(_("playerNotFound"));
+ }
}
}
| false | true |
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
final String whois = args[0].toLowerCase(Locale.ENGLISH);
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User u = ess.getUser(onlinePlayer);
if (u.isHidden())
{
continue;
}
u.setDisplayNick();
final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (!whois.equals(displayName)
&& !displayName.equals(Util.stripFormat(ess.getSettings().getNicknamePrefix()) + whois)
&& !whois.equalsIgnoreCase(u.getName()))
{
continue;
}
sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName());
}
}
|
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
final String whois = args[0].toLowerCase(Locale.ENGLISH);
boolean foundUser = false;
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User u = ess.getUser(onlinePlayer);
if (u.isHidden())
{
continue;
}
u.setDisplayNick();
final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (!whois.equals(displayName)
&& !displayName.equals(Util.stripFormat(ess.getSettings().getNicknamePrefix()) + whois)
&& !whois.equalsIgnoreCase(u.getName()))
{
continue;
}
foundUser = true;
sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName());
}
if (!foundUser)
{
throw new NoSuchFieldException(_("playerNotFound"));
}
}
|
diff --git a/vlc-android/src/org/videolan/vlc/widget/AudioMediaSwitcher.java b/vlc-android/src/org/videolan/vlc/widget/AudioMediaSwitcher.java
index dc212102..284f0f25 100644
--- a/vlc-android/src/org/videolan/vlc/widget/AudioMediaSwitcher.java
+++ b/vlc-android/src/org/videolan/vlc/widget/AudioMediaSwitcher.java
@@ -1,157 +1,159 @@
/*****************************************************************************
* AudioMediaSwitcher.java
*****************************************************************************
* Copyright © 2011-2014 VLC authors and VideoLAN
*
* 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.widget;
import org.videolan.vlc.AudioServiceController;
import org.videolan.vlc.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class AudioMediaSwitcher extends FlingViewGroup {
private AudioMediaSwitcherListener mAudioMediaSwitcherListener;
private boolean hasPrevious;
private int previousPosition;
public AudioMediaSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
setOnViewSwitchedListener(mViewSwitchListener);
}
public void updateMedia() {
AudioServiceController audioController = AudioServiceController.getInstance();
if (audioController == null)
return;
removeAllViews();
hasPrevious = false;
previousPosition = 0;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (audioController.hasPrevious()) {
addMediaView(inflater,
audioController.getTitlePrev(),
audioController.getArtistPrev(),
audioController.getCoverPrev());
hasPrevious = true;
}
if (audioController.hasMedia())
addMediaView(inflater,
audioController.getTitle(),
audioController.getArtist(),
audioController.getCover());
if (audioController.hasNext())
addMediaView(inflater,
audioController.getTitleNext(),
audioController.getArtistNext(),
audioController.getCoverNext());
if (audioController.hasPrevious() && audioController.hasMedia()) {
previousPosition = 1;
scrollTo(1);
}
+ else
+ scrollTo(0);
}
private void addMediaView(LayoutInflater inflater, String title, String artist, Bitmap cover) {
View v = inflater.inflate(R.layout.audio_media_switcher_item, this, false);
ImageView coverView = (ImageView) v.findViewById(R.id.cover);
TextView titleView = (TextView) v.findViewById(R.id.title);
TextView artistView = (TextView) v.findViewById(R.id.artist);
if (cover != null) {
coverView.setVisibility(VISIBLE);
coverView.setImageBitmap(cover);
}
titleView.setText(title);
artistView.setText(artist);
addView(v);
}
private final ViewSwitchListener mViewSwitchListener = new ViewSwitchListener() {
@Override
public void onSwitching(float progress) {
if (mAudioMediaSwitcherListener != null)
mAudioMediaSwitcherListener.onMediaSwitching();
}
@Override
public void onSwitched(int position) {
if (mAudioMediaSwitcherListener != null)
{
if (previousPosition != position) {
if (position == 0 && hasPrevious)
mAudioMediaSwitcherListener.onMediaSwitched(AudioMediaSwitcherListener.PREVIOUS_MEDIA);
if (position == 1 && !hasPrevious)
mAudioMediaSwitcherListener.onMediaSwitched(AudioMediaSwitcherListener.NEXT_MEDIA);
else if (position == 2)
mAudioMediaSwitcherListener.onMediaSwitched(AudioMediaSwitcherListener.NEXT_MEDIA);
previousPosition = position;
}
else
mAudioMediaSwitcherListener.onMediaSwitched(AudioMediaSwitcherListener.CURRENT_MEDIA);
}
}
@Override
public void onTouchDown() {
if (mAudioMediaSwitcherListener != null)
mAudioMediaSwitcherListener.onTouchDown();
}
@Override
public void onTouchUp() {
if (mAudioMediaSwitcherListener != null)
mAudioMediaSwitcherListener.onTouchUp();
}
};
public void setAudioMediaSwitcherListener(AudioMediaSwitcherListener l) {
mAudioMediaSwitcherListener = l;
}
public static interface AudioMediaSwitcherListener {
public final static int PREVIOUS_MEDIA = 1;
public final static int CURRENT_MEDIA = 2;
public final static int NEXT_MEDIA = 3;
void onMediaSwitching();
void onMediaSwitched(int position);
void onTouchDown();
void onTouchUp();
}
}
| true | true |
public void updateMedia() {
AudioServiceController audioController = AudioServiceController.getInstance();
if (audioController == null)
return;
removeAllViews();
hasPrevious = false;
previousPosition = 0;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (audioController.hasPrevious()) {
addMediaView(inflater,
audioController.getTitlePrev(),
audioController.getArtistPrev(),
audioController.getCoverPrev());
hasPrevious = true;
}
if (audioController.hasMedia())
addMediaView(inflater,
audioController.getTitle(),
audioController.getArtist(),
audioController.getCover());
if (audioController.hasNext())
addMediaView(inflater,
audioController.getTitleNext(),
audioController.getArtistNext(),
audioController.getCoverNext());
if (audioController.hasPrevious() && audioController.hasMedia()) {
previousPosition = 1;
scrollTo(1);
}
}
|
public void updateMedia() {
AudioServiceController audioController = AudioServiceController.getInstance();
if (audioController == null)
return;
removeAllViews();
hasPrevious = false;
previousPosition = 0;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (audioController.hasPrevious()) {
addMediaView(inflater,
audioController.getTitlePrev(),
audioController.getArtistPrev(),
audioController.getCoverPrev());
hasPrevious = true;
}
if (audioController.hasMedia())
addMediaView(inflater,
audioController.getTitle(),
audioController.getArtist(),
audioController.getCover());
if (audioController.hasNext())
addMediaView(inflater,
audioController.getTitleNext(),
audioController.getArtistNext(),
audioController.getCoverNext());
if (audioController.hasPrevious() && audioController.hasMedia()) {
previousPosition = 1;
scrollTo(1);
}
else
scrollTo(0);
}
|
diff --git a/testing_tool/src/main/java/edu/ch/unifr/diuf/testing_tool/Coordinator.java b/testing_tool/src/main/java/edu/ch/unifr/diuf/testing_tool/Coordinator.java
index 05930fd..f404094 100644
--- a/testing_tool/src/main/java/edu/ch/unifr/diuf/testing_tool/Coordinator.java
+++ b/testing_tool/src/main/java/edu/ch/unifr/diuf/testing_tool/Coordinator.java
@@ -1,377 +1,378 @@
package edu.ch.unifr.diuf.testing_tool;
import net.schmizz.sshj.transport.TransportException;
import org.apache.commons.configuration.ConfigurationException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This object is supposed to control everything it is running.
*
* @author Teodor Macicas
*/
public class Coordinator
{
private final static Logger LOGGER = Logger.getLogger(
Coordinator.class.getName());
public static void main(String... args) throws TransportException, IOException {
MachineManager mm = new MachineManager();
try {
System.out.println("Parsing properties file ...");
mm.parsePropertiesFile();
}
catch( WrongIpAddressException |
WrongPortNumberException|
ClientNotProperlyInitException ex ) {
LOGGER.log(Level.SEVERE, "Error while setting up a machine. " + ex.getMessage());
System.exit(1);
}
catch( ConfigurationException ex4 ) {
LOGGER.log(Level.SEVERE, ex4.getMessage());
System.exit(4);
}
catch( FileNotFoundException ex5 ) {
LOGGER.log(Level.SEVERE, ex5.getMessage());
System.exit(5);
}
catch( UnwritableWorkingDirectoryException ex6 ) {
LOGGER.log(Level.SEVERE, "Either working directory of the server "
+ " or of a client is not writable. " + ex6.getMessage());
System.exit(56);
}
catch( Exception ex7 ) {
LOGGER.log(Level.SEVERE, "Please verify if all needed parameters are "
+ "declared in the properties file." , ex7);
System.exit(56);
}
// print the machines and tests that have been created according to the properties file
System.out.println(mm.printMachines());
System.out.println(mm.printTests());
System.out.println("[INFO] Create the ssh clients for current thread ...");
mm.createSSHClients();
// are clients set up?
if( ! mm.checkIfClientsSet() ) {
LOGGER.severe("Clients are not yet configured. "
+ "Please do so before you start once again.");
System.exit(6);
}
+ /*
// are either all or none loopback addresses used?
if( ! mm.checkIfAllOrNoneLoopbackAddresses() ) {
LOGGER.severe("Please either use loopback addresses for all clients "
+ "and server OR non-loopback for all machines. This will be "
+ "more probably they can reach other.");
System.exit(7);
- }
+ } */
System.out.println("[INFO] Checking if all clients can ping the server ...");
try {
// can all clients, at least, ping the server?
if( ! mm.checkClientsCanAccessServer() ) {
LOGGER.severe("Not all clients can ping the server. Check once again "
+ "the IP addresses and/or the network status.");
System.exit(8);
}
} catch (TransportException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
}
System.out.println("[INFO] All clients have network connection with server.");
// delete local .data files
/*try {
Runtime.getRuntime().exec("/bin/bash rm log*.data").waitFor();
} catch (IOException|InterruptedException ex) {
Logger.getLogger(Coordinator.class.getName()).log(Level.SEVERE, null, ex);
}*/
// upload the programs to clients
try {
System.out.println("[INFO] Start uploading the program to clients ...");
mm.uploadProgramToClients();
} catch (TransportException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage());
System.exit(9);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage());
System.exit(10);
}
// now start the connectivity and status threads
System.out.println("[INFO] Start the connectivity thread. "
+ "NOTE: if public-key auth is used then this may take some time ...");
mm.startConnectivityThread();
System.out.println("[INFO] Checking if all machines are in a runnable state ...");
try {
// check if all are ok ...
// sleep a bit before checking, to allow some time for the coordinator
// to contact each client
Thread.sleep(2000);
int retries = 10;
while( ! mm.allAreConnectionsOK() && retries > 0 ) {
--retries;
LOGGER.info(" There are some machines that have either ssh problems "
+ "or just connectivity problems. Wait and retry (left "
+ "#retries: " + retries + ").");
Thread.sleep(10000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("[INFO] ALL machines checked and they are in a runnable state.");
System.out.println("[INFO] Starting the threads for checking connectivity, status and running PIDs. "
+ "NOTE: if public-key auth is used then this may take some time ...");
// now start all the other thread as the connectity at this point should be ok
mm.startOtherThreads();
// run tests
List<TestParams> testParamsList = mm.getTests();
Coordinator coord = new Coordinator();
for(TestParams test: testParamsList) {
// delete here the output dir for this test (if there was a previous run with old files)
String currentDir = new java.io.File( "." ).getCanonicalPath();
String testDir = currentDir+"/"+test.getFullTestName()+"/";
try {
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c", "rm -r " + testDir}).waitFor();
Runtime.getRuntime().exec(new String[]{"/bin/bash","-c", "mkdir " + testDir}).waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// multiple thread numbers
for( Iterator it=test.getTestThreadNum().iterator(); it.hasNext(); ) {
int thread_num = (int)it.next();
// one test can be run multiple times
for (int i = 0; i < test.getTestNum(); i++) {
// set server related params
mm.getServer().setSourceGraph(test.getTestServerSourceGraphName());
mm.getServer().setDestGraph(test.getTestServerDestGraphName());
mm.getServer().setGraphReset(test.getTestServerGraphReset());
mm.getServer().setReadCons(test.getTestReadCons());
mm.getServer().setWriteCons(test.getTestWriteCons());
mm.getServer().setTransLockGran(test.getTransLockGran());
mm.getServer().setReplFactor(test.getReplicationFactor());
mm.getServer().setCheckMyWritesMode(test.getCheckMyWritesMode());
mm.getServer().setTestName(test.getFullTestName());
// set client related params
for(int k = 0; k < mm.getClientsNum(); k++) {
//mm.getClientNo(j).setInputFilename(test.getTestInputFilename());
mm.getClientNo(k).setNoThreads(thread_num);
mm.getClientNo(k).setWarmupPeriod(test.getTestWarmupPer());
mm.getClientNo(k).setRunningPeriod(test.getTestRunningPer());
mm.getClientNo(k).setOperationType(test.getTestOperationType());
mm.getClientNo(k).setOperationNum(test.getTestOperationNum());
mm.getClientNo(k).setTransRetrials(test.getTestTransRetrials());
mm.getClientNo(k).setDiffE(test.getDiffEnt());
mm.getClientNo(k).setDiffPperE(test.getDiffPropPerEnt());
mm.getClientNo(k).setDiffVperP(test.getDiffValuesPerProp());
mm.getClientNo(k).setConflictsFlag(test.getConflictsParameter());
}
StringBuilder sbTest = new StringBuilder("[INFO] Test with parameters: ");
sbTest.append(test.getTestServerSourceGraphName()).append("/").append(test.getTestServerDestGraphName()).
append(" ").append(test.getTestServerGraphReset()).append(" ").
append(test.getTestReadCons()).append(" ").append(test.getTestWriteCons()).append(" ").
append(test.getTransLockGran()).append(" ").append(test.getReplicationFactor()).append(" ").
append(thread_num).append(" ").append(test.getTestRunningPer()).append(" ").
append(test.getTestWarmupPer()).append(" ").append(test.getTestOperationType()).append(" ").
append(test.getTestOperationNum()).append(" ").append(test.getTestTransRetrials()).append(" ").
append(test.getCheckMyWritesMode());
System.out.println(sbTest.toString());
// before starting the clients, lets check if the data inputfile exists remotely
Client c = mm.checkClientsRemoteDatafiles();
if( c != null ) {
System.out.println("[FAIL] Client " + c.getId() + " " + c.getIpAddress() +
" lacks of the input filename " + Utils.getClientRemoteDataFilename(c));
break;
}
coord.runClients(mm, sbTest.toString(), test.getFinalRestultFilename(), i);
/* try {
System.out.println("Sleep 10s in between each test ... ");
Thread.sleep(10000);
} catch( InterruptedException ex ) { } */
}
}
// one test scenario is done here, parse the output file
Parser p = new Parser(testDir+test.getFinalRestultFilename(),
testDir+"data-for-plot.running", mm.getClientsNum(), test.getTestNum());
p.parseFileRunningStats();
Parser p_vers = new Parser(testDir+test.getFinalRestultFilename()+".vers",
testDir+"data-for-plot.vers", mm.getClientsNum(), test.getTestNum());
p_vers.parseFileVersionsStats();
try {
// make a pause inbetween tests
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("[INFO] Now join all threads ...");
mm.joinAllThreads();
System.out.println("[INFO] Now disconnect SSH clients and exit ...");
mm.disconnectSSHClients(mm.getSSHClients());
}
/**
*
* @param mm
* @param testName
*/
private void runClients(MachineManager mm, String testName,
String finalResultFilename, int testNo) {
RunClient rc = new RunClient(mm, mm.getServer().getRestartAttempts(), testName,
finalResultFilename, testNo);
rc.start();
if( mm.getServer().getFaultTolerant().equals("yes") ) {
mm.startFaultTolerantThread(rc);
}
try {
rc.join();
mm.joinFaultTolerantThread();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
//get status
if( rc.status != 0 )
LOGGER.log(Level.SEVERE, "Test " + testName + " could not be run. ");
else
LOGGER.log(Level.INFO, "Test " + testName + " was successfully run. ");
}
// it runs the server and client for a given test
// this thread may be interrupted in case of failure
class RunClient extends Thread
{
private MachineManager mm;
private int no_retrials;
private int status;
private String testName;
private String resultFile;
private int testNo;
public RunClient(MachineManager mm, Integer retrials,
String testName, String finalResultFilename, int testNo) {
this.mm = mm;
this.no_retrials = retrials;
this.testName = testName;
this.resultFile = finalResultFilename;
this.testNo = testNo;
}
public void run() {
while( true ) {
try {
if( no_retrials < 0 ) {
// this means all retrials have been tried, but without any success
status = 1;
break;
}
runClients(mm);
status = 0;
break;
} catch (RerunTestException ex) {
--no_retrials;
LOGGER.log(Level.INFO, "Test " + ex.getMessage() + " could not be run "
+ "due to too many failing clients. Retry ... " + no_retrials
+ " retrials remaining");
}
}
}
// start server and client program, synchronize, run test, fetch the logs
// NOTE: this can be interrupted by the fault tolerant thread
private void runClients(MachineManager mm) throws RerunTestException {
try {
System.out.println("[INFO] Deleting any data from previous run ...");
// delete client logs
mm.deleteClientLogs();
// delete from each client the files that might have been used before
mm.deleteClientPreviouslyMessages();
// run the clients remotely
System.out.println("[INFO] START the clients ... and wait some time ... ");
mm.startAllClients();
// check if all clients are synchronized
while( true ) {
if( ! mm.checkClientsSynch() ) {
System.out.println("[INFO] Clients are not yet ready for warmup. "
+ "Wait more time ... ");
Thread.sleep(3000);
}
else
break;
}
System.out.println("[INFO] Clients' are ready for warmup. Now start sending requests to global server.");
// send a message to the clients to start sending requests as they are now ready
mm.sendClientsMsgToStartRequests();
System.out.println("[INFO] All clients are now sending requests to the server.");
// check if tests are completed
while( true ) {
if( ! mm.checkTestsCompletion() ) {
System.out.println("[INFO] Client tests are not done yet ... wait more.");
Thread.sleep(5000);
}
else
break;
}
System.out.println("[INFO] Client tests are done.");
System.out.println("[INFO] Now locally download the logs from the clients. Final results to file "
+ resultFile);
mm.downloadAllLogs(resultFile, testNo);
System.out.println("[INFO] All the logs are downloaded. For further information "
+ "please check them.");
}
catch (Exception ex) {
if( (ex.getCause() != null && ex.getCause() instanceof InterruptedException)
|| ex instanceof InterruptedException ) {
// if the cause is InterruptedException, most probably, it has been thrown
// by the fault tolerant thread
System.out.println("[FAULT TOLERANCE] The condition of dead clients "
+ "has been reached. Restart the server and the clients for "
+ "the test " + testName + " ... ");
throw new RerunTestException(testName);
}
else
LOGGER.log(Level.SEVERE,"[EXCEPTION] ", ex);
}
finally {
// even if success or failure, kill clients and server
try {
System.out.println("[INFO] Kill all the clients (if they are still running) ... ");
mm.killClients();
} catch (Exception ex) {
Logger.getLogger(Coordinator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
class RerunTestException extends Exception
{
public RerunTestException(String string) {
super(string);
}
}
| false | true |
public static void main(String... args) throws TransportException, IOException {
MachineManager mm = new MachineManager();
try {
System.out.println("Parsing properties file ...");
mm.parsePropertiesFile();
}
catch( WrongIpAddressException |
WrongPortNumberException|
ClientNotProperlyInitException ex ) {
LOGGER.log(Level.SEVERE, "Error while setting up a machine. " + ex.getMessage());
System.exit(1);
}
catch( ConfigurationException ex4 ) {
LOGGER.log(Level.SEVERE, ex4.getMessage());
System.exit(4);
}
catch( FileNotFoundException ex5 ) {
LOGGER.log(Level.SEVERE, ex5.getMessage());
System.exit(5);
}
catch( UnwritableWorkingDirectoryException ex6 ) {
LOGGER.log(Level.SEVERE, "Either working directory of the server "
+ " or of a client is not writable. " + ex6.getMessage());
System.exit(56);
}
catch( Exception ex7 ) {
LOGGER.log(Level.SEVERE, "Please verify if all needed parameters are "
+ "declared in the properties file." , ex7);
System.exit(56);
}
// print the machines and tests that have been created according to the properties file
System.out.println(mm.printMachines());
System.out.println(mm.printTests());
System.out.println("[INFO] Create the ssh clients for current thread ...");
mm.createSSHClients();
// are clients set up?
if( ! mm.checkIfClientsSet() ) {
LOGGER.severe("Clients are not yet configured. "
+ "Please do so before you start once again.");
System.exit(6);
}
// are either all or none loopback addresses used?
if( ! mm.checkIfAllOrNoneLoopbackAddresses() ) {
LOGGER.severe("Please either use loopback addresses for all clients "
+ "and server OR non-loopback for all machines. This will be "
+ "more probably they can reach other.");
System.exit(7);
}
System.out.println("[INFO] Checking if all clients can ping the server ...");
try {
// can all clients, at least, ping the server?
if( ! mm.checkClientsCanAccessServer() ) {
LOGGER.severe("Not all clients can ping the server. Check once again "
+ "the IP addresses and/or the network status.");
System.exit(8);
}
} catch (TransportException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
}
System.out.println("[INFO] All clients have network connection with server.");
// delete local .data files
/*try {
Runtime.getRuntime().exec("/bin/bash rm log*.data").waitFor();
} catch (IOException|InterruptedException ex) {
|
public static void main(String... args) throws TransportException, IOException {
MachineManager mm = new MachineManager();
try {
System.out.println("Parsing properties file ...");
mm.parsePropertiesFile();
}
catch( WrongIpAddressException |
WrongPortNumberException|
ClientNotProperlyInitException ex ) {
LOGGER.log(Level.SEVERE, "Error while setting up a machine. " + ex.getMessage());
System.exit(1);
}
catch( ConfigurationException ex4 ) {
LOGGER.log(Level.SEVERE, ex4.getMessage());
System.exit(4);
}
catch( FileNotFoundException ex5 ) {
LOGGER.log(Level.SEVERE, ex5.getMessage());
System.exit(5);
}
catch( UnwritableWorkingDirectoryException ex6 ) {
LOGGER.log(Level.SEVERE, "Either working directory of the server "
+ " or of a client is not writable. " + ex6.getMessage());
System.exit(56);
}
catch( Exception ex7 ) {
LOGGER.log(Level.SEVERE, "Please verify if all needed parameters are "
+ "declared in the properties file." , ex7);
System.exit(56);
}
// print the machines and tests that have been created according to the properties file
System.out.println(mm.printMachines());
System.out.println(mm.printTests());
System.out.println("[INFO] Create the ssh clients for current thread ...");
mm.createSSHClients();
// are clients set up?
if( ! mm.checkIfClientsSet() ) {
LOGGER.severe("Clients are not yet configured. "
+ "Please do so before you start once again.");
System.exit(6);
}
/*
// are either all or none loopback addresses used?
if( ! mm.checkIfAllOrNoneLoopbackAddresses() ) {
LOGGER.severe("Please either use loopback addresses for all clients "
+ "and server OR non-loopback for all machines. This will be "
+ "more probably they can reach other.");
System.exit(7);
} */
System.out.println("[INFO] Checking if all clients can ping the server ...");
try {
// can all clients, at least, ping the server?
if( ! mm.checkClientsCanAccessServer() ) {
LOGGER.severe("Not all clients can ping the server. Check once again "
+ "the IP addresses and/or the network status.");
System.exit(8);
}
} catch (TransportException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Exception catched while checking clients "
+ "network connection to the server.", ex);
System.exit(8);
}
System.out.println("[INFO] All clients have network connection with server.");
// delete local .data files
/*try {
Runtime.getRuntime().exec("/bin/bash rm log*.data").waitFor();
} catch (IOException|InterruptedException ex) {
|
diff --git a/src/gui/inventory/InventoryController.java b/src/gui/inventory/InventoryController.java
index f30daff..b5c488d 100644
--- a/src/gui/inventory/InventoryController.java
+++ b/src/gui/inventory/InventoryController.java
@@ -1,821 +1,825 @@
package gui.inventory;
import gui.common.Controller;
import gui.common.DataWrapper;
import gui.item.ItemData;
import gui.product.ProductData;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import mcontrollers.ItemListener;
import mcontrollers.ProductContainerListener;
import mcontrollers.ProductListener;
import model.Item;
import model.ItemManager;
import model.Product;
import model.ProductContainer;
import model.ProductGroup;
import model.ProductManager;
import model.StorageUnit;
/**
* Controller class for inventory view.
*/
public class InventoryController extends Controller implements IInventoryController {
/**
* Constructor.
*
* @param view
* Reference to the inventory view
*
* @pre view != null
* @post true
*/
public InventoryController(IInventoryView view) {
super(view);
new ProductContainerListener(getView(), getProductContainerManager());
new ItemListener(getView(), getItemManager());
new ProductListener(getView(), getProductManager());
construct();
}
/**
* This method is called when the user selects the "Add Items" menu item.
*
* @throws IllegalStateException
* if(!canAddItems())
*
* @pre canAddItems()
* @post true
*/
@Override
public void addItems() {
if (!canAddItems()) {
throw new IllegalStateException("Unable to add Items");
}
getView().displayAddItemBatchView();
}
/**
* This method is called when the user selects the "Add Product Group" menu item.
*
* @throws IllegalStateException
* if(!canAddProductGroup())
*
* @pre canAddProductGroup()
* @post true
*/
@Override
public void addProductGroup() {
if (!canAddProductGroup()) {
throw new IllegalStateException("Unable to add Product Groups");
}
getView().displayAddProductGroupView();
}
/**
* This method is called when the user drags a product into a product container.
*
* @param productData
* Product dragged into the target product container
* @param containerData
* Target product container
* @throws IllegalArgumentException
* if either parameter is null
* @throws IllegalStateException
* if either parameter's getTag() == null
*
* @pre productData != null && productData.getTag() != null
* @pre containerData != null && containerData.getTag() != null
* @post containerData.getChildCount() == old(getChildCount()) + 1
*/
@Override
public void addProductToContainer(ProductData productData,
ProductContainerData containerData) {
/*
* Desired Behavior
*
* Target Product Container = the Product Container the user dropped the Product on
*
* Target StorageUnit = the StorageUnit containing the Target Product Container
*
* If the Product is already contained in a Product Container in the Target StorageUnit
* Else Add the Product to the Target Product Container
*/
if (productData == null)
throw new IllegalArgumentException("ProductData should not be null");
if (containerData == null)
throw new IllegalArgumentException("ProductContainerData should not be null");
Product productToAdd = (Product) productData.getTag();
if (productToAdd == null)
throw new IllegalStateException("Product must have a tag.");
ProductContainer targetContainer = (ProductContainer) containerData.getTag();
if (targetContainer == null)
throw new IllegalStateException("ProductContainer must have a tag.");
ProductContainer oldContainer = getSelectedProductContainerTag();
- StorageUnit targetSU = getProductContainerManager().getRootStorageUnitByName(
- targetContainer.getName());
+ StorageUnit targetSU = getProductContainerManager().getRootStorageUnitForChild(
+ targetContainer);
// add product to container
if (targetSU.hasDescendantProductContainer(oldContainer)
|| targetSU.equals(oldContainer)) {
// Staying in the same tree, move items
// Get all the items
ItemManager itemManager = getItemManager();
Set<Item> itemsToMove = itemManager.getItemsByProduct(productToAdd);
// copy the items so we can loop over them to remove and add
Set<Item> itemsToRemove = new HashSet<Item>();
Set<Item> itemsToAdd = new HashSet<Item>();
for (Item item : itemsToMove) {
itemsToAdd.add(item);
itemsToRemove.add(item);
}
// remove the items so we can remove the product
for (Item item : itemsToRemove) {
oldContainer.remove(item, itemManager);
}
// remove the product
oldContainer.remove(productToAdd);
productToAdd.removeContainer(oldContainer);
// add the product to the target
productToAdd.addContainer(targetContainer);
targetContainer.add(productToAdd);
// add the items
for (Item item : itemsToAdd) {
targetContainer.add(item);
itemManager.manage(item);
}
} else {
- productToAdd.addContainer(targetContainer);
- targetContainer.add(productToAdd);
+ if (targetContainer.canAddProduct(productToAdd.getBarcode())) {
+ productToAdd.addContainer(targetContainer);
+ targetContainer.add(productToAdd);
+ } else {
+ getView().displayErrorMessage("Cannot move Product to that Container");
+ }
}
}
/**
* This method is called when the user selects the "Add Storage Unit" menu item.
*
* @throws IllegalStateException
* if(!canAddStorageUnit())
*
* @pre canAddStorageUnit()
* @post true
*/
@Override
public void addStorageUnit() {
if (!canAddStorageUnit()) {
throw new IllegalStateException("Unable to add Storage Units");
}
getView().displayAddStorageUnitView();
}
/**
* Returns true if and only if the "Add Items" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canAddItems() {
// Always enabled per Functional Spec p17
return true;
}
/**
* Returns true if and only if the "Add Product Group" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canAddProductGroup() {
// Always enabled per Functional Spec p15
return true;
}
/**
* Returns true if and only if the "Add Storage Unit" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canAddStorageUnit() {
// Always enabled per Functional Spec p14
return true;
}
/**
* Returns true if and only if the "Delete Product" menu item should be enabled.
*
* @pre if(getView().getSelectedProductContainer() != null)
* getView().getSelectedProductContainer().getTag() != null
* @pre if(getView().getSelectedProductContainer() != null) getSelectedProductTag() != null
* @post true
*
*/
@Override
public boolean canDeleteProduct() {
// 3 cases depending on getView().getSelectedProductContainer().
// See Functional Spec p21-22
// case 1: No product container is selected
if (getView().getSelectedProductContainer() == null)
return false;
ProductContainer containerTag = getSelectedProductContainerTag();
if (getView().getSelectedProduct() == null)
return false;
Product productTag = getSelectedProductTag();
// case 2: selected product container is the root node
if (containerTag == null) // root 'Storage Units' is assigned 'null' for its tag
return productTag.canRemove();
// case 3: selected product container is a child StorageUnit or ProductGroup
else
return containerTag.canRemove(productTag);
}
/**
* Returns true if and only if the "Delete Product Group" menu item should be enabled.
*
* @pre getView().getSelectedProductContainer() != null
* @pre getView().getSelectedProductContainer().getTag() instanceof ProductGroup
* @post true
*/
@Override
public boolean canDeleteProductGroup() {
// Enabled only if getView().getSelectedProductContainer() does not contain any
// items (including it's sub Product Groups)
// See Functional Spec p17
return getSelectedProductContainerTag().canRemove();
}
/**
* Returns true if and only if the "Delete Storage Unit" menu item should be enabled.
*
* @pre getView().getSelectedProductContainer() != null
* @pre getView().getSelectedProductContainer().getTag() instanceof StorageUnit
* @post true
*/
@Override
public boolean canDeleteStorageUnit() {
// Enabled only if getView().getSelectedProductContainer() does not contain any
// items (including it's Product Groups)
// See Functional Spec p15
if (getView().getSelectedProductContainer() == null)
return false;
return getSelectedProductContainerTag().canRemove();
}
/**
* Returns true if and only if the "Edit Item" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canEditItem() {
return getView().getSelectedItem() != null;
}
/**
* Returns true if and only if the "Edit Product" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canEditProduct() {
return getView().getSelectedProduct() != null;
}
/**
* Returns true if and only if the "Edit Product Group" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canEditProductGroup() {
ProductContainerData pcData = getView().getSelectedProductContainer();
return pcData != null && (pcData.getTag() instanceof ProductGroup);
}
/**
* Returns true if and only if the "Edit Storage Unit" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canEditStorageUnit() {
ProductContainerData pcData = getView().getSelectedProductContainer();
return pcData != null && (pcData.getTag() instanceof StorageUnit);
}
/**
* Returns true if and only if the "Remove Item" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canRemoveItem() {
ItemData id = getView().getSelectedItem();
return id != null && id.getTag() != null;
}
/**
* Returns true if and only if the "Remove Items" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canRemoveItems() {
ProductContainerData pcData = getView().getSelectedProductContainer();
return pcData.getTag() == null;
}
/**
* Returns true if and only if the "Transfer Items" menu item should be enabled.
*
* @pre true
* @post true
*/
@Override
public boolean canTransferItems() {
// Always enabled per Functional Spec p24
return true;
}
/**
* This method is called when the user selects the "Delete Product" menu item.
*
* @throws IllegalStateException
* if (!canDeleteProduct())
*
* @pre canDeleteProduct()
* @pre getSelectedProductTag() != null
* @post !getProductManager().contains(old(getView().getSelectedProduct().getTag()))
*/
@Override
public void deleteProduct() {
if (!canDeleteProduct()) {
throw new IllegalStateException("Unable to delete Product");
}
ProductContainer parent = (ProductContainer) getView().getSelectedProductContainer()
.getTag();
parent.remove(getSelectedProductTag());
getProductManager().unmanage(getSelectedProductTag());
}
/**
* This method is called when the user selects the "Delete Product Group" menu item.
*
* @throws IllegalStateException
* if (!canDeleteProductGroup())
*
* @pre canDeleteProductGroup()
* @pre getSelectedProductContainerTag() != null
* @post !getProductContainerManager().contains(PREVIOUS
* getView().getSelectedProductContainer().getTag())
*/
@Override
public void deleteProductGroup() {
if (!canDeleteProductGroup()) {
throw new IllegalStateException("Unable to delete Product Group");
}
deleteSelectedProductContainer();
}
/**
* This method is called when the user selects the "Delete Storage Unit" menu item.
*
* @throws IllegalStateException
* if (!canDeleteStorageUnit())
*
* @pre canDeleteStorageUnit()
* @pre getSelectedProductContainerTag() != null
* @post !getProductContainerManager().contains(PREVIOUS
* getView().getSelectedProductContainer().getTag())
*/
@Override
public void deleteStorageUnit() {
if (!canDeleteStorageUnit()) {
throw new IllegalStateException("Unable to delete Storage Unit");
}
deleteSelectedProductContainer();
}
/**
* This method is called when the user selects the "Edit Item" menu item.
*
* @throws IllegalStateException
* if (!canEditItem())
*
* @pre canEditItem()
* @post getItemManager().contains(old(getView().getSelectedItem().getTag()))
*/
@Override
public void editItem() {
ItemData selectedItem = getView().getSelectedItem();
if (!canEditItem()) {
throw new IllegalStateException("Unable to edit Item");
}
getView().displayEditItemView();
getView().selectItem(selectedItem);
}
/**
* This method is called when the user selects the "Edit Product" menu item.
*
* @throws IllegalStateException
* if (!canEditProduct())
*
* @pre canEditProduct()
* @post getProductManager().contains(old(getView().getSelectedProduct().getTag()))
*/
@Override
public void editProduct() {
if (!canEditProduct()) {
throw new IllegalStateException("Unable to edit Product");
}
getView().displayEditProductView();
}
/**
* This method is called when the user selects the "Edit Product Group" menu item.
*
* @throws IllegalStateException
* if (!canEditProductGroup)
*
* @pre canEditProductGroup()
* @post getProductContainerManager().contains(PREVIOUS
* getView().getSelectedProductContainer().getTag())
*/
@Override
public void editProductGroup() {
if (!canEditProductGroup()) {
throw new IllegalStateException("Unable to edit Product Group");
}
getView().displayEditProductGroupView();
}
/**
* This method is called when the user selects the "Edit Storage Unit" menu item.
*
* @throws IllegalStateException
* if (!canEditStorageUnit())
*
* @pre canEditStorageUnit()
* @post getProductContainerManager().contains(PREVIOUS
* getView().getSelectedProductContainer().getTag())
*/
@Override
public void editStorageUnit() {
if (!canEditStorageUnit()) {
throw new IllegalStateException("Unable to edit Storage Unit");
}
getView().displayEditStorageUnitView();
}
/**
* This method is called when the selected item changes.
*
* @pre true
* @post true
*/
@Override
public void itemSelectionChanged() {
// The only possible change is in the context menus available
enableComponents();
}
/**
* This method is called when the user drags an item into a product container.
*
* @param itemData
* Item dragged into the target product container
* @param containerData
* Target product container
*
* @throws IllegalArgumentException
* if either parameter is null
*
* @throws IllegalArgumentException
* if either parameter is null
* @throws IllegalStateException
* if the target product container doesn't have a tag
*
* @pre itemData != null
* @pre containerData != null
* @pre getView().getSelectedProductContainer() != null
* @pre getView().getSelectedProductContainer().getTag().contains(itemData.getTag())
* @pre !containerData.getTag().contains(itemData.getTag())
* @post !old(getView().getSelectedProductContainer().getTag().contains(itemData.getTag()))
* @post containerData.getTag().contains(itemData.getTag())
*
*/
@Override
public void moveItemToContainer(ItemData itemData, ProductContainerData containerData) {
if (itemData == null)
throw new NullPointerException("ItemData should not be null.");
if (containerData == null)
throw new NullPointerException("ProductContainerData should not be null.");
ProductContainer targetContainer = (ProductContainer) containerData.getTag();
if (targetContainer == null)
throw new NullPointerException("Target product container must have a tag.");
// note: the currently-selected ProductContainer is the source
getSelectedProductContainerTag().moveIntoContainer(getSelectedItemTag(),
targetContainer);
}
/**
* This method is called when the selected item container changes.
*
* @pre true
* @post true
*/
@Override
public void productContainerSelectionChanged() {
// Load Products in selected ProductContainer
List<ProductData> productDataList = new ArrayList<ProductData>();
ProductContainerData selectedContainer = getView().getSelectedProductContainer();
if (selectedContainer != null) {
ProductContainer selected = (ProductContainer) selectedContainer.getTag();
if (selected != null) {
Iterator<Product> it = selected.getProductsIterator();
while (it.hasNext()) {
Product p = it.next();
int count = selected.getItemsForProduct(p).size();
productDataList.add(DataWrapper.wrap(p, count));
}
// Update contextView
ProductContainer currentContainer = (ProductContainer) selectedContainer
.getTag();
if (currentContainer instanceof StorageUnit) {
getView().setContextGroup("");
getView().setContextSupply("");
getView().setContextUnit(selectedContainer.getName());
} else if (currentContainer instanceof ProductGroup) {
ProductGroup group = (ProductGroup) currentContainer;
StorageUnit root = getView().getProductContainerManager()
.getRootStorageUnitForChild(group);
getView().setContextGroup(group.getName());
getView().setContextSupply(group.getThreeMonthSupply().toString());
getView().setContextUnit(root.getName());
}
} else {
// Root "Storage units" node is selected; display all Products in system
ProductManager manager = getProductManager();
Set<Product> products = manager.getProducts();
for (Product product : products) {
productDataList.add(DataWrapper.wrap(product, product.getItemCount()));
}
getView().setContextUnit("All");
}
}
getView().setProducts(productDataList.toArray(new ProductData[0]));
// Clear ItemTable
List<ItemData> itemDataList = new ArrayList<ItemData>();
getView().setItems(itemDataList.toArray(new ItemData[0]));
}
/**
* This method is called when the selected product changes.
*
* @pre true
* @post true
*/
@Override
public void productSelectionChanged() {
ArrayList<ItemData> itemsToDisplay = new ArrayList<ItemData>();
ProductData selectedProduct = getView().getSelectedProduct();
if (selectedProduct != null) {
Product product = (Product) selectedProduct.getTag();
ProductContainerData pcData = getView().getSelectedProductContainer();
if (pcData == null)
throw new NullPointerException("Selected product container should not be null");
ProductContainer container = (ProductContainer) pcData.getTag();
Iterator<Item> itemIterator;
// Root container is selected
if (container == null) {
itemIterator = product.getItemsIterator();
} else {
itemIterator = container.getItemsForProduct(product).iterator();
}
while (itemIterator.hasNext()) {
ItemData id = DataWrapper.wrap(itemIterator.next());
itemsToDisplay.add(id);
}
}
getView().setItems(itemsToDisplay.toArray(new ItemData[0]));
}
/**
* This method is called when the user selects the "Remove Item" menu item.
*
* @throws IllegalStateException
* if !canRemoveItem()
*
* @pre canRemoveItem()
* @pre getSelectedItemTag() != null
* @post !getItemManager().contains(old(getView().getSelectedItem().getTag()))
*/
@Override
public void removeItem() {
if (!canRemoveItem()) {
throw new IllegalStateException("Unable to remove Item");
}
ItemData itemData = getView().getSelectedItem();
if (itemData == null)
throw new NullPointerException("ItemData object should not be null");
Item item = (Item) itemData.getTag();
if (item == null)
throw new NullPointerException("Item object should not be null");
Product itemsProduct = item.getProduct();
if (itemsProduct == null)
throw new NullPointerException("Item should always have a product");
ItemManager itemManager = getItemManager();
ProductContainer container = item.getContainer();
container.remove(item, itemManager);
// update view
Set<Item> pcItems = container.getItemsForProduct(itemsProduct);
ItemData[] viewItems = new ItemData[pcItems.size()];
Iterator<Item> it = pcItems.iterator();
int counter = 0;
while (it.hasNext())
viewItems[counter++] = DataWrapper.wrap(it.next());
getView().setItems(viewItems);
}
/**
* This method is called when the user selects the "Remove Items" menu item.
*
* @throws IllegalStateException
* if(!canRemoveItems())
*
* @pre canRemoveItems()
* @post itemManager (from getItemManager() ) no longer contains any of the items matching
* those removed by the user.
*/
@Override
public void removeItems() {
if (!canRemoveItems()) {
throw new IllegalStateException("Unable to remove Items");
}
getView().displayRemoveItemBatchView();
}
/**
* This method is called when the user selects the "Transfer Items" menu item.
*
* @throws IllegalStateException
* if(!canTransferItems())
*
* @pre canTransferItems()
* @post true
*/
@Override
public void transferItems() {
if (!canTransferItems()) {
throw new IllegalStateException("Unable to edit Storage Unit");
}
getView().displayTransferItemBatchView();
}
/**
*
*/
public void updateView() {
// TODO: Implement me all in one place from InventoryListener so we can reduce code
// duplication!
}
private void deleteSelectedProductContainer() {
ProductContainer selectedSU = getSelectedProductContainerTag();
assert (selectedSU != null);
getProductContainerManager().unmanage(selectedSU);
}
private Item getSelectedItemTag() {
ItemData selectedItem = getView().getSelectedItem();
assert (selectedItem != null);
Item selectedTag = (Item) selectedItem.getTag();
assert (selectedTag != null);
return selectedTag;
}
private ProductContainer getSelectedProductContainerTag() {
ProductContainerData selectedPC = getView().getSelectedProductContainer();
assert (selectedPC != null);
ProductContainer selectedTag = (ProductContainer) selectedPC.getTag();
assert (selectedTag != null);
return selectedTag;
}
private Product getSelectedProductTag() {
ProductData selectedProduct = getView().getSelectedProduct();
assert (selectedProduct != null);
Product selectedTag = (Product) selectedProduct.getTag();
assert (selectedTag != null);
return selectedTag;
}
private ProductContainerData loadProductContainerData(ProductContainerData parentData,
ProductContainer container) {
ProductContainerData pcData = new ProductContainerData(container.getName());
pcData.setTag(container);
parentData.addChild(pcData);
Iterator<ProductGroup> productGroupIterator = container.getProductGroupIterator();
while (productGroupIterator.hasNext()) {
ProductGroup child = productGroupIterator.next();
pcData = loadProductContainerData(pcData, child);
}
return parentData;
}
/**
* Sets the enable/disable state of all components in the controller's view. A component
* should be enabled only if the user is currently allowed to interact with that component.
*
* {@pre None}
*
* {@post The enable/disable state of all components in the controller's view have been set
* appropriately.}
*/
@Override
protected void enableComponents() {
return;
}
/**
* Returns a reference to the view for this controller.
*/
@Override
protected IInventoryView getView() {
return (IInventoryView) super.getView();
}
/**
* Loads data into the controller's view.
*
* {@pre None}
*
* {@post The controller has loaded data into its view}
*/
@Override
protected void loadValues() {
ProductContainerData root = new ProductContainerData();
root.setTag(null);
Iterator<StorageUnit> storageUnitIterator = getProductContainerManager()
.getStorageUnitIterator();
while (storageUnitIterator.hasNext()) {
ProductContainer pc = storageUnitIterator.next();
root = loadProductContainerData(root, pc);
}
getView().setProductContainers(root);
}
}
| false | true |
public void addProductToContainer(ProductData productData,
ProductContainerData containerData) {
/*
* Desired Behavior
*
* Target Product Container = the Product Container the user dropped the Product on
*
* Target StorageUnit = the StorageUnit containing the Target Product Container
*
* If the Product is already contained in a Product Container in the Target StorageUnit
* Else Add the Product to the Target Product Container
*/
if (productData == null)
throw new IllegalArgumentException("ProductData should not be null");
if (containerData == null)
throw new IllegalArgumentException("ProductContainerData should not be null");
Product productToAdd = (Product) productData.getTag();
if (productToAdd == null)
throw new IllegalStateException("Product must have a tag.");
ProductContainer targetContainer = (ProductContainer) containerData.getTag();
if (targetContainer == null)
throw new IllegalStateException("ProductContainer must have a tag.");
ProductContainer oldContainer = getSelectedProductContainerTag();
StorageUnit targetSU = getProductContainerManager().getRootStorageUnitByName(
targetContainer.getName());
// add product to container
if (targetSU.hasDescendantProductContainer(oldContainer)
|| targetSU.equals(oldContainer)) {
// Staying in the same tree, move items
// Get all the items
ItemManager itemManager = getItemManager();
Set<Item> itemsToMove = itemManager.getItemsByProduct(productToAdd);
// copy the items so we can loop over them to remove and add
Set<Item> itemsToRemove = new HashSet<Item>();
Set<Item> itemsToAdd = new HashSet<Item>();
for (Item item : itemsToMove) {
itemsToAdd.add(item);
itemsToRemove.add(item);
}
// remove the items so we can remove the product
for (Item item : itemsToRemove) {
oldContainer.remove(item, itemManager);
}
// remove the product
oldContainer.remove(productToAdd);
productToAdd.removeContainer(oldContainer);
// add the product to the target
productToAdd.addContainer(targetContainer);
targetContainer.add(productToAdd);
// add the items
for (Item item : itemsToAdd) {
targetContainer.add(item);
itemManager.manage(item);
}
} else {
productToAdd.addContainer(targetContainer);
targetContainer.add(productToAdd);
}
}
|
public void addProductToContainer(ProductData productData,
ProductContainerData containerData) {
/*
* Desired Behavior
*
* Target Product Container = the Product Container the user dropped the Product on
*
* Target StorageUnit = the StorageUnit containing the Target Product Container
*
* If the Product is already contained in a Product Container in the Target StorageUnit
* Else Add the Product to the Target Product Container
*/
if (productData == null)
throw new IllegalArgumentException("ProductData should not be null");
if (containerData == null)
throw new IllegalArgumentException("ProductContainerData should not be null");
Product productToAdd = (Product) productData.getTag();
if (productToAdd == null)
throw new IllegalStateException("Product must have a tag.");
ProductContainer targetContainer = (ProductContainer) containerData.getTag();
if (targetContainer == null)
throw new IllegalStateException("ProductContainer must have a tag.");
ProductContainer oldContainer = getSelectedProductContainerTag();
StorageUnit targetSU = getProductContainerManager().getRootStorageUnitForChild(
targetContainer);
// add product to container
if (targetSU.hasDescendantProductContainer(oldContainer)
|| targetSU.equals(oldContainer)) {
// Staying in the same tree, move items
// Get all the items
ItemManager itemManager = getItemManager();
Set<Item> itemsToMove = itemManager.getItemsByProduct(productToAdd);
// copy the items so we can loop over them to remove and add
Set<Item> itemsToRemove = new HashSet<Item>();
Set<Item> itemsToAdd = new HashSet<Item>();
for (Item item : itemsToMove) {
itemsToAdd.add(item);
itemsToRemove.add(item);
}
// remove the items so we can remove the product
for (Item item : itemsToRemove) {
oldContainer.remove(item, itemManager);
}
// remove the product
oldContainer.remove(productToAdd);
productToAdd.removeContainer(oldContainer);
// add the product to the target
productToAdd.addContainer(targetContainer);
targetContainer.add(productToAdd);
// add the items
for (Item item : itemsToAdd) {
targetContainer.add(item);
itemManager.manage(item);
}
} else {
if (targetContainer.canAddProduct(productToAdd.getBarcode())) {
productToAdd.addContainer(targetContainer);
targetContainer.add(productToAdd);
} else {
getView().displayErrorMessage("Cannot move Product to that Container");
}
}
}
|
diff --git a/src/protocol/swg/objectControllerObjects/Animation.java b/src/protocol/swg/objectControllerObjects/Animation.java
index c3475969..751b6f1a 100644
--- a/src/protocol/swg/objectControllerObjects/Animation.java
+++ b/src/protocol/swg/objectControllerObjects/Animation.java
@@ -1,75 +1,75 @@
/*******************************************************************************
* Copyright (c) 2013 <Project SWG>
*
* This File is part of NGECore2.
*
* 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/>.
*
* Using NGEngine to work with NGECore2 is making a combined work based on NGEngine.
* Therefore all terms and conditions of the GNU Lesser General Public License cover the combination.
******************************************************************************/
package protocol.swg.objectControllerObjects;
import java.nio.ByteOrder;
import org.apache.mina.core.buffer.IoBuffer;
import protocol.swg.ObjControllerMessage;
import protocol.swg.SWGMessage;
public class Animation extends ObjControllerObject {
private long objectId;
private String animation;
public Animation(long objectId, String animation) {
this.objectId = objectId;
this.animation = animation;
}
@Override
public void deserialize(IoBuffer data) {
}
@Override
public IoBuffer serialize() {
- IoBuffer result = IoBuffer.allocate(36).order(ByteOrder.LITTLE_ENDIAN);
+ IoBuffer result = IoBuffer.allocate(16 + animation.length()).order(ByteOrder.LITTLE_ENDIAN);
result.putInt(ObjControllerMessage.ANIMATION);
result.putLong(objectId); // person performing animation's id
result.putInt(0); // seems to be just a place holder
result.put(getAsciiString(animation)); // animation name ex: tumble_to_standing
return result.flip();
}
public long getObjectId() {
return objectId;
}
public void setObjectId(long objectId) {
this.objectId = objectId;
}
public String getAnimation() {
return animation;
}
public void setAnimation(String animation) {
this.animation = animation;
}
}
| true | true |
public IoBuffer serialize() {
IoBuffer result = IoBuffer.allocate(36).order(ByteOrder.LITTLE_ENDIAN);
result.putInt(ObjControllerMessage.ANIMATION);
result.putLong(objectId); // person performing animation's id
result.putInt(0); // seems to be just a place holder
result.put(getAsciiString(animation)); // animation name ex: tumble_to_standing
return result.flip();
}
|
public IoBuffer serialize() {
IoBuffer result = IoBuffer.allocate(16 + animation.length()).order(ByteOrder.LITTLE_ENDIAN);
result.putInt(ObjControllerMessage.ANIMATION);
result.putLong(objectId); // person performing animation's id
result.putInt(0); // seems to be just a place holder
result.put(getAsciiString(animation)); // animation name ex: tumble_to_standing
return result.flip();
}
|
diff --git a/Java/antisamy/src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java b/Java/antisamy/src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java
index fece9bd..771da1d 100644
--- a/Java/antisamy/src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java
+++ b/Java/antisamy/src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java
@@ -1,974 +1,974 @@
/*
* Copyright (c) 2007-2010, Arshan Dabirsiaghi, Jason Li
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of OWASP nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.owasp.validator.html.scan;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.apache.batik.css.parser.ParseException;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.HTMLSerializer;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XHTMLSerializer;
import org.cyberneko.html.parsers.DOMFragmentParser;
import org.owasp.validator.css.CssScanner;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
import org.owasp.validator.html.model.Attribute;
import org.owasp.validator.html.model.Tag;
import org.owasp.validator.html.util.ErrorMessageUtil;
import org.owasp.validator.html.util.HTMLEntityEncoder;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
/**
* This is where the magic lives. All the scanning/filtration logic resides
* here, but it should not be called directly. All scanning should be done
* through a <code>AntiSamy.scan()</code> method.
*
* @author Arshan Dabirsiaghi
*
*/
public class AntiSamyDOMScanner extends AbstractAntiSamyScanner {
private Document document = new DocumentImpl();
private DocumentFragment dom = document.createDocumentFragment();
private CleanResults results = null;
/**
* This is where the magic lives.
*
* @param html
* A String whose contents we want to scan.
* @return A <code>CleanResults</code> object with an
* <code>XMLDocumentFragment</code> object and its String
* representation, as well as some scan statistics.
* @throws ScanException
*/
public CleanResults scan(String html, String inputEncoding, String outputEncoding) throws ScanException {
if (html == null) {
throw new ScanException(new NullPointerException("Null input"));
}
int maxInputSize = policy.getMaxInputSize();
if (maxInputSize < html.length()) {
addError(ErrorMessageUtil.ERROR_INPUT_SIZE, new Object[] { new Integer(html.length()), new Integer(maxInputSize) });
throw new ScanException(errorMessages.get(0).toString());
}
isNofollowAnchors = "true".equals(policy.getDirective(Policy.ANCHORS_NOFOLLOW));
isValidateParamAsEmbed = "true".equals(policy.getDirective(Policy.VALIDATE_PARAM_AS_EMBED));
Date start = new Date();
try {
/*
* We have to replace any invalid XML characters to prevent NekoHTML
* from breaking when it gets passed encodings like %21.
*/
html = stripNonValidXMLCharacters(html);
/*
* First thing we do is call the HTML cleaner ("NekoHTML") on it
* with the appropriate options. We choose not to omit tags due to
* the fallibility of our own listing in the ever changing world of
* W3C.
*/
DOMFragmentParser parser = new DOMFragmentParser();
parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
parser.setProperty("http://cyberneko.org/html/properties/default-encoding", inputEncoding);
parser.setFeature("http://cyberneko.org/html/features/scanner/style/strip-cdata-delims", false);
parser.setFeature("http://cyberneko.org/html/features/scanner/cdata-sections", true);
try {
parser.setFeature("http://cyberneko.org/html/features/enforce-strict-attribute-names", true);
} catch (SAXNotRecognizedException se) {
// this indicates that the patched nekohtml is not on the
// classpath
}
try {
parser.parse(new InputSource(new StringReader(html)), dom);
} catch (Exception e) {
throw new ScanException(e);
}
/*
* Call the work horse.
*/
for (int i = 0; i < dom.getChildNodes().getLength(); i++) {
Node tmp = dom.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This check indicates if the node that was just scanned was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Serialize the output and then return the resulting DOM object and
* its string representation.
*/
OutputFormat format = new OutputFormat();
format.setEncoding(outputEncoding);
StringWriter sw = new StringWriter();
/*
* Using the HTMLSerializer is the only way to notify the parser to
* fire events for recognizing HTML-entities. The other ways should,
* but do not work.
*
* We're using HTMLSerializer even though it's deprecated.
*
* See http://marc.info/?l=xerces-j-dev&m=108071323405980&w=2 for
* why we know it's still ok to use.
*/
format.setEncoding(outputEncoding);
format.setOmitXMLDeclaration("true".equals(policy.getDirective(Policy.OMIT_XML_DECLARATION)));
format.setOmitDocumentType("true".equals(policy.getDirective(Policy.OMIT_DOCTYPE_DECLARATION)));
format.setPreserveEmptyAttributes(true);
if ("true".equals(policy.getDirective(Policy.FORMAT_OUTPUT))) {
format.setLineWidth(80);
format.setIndenting(true);
format.setIndent(2);
}
boolean preserveSpace = policy.getDirective(Policy.PRESERVE_SPACE) != null ? "true".equals(policy.getDirective(Policy.PRESERVE_SPACE)) : true;
format.setPreserveSpace(preserveSpace);
if ("true".equals(policy.getDirective(Policy.USE_XHTML))) {
XHTMLSerializer serializer = new XHTMLSerializer(sw, format);
serializer.serialize(dom);
} else {
HTMLSerializer serializer = new HTMLSerializer(sw, format);
serializer.serialize(dom);
}
/*
* Get the String out of the StringWriter and rip out the XML
* declaration if the Policy says we should.
*/
String finalCleanHTML = sw.getBuffer().toString();
/*
* I thought you could just call String.trim(), but it doesn't work.
*/
if (finalCleanHTML.endsWith("\n")) {
if (!html.endsWith("\n")) {
if (finalCleanHTML.endsWith("\r\n")) {
finalCleanHTML = finalCleanHTML.substring(0, finalCleanHTML.length() - 2);
} else if (finalCleanHTML.endsWith("\n")) {
finalCleanHTML = finalCleanHTML.substring(0, finalCleanHTML.length() - 1);
}
}
}
/**
* Return DOM object as well as string HTML.
*/
results = new CleanResults(start, new Date(), finalCleanHTML, dom, errorMessages);
return results;
} catch (SAXException e) {
throw new ScanException(e);
} catch (IOException e) {
throw new ScanException(e);
}
}
/**
* The workhorse of the scanner. Recursively scans document elements
* according to the policy. This should be called implicitly through the
* AntiSamy.scan() method.
*
* @param node
* The node to validate.
*/
private void recursiveValidateTag(Node node) {
if (node instanceof Comment ) {
String preserveComments = policy.getDirective(Policy.PRESERVE_COMMENTS);
if (preserveComments == null || !"true".equals(preserveComments)) {
node.getParentNode().removeChild(node);
} else {
String value = ((Comment) node).getData();
// Strip conditional directives regardless of the
// PRESERVE_COMMENTS setting.
if (value != null) {
((Comment) node).setData(value.replaceAll("<?!?\\[\\s*(?:end)?if[^]]*\\]>?", ""));
}
}
return;
}
if (node instanceof Element && node.getChildNodes().getLength() == 0) {
boolean isEmptyAllowed = false;
for (int i = 0; i < Constants.allowedEmptyTags.length; i++) {
if (Constants.allowedEmptyTags[i].equalsIgnoreCase(node.getNodeName())) {
isEmptyAllowed = true;
i = Constants.allowedEmptyTags.length;
}
}
if (!isEmptyAllowed) {
/*
* Wasn't in the list of allowed elements, so we'll nuke it.
*/
- addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[] { node.getNodeName() });
+ addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getNodeName()) });
node.getParentNode().removeChild(node);
return;
}
}
if ( node instanceof Text && Node.CDATA_SECTION_NODE == node.getNodeType() ) {
- addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[] {node.getTextContent()} );
+ addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[] {HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())} );
//String encoded = HTMLEntityEncoder.htmlEntityEncode(node.getTextContent());
Node text = document.createTextNode(node.getTextContent());
node.getParentNode().insertBefore(text, node);
node.getParentNode().removeChild(node);
return;
}
if ( node instanceof ProcessingInstruction) {
- addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[] {node.getTextContent()} );
+ addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[] {HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())} );
node.getParentNode().removeChild(node);
}
if (!(node instanceof Element)) {
return;
}
Element ele = (Element) node;
Node parentNode = ele.getParentNode();
Node tmp = null;
/*
* See if we have a policy for this tag. If we do, getTagByName() will
* retrieve its object representation.
*/
String tagName = ele.getNodeName();
Tag tag = policy.getTagByName(tagName.toLowerCase());
/*
* If <param> and no policy and isValidateParamAsEmbed and policy in
* place for <embed> and <embed> policy is to validate, use custom
* policy to get the tag through to the validator.
*/
boolean masqueradingParam = false;
if (tag == null && isValidateParamAsEmbed && "param".equals(tagName.toLowerCase())) {
Tag embedPolicy = policy.getTagByName("embed");
if (embedPolicy != null && Policy.ACTION_VALIDATE.equals(embedPolicy.getAction())) {
tag = Constants.BASIC_PARAM_TAG_RULE;
masqueradingParam = true;
}
}
if ((tag == null && "encode".equals(policy.getDirective("onUnknownTag"))) || (tag != null && "encode".equals(tag.getAction()))) {
addError(ErrorMessageUtil.ERROR_TAG_ENCODED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Transform the tag to text, HTML-encode it and promote the
* children. The tag will be kept in the fragment as one or two text
* Nodes located before and after the children; representing how the
* tag used to wrap them.
*/
encodeAndPromoteChildren(ele);
return;
} else if (tag == null || Policy.ACTION_FILTER.equals(tag.getAction())) {
if (tag == null) {
addError(ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
} else {
addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
}
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Loop through and add the children node to the parent before
* removing the current node from the parent.
*
* We must get a fresh copy of the children nodes because validating
* the children may have resulted in us getting less or more
* children.
*/
promoteChildren(ele);
return;
} else if (Policy.ACTION_VALIDATE.equals(tag.getAction())) {
/*
* If doing <param> as <embed>, now is the time to convert it.
*/
String nameValue = null;
if (masqueradingParam) {
nameValue = ele.getAttribute("name");
if (nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute("value");
ele.setAttribute(nameValue, valueValue);
ele.removeAttribute("name");
ele.removeAttribute("value");
tag = policy.getTagByName("embed");
}
}
/*
* Check to see if it's a <style> tag. We have to special case this
* tag so we can hand it off to the custom style sheet validating
* parser.
*/
if ("style".equals(tagName.toLowerCase()) && policy.getTagByName("style") != null) {
/*
* Invoke the css parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
if (node.getFirstChild() != null) {
String toScan = node.getFirstChild().getNodeValue();
CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize());
errorMessages.addAll(cr.getErrorMessages());
/*
* If IE gets an empty style tag, i.e. <style/> it will
* break all CSS on the page. I wish I was kidding. So,
* if after validation no CSS properties are left, we
* would normally be left with an empty style tag and
* break all CSS. To prevent that, we have this check.
*/
final String cleanHTML = cr.getCleanHTML();
if (cleanHTML == null || cleanHTML.equals("")) {
node.getFirstChild().setNodeValue("/* */");
} else {
node.getFirstChild().setNodeValue(cleanHTML);
}
}
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* This shouldn't be reachable anymore, but we'll leave it
* here because I'm hilariously dumb sometimes.
*/
} catch (ParseException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* Batik can throw NumberFormatExceptions (see bug #48).
*/
} catch (NumberFormatException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
}
}
/*
* Go through the attributes in the tainted tag and validate them
* against the values we have for them.
*
* If we don't have a rule for the attribute we remove the
* attribute.
*/
Node attribute = null;
for (int currentAttributeIndex = 0; currentAttributeIndex < ele.getAttributes().getLength(); currentAttributeIndex++) {
attribute = ele.getAttributes().item(currentAttributeIndex);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
Attribute attr = tag.getAttributeByName(name.toLowerCase());
/**
* If we there isn't an attribute by that name in our policy
* check to see if it's a globally defined attribute. Validate
* against that if so.
*/
if (attr == null) {
attr = policy.getGlobalAttributeByName(name);
}
boolean isAttributeValid = false;
/*
* We have to special case the "style" attribute since it's
* validated quite differently.
*/
if ("style".equals(name.toLowerCase()) && attr != null) {
/*
* Invoke the CSS parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
CleanResults cr = styleScanner.scanInlineStyle(value, tagName, policy.getMaxInputSize());
attribute.setNodeValue(cr.getCleanHTML());
ArrayList cssScanErrorMessages = cr.getErrorMessages();
errorMessages.addAll(cssScanErrorMessages);
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
}
} else {
if (attr != null) {
Iterator allowedValues = attr.getAllowedValues().iterator();
while (allowedValues.hasNext() && !isAttributeValid) {
String allowedValue = (String) allowedValues.next();
if (allowedValue != null && allowedValue.toLowerCase().equals(value.toLowerCase())) {
isAttributeValid = true;
}
}
Iterator allowedRegexps = attr.getAllowedRegExp().iterator();
while (allowedRegexps.hasNext() && !isAttributeValid) {
Pattern pattern = (Pattern) allowedRegexps.next();
if (pattern != null && pattern.matcher(value.toLowerCase()).matches()) {
isAttributeValid = true;
}
}
if (!isAttributeValid) {
/*
* Document transgression and perform the
* "onInvalid" action. The default action is to
* strip the attribute and leave the rest intact.
*/
String onInvalidAction = attr.getOnInvalid();
if ("removeTag".equals(onInvalidAction)) {
/*
* Remove the tag and its contents.
*/
parentNode.removeChild(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,
new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
return;
} else if ("filterTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
promoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else if ("encodeTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
encodeAndPromoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_ENCODE, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else {
/*
* onInvalidAction = "removeAttribute"
*/
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
if ("removeTag".equals(onInvalidAction) || "filterTag".equals(onInvalidAction)) {
return; // can't process any more if we
// remove/filter the tag
}
}
}
} else { /*
* the attribute they specified isn't in our policy
* - remove it (whitelisting!)
*/
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} // end if attribute is or is not found in policy file
} // end while loop through attributes
} // loop through each attribute
if (isNofollowAnchors && "a".equals(tagName.toLowerCase())) {
ele.setAttribute("rel", "nofollow");
}
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* If we have been dealing with a <param> that has been converted to
* an <embed>, convert it back
*/
if (masqueradingParam && nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute(nameValue);
ele.setAttribute("name", nameValue);
ele.setAttribute("value", valueValue);
ele.removeAttribute(nameValue);
}
return;
} else if (Policy.ACTION_TRUNCATE.equals(tag.getAction())) {
/*
* Remove all attributes. This is for tags like i, b, u, etc. Purely
* formatting without any need for attributes. It also removes any
* children.
*/
NamedNodeMap nnmap = ele.getAttributes();
while (nnmap.getLength() > 0) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(nnmap.item(0).getNodeName()) });
ele.removeAttribute(nnmap.item(0).getNodeName());
}
NodeList cList = ele.getChildNodes();
int i = 0;
int j = 0;
int length = cList.getLength();
while (i < length) {
Node nodeToRemove = cList.item(j);
if (nodeToRemove.getNodeType() != Node.TEXT_NODE) {
ele.removeChild(nodeToRemove);
} else {
j++;
}
i++;
}
} else {
/*
* If we reached this that means that the tag's action is "remove",
* which means to remove the tag (including its contents).
*/
addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
parentNode.removeChild(ele);
}
}
/**
* This method replaces all entity codes with a normalized version of all
* entity references contained in order to reduce our encoding/parsing
* attack surface.
*
* @param txt
* The string to be normalized.
* @return The normalized version of the string.
*/
/*
* private String replaceEntityCodes(String txt) {
*
* if ( txt == null ) { return null; }
*
* String entityPattern = "&[a-zA-Z0-9]{2,};"; Pattern pattern =
* Pattern.compile(entityPattern); Matcher matcher = pattern.matcher(txt);
* StringBuffer buff = new StringBuffer();
*
* int lastIndex = 0;
*
* while ( matcher.find() ) {
*
* String entity = matcher.group(); int startPos = matcher.start(); int
* endPos = matcher.end();
*
* entity = entity.substring(1); entity =
* entity.substring(0,entity.length()-1);
*
* String code = policy.getEntityReferenceCode(entity);
*
* if ( code != null ) {
*
* buff.append(txt.substring(lastIndex,startPos)); buff.append(code);
* lastIndex = endPos;
*
* }
*
* }
*
* buff.append(txt.substring(lastIndex));
*
* return buff.toString();
*
* }
*/
public static void main(String[] args) throws PolicyException {
}
public AntiSamyDOMScanner(Policy policy) {
super(policy);
}
public AntiSamyDOMScanner() throws PolicyException {
super();
}
/**
* Used to promote the children of a parent to accomplish the "filterTag"
* action.
*
* @param ele
* The Element we want to filter.
*/
private void promoteChildren(Element ele) {
NodeList nodeList = ele.getChildNodes();
Node parent = ele.getParentNode();
while (nodeList.getLength() > 0) {
Node node = ele.removeChild(nodeList.item(0));
parent.insertBefore(node, ele);
}
parent.removeChild(ele);
}
/**
*
* This method was borrowed from Mark McLaren, to whom I owe much beer.
*
* This method ensures that the output has only valid XML unicode characters
* as specified by the XML 1.0 standard. For reference, please see <a
* href="http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char">the
* standard</a>. This method will return an empty String if the input is
* null or empty.
*
* @param in
* The String whose non-valid characters we want to remove.
* @return The in String, stripped of non-valid characters.
*/
private String stripNonValidXMLCharacters(String in) {
if (in == null || ("".equals(in)))
return ""; // vacancy test.
return in.replaceAll("[\\u0000-\\u001F\\uD800-\\uDFFF\\uFFFE-\\uFFFF&&[^\\u0009\\u000A\\u000D]]", "");
}
// private void debug(String s) { System.out.println(s); }
/**
* Transform the element to text, HTML-encode it and promote the children.
* The element will be kept in the fragment as one or two text Nodes located
* before and after the children; representing how the tag used to wrap
* them. If the element didn't have any children then only one text Node is
* created representing an empty element. *
*
* @param ele
* Element to be encoded
*/
private void encodeAndPromoteChildren(Element ele) {
Node parent = ele.getParentNode();
String tagName = ele.getTagName();
Node openingTag = parent.getOwnerDocument().createTextNode(toString(ele));
parent.insertBefore(openingTag, ele);
if (ele.hasChildNodes()) {
Node closingTag = parent.getOwnerDocument().createTextNode("</" + tagName + ">");
parent.insertBefore(closingTag, ele.getNextSibling());
}
promoteChildren(ele);
}
/**
* Returns a text version of the passed element
*
* @param ele
* Element to be converted
* @return String representation of the element
*/
private String toString(Element ele) {
StringBuffer eleAsString = new StringBuffer("<" + ele.getNodeName());
NamedNodeMap attributes = ele.getAttributes();
Node attribute = null;
for (int i = 0; i < attributes.getLength(); i++) {
attribute = attributes.item(i);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
eleAsString.append(" ");
eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(name));
eleAsString.append("=\"");
eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(value));
eleAsString.append("\"");
}
if (ele.hasChildNodes()) {
eleAsString.append(">");
} else {
eleAsString.append("/>");
}
return eleAsString.toString();
}
public CleanResults getResults() {
return results;
}
}
| false | true |
private void recursiveValidateTag(Node node) {
if (node instanceof Comment ) {
String preserveComments = policy.getDirective(Policy.PRESERVE_COMMENTS);
if (preserveComments == null || !"true".equals(preserveComments)) {
node.getParentNode().removeChild(node);
} else {
String value = ((Comment) node).getData();
// Strip conditional directives regardless of the
// PRESERVE_COMMENTS setting.
if (value != null) {
((Comment) node).setData(value.replaceAll("<?!?\\[\\s*(?:end)?if[^]]*\\]>?", ""));
}
}
return;
}
if (node instanceof Element && node.getChildNodes().getLength() == 0) {
boolean isEmptyAllowed = false;
for (int i = 0; i < Constants.allowedEmptyTags.length; i++) {
if (Constants.allowedEmptyTags[i].equalsIgnoreCase(node.getNodeName())) {
isEmptyAllowed = true;
i = Constants.allowedEmptyTags.length;
}
}
if (!isEmptyAllowed) {
/*
* Wasn't in the list of allowed elements, so we'll nuke it.
*/
addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[] { node.getNodeName() });
node.getParentNode().removeChild(node);
return;
}
}
if ( node instanceof Text && Node.CDATA_SECTION_NODE == node.getNodeType() ) {
addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[] {node.getTextContent()} );
//String encoded = HTMLEntityEncoder.htmlEntityEncode(node.getTextContent());
Node text = document.createTextNode(node.getTextContent());
node.getParentNode().insertBefore(text, node);
node.getParentNode().removeChild(node);
return;
}
if ( node instanceof ProcessingInstruction) {
addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[] {node.getTextContent()} );
node.getParentNode().removeChild(node);
}
if (!(node instanceof Element)) {
return;
}
Element ele = (Element) node;
Node parentNode = ele.getParentNode();
Node tmp = null;
/*
* See if we have a policy for this tag. If we do, getTagByName() will
* retrieve its object representation.
*/
String tagName = ele.getNodeName();
Tag tag = policy.getTagByName(tagName.toLowerCase());
/*
* If <param> and no policy and isValidateParamAsEmbed and policy in
* place for <embed> and <embed> policy is to validate, use custom
* policy to get the tag through to the validator.
*/
boolean masqueradingParam = false;
if (tag == null && isValidateParamAsEmbed && "param".equals(tagName.toLowerCase())) {
Tag embedPolicy = policy.getTagByName("embed");
if (embedPolicy != null && Policy.ACTION_VALIDATE.equals(embedPolicy.getAction())) {
tag = Constants.BASIC_PARAM_TAG_RULE;
masqueradingParam = true;
}
}
if ((tag == null && "encode".equals(policy.getDirective("onUnknownTag"))) || (tag != null && "encode".equals(tag.getAction()))) {
addError(ErrorMessageUtil.ERROR_TAG_ENCODED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Transform the tag to text, HTML-encode it and promote the
* children. The tag will be kept in the fragment as one or two text
* Nodes located before and after the children; representing how the
* tag used to wrap them.
*/
encodeAndPromoteChildren(ele);
return;
} else if (tag == null || Policy.ACTION_FILTER.equals(tag.getAction())) {
if (tag == null) {
addError(ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
} else {
addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
}
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Loop through and add the children node to the parent before
* removing the current node from the parent.
*
* We must get a fresh copy of the children nodes because validating
* the children may have resulted in us getting less or more
* children.
*/
promoteChildren(ele);
return;
} else if (Policy.ACTION_VALIDATE.equals(tag.getAction())) {
/*
* If doing <param> as <embed>, now is the time to convert it.
*/
String nameValue = null;
if (masqueradingParam) {
nameValue = ele.getAttribute("name");
if (nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute("value");
ele.setAttribute(nameValue, valueValue);
ele.removeAttribute("name");
ele.removeAttribute("value");
tag = policy.getTagByName("embed");
}
}
/*
* Check to see if it's a <style> tag. We have to special case this
* tag so we can hand it off to the custom style sheet validating
* parser.
*/
if ("style".equals(tagName.toLowerCase()) && policy.getTagByName("style") != null) {
/*
* Invoke the css parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
if (node.getFirstChild() != null) {
String toScan = node.getFirstChild().getNodeValue();
CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize());
errorMessages.addAll(cr.getErrorMessages());
/*
* If IE gets an empty style tag, i.e. <style/> it will
* break all CSS on the page. I wish I was kidding. So,
* if after validation no CSS properties are left, we
* would normally be left with an empty style tag and
* break all CSS. To prevent that, we have this check.
*/
final String cleanHTML = cr.getCleanHTML();
if (cleanHTML == null || cleanHTML.equals("")) {
node.getFirstChild().setNodeValue("/* */");
} else {
node.getFirstChild().setNodeValue(cleanHTML);
}
}
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* This shouldn't be reachable anymore, but we'll leave it
* here because I'm hilariously dumb sometimes.
*/
} catch (ParseException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* Batik can throw NumberFormatExceptions (see bug #48).
*/
} catch (NumberFormatException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
}
}
/*
* Go through the attributes in the tainted tag and validate them
* against the values we have for them.
*
* If we don't have a rule for the attribute we remove the
* attribute.
*/
Node attribute = null;
for (int currentAttributeIndex = 0; currentAttributeIndex < ele.getAttributes().getLength(); currentAttributeIndex++) {
attribute = ele.getAttributes().item(currentAttributeIndex);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
Attribute attr = tag.getAttributeByName(name.toLowerCase());
/**
* If we there isn't an attribute by that name in our policy
* check to see if it's a globally defined attribute. Validate
* against that if so.
*/
if (attr == null) {
attr = policy.getGlobalAttributeByName(name);
}
boolean isAttributeValid = false;
/*
* We have to special case the "style" attribute since it's
* validated quite differently.
*/
if ("style".equals(name.toLowerCase()) && attr != null) {
/*
* Invoke the CSS parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
CleanResults cr = styleScanner.scanInlineStyle(value, tagName, policy.getMaxInputSize());
attribute.setNodeValue(cr.getCleanHTML());
ArrayList cssScanErrorMessages = cr.getErrorMessages();
errorMessages.addAll(cssScanErrorMessages);
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
}
} else {
if (attr != null) {
Iterator allowedValues = attr.getAllowedValues().iterator();
while (allowedValues.hasNext() && !isAttributeValid) {
String allowedValue = (String) allowedValues.next();
if (allowedValue != null && allowedValue.toLowerCase().equals(value.toLowerCase())) {
isAttributeValid = true;
}
}
Iterator allowedRegexps = attr.getAllowedRegExp().iterator();
while (allowedRegexps.hasNext() && !isAttributeValid) {
Pattern pattern = (Pattern) allowedRegexps.next();
if (pattern != null && pattern.matcher(value.toLowerCase()).matches()) {
isAttributeValid = true;
}
}
if (!isAttributeValid) {
/*
* Document transgression and perform the
* "onInvalid" action. The default action is to
* strip the attribute and leave the rest intact.
*/
String onInvalidAction = attr.getOnInvalid();
if ("removeTag".equals(onInvalidAction)) {
/*
* Remove the tag and its contents.
*/
parentNode.removeChild(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,
new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
return;
} else if ("filterTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
promoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else if ("encodeTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
encodeAndPromoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_ENCODE, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else {
/*
* onInvalidAction = "removeAttribute"
*/
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
if ("removeTag".equals(onInvalidAction) || "filterTag".equals(onInvalidAction)) {
return; // can't process any more if we
// remove/filter the tag
}
}
}
} else { /*
* the attribute they specified isn't in our policy
* - remove it (whitelisting!)
*/
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} // end if attribute is or is not found in policy file
} // end while loop through attributes
} // loop through each attribute
if (isNofollowAnchors && "a".equals(tagName.toLowerCase())) {
ele.setAttribute("rel", "nofollow");
}
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* If we have been dealing with a <param> that has been converted to
* an <embed>, convert it back
*/
if (masqueradingParam && nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute(nameValue);
ele.setAttribute("name", nameValue);
ele.setAttribute("value", valueValue);
ele.removeAttribute(nameValue);
}
return;
} else if (Policy.ACTION_TRUNCATE.equals(tag.getAction())) {
/*
* Remove all attributes. This is for tags like i, b, u, etc. Purely
* formatting without any need for attributes. It also removes any
* children.
*/
NamedNodeMap nnmap = ele.getAttributes();
while (nnmap.getLength() > 0) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(nnmap.item(0).getNodeName()) });
ele.removeAttribute(nnmap.item(0).getNodeName());
}
NodeList cList = ele.getChildNodes();
int i = 0;
int j = 0;
int length = cList.getLength();
while (i < length) {
Node nodeToRemove = cList.item(j);
if (nodeToRemove.getNodeType() != Node.TEXT_NODE) {
ele.removeChild(nodeToRemove);
} else {
j++;
}
i++;
}
} else {
/*
* If we reached this that means that the tag's action is "remove",
* which means to remove the tag (including its contents).
*/
addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
parentNode.removeChild(ele);
}
}
|
private void recursiveValidateTag(Node node) {
if (node instanceof Comment ) {
String preserveComments = policy.getDirective(Policy.PRESERVE_COMMENTS);
if (preserveComments == null || !"true".equals(preserveComments)) {
node.getParentNode().removeChild(node);
} else {
String value = ((Comment) node).getData();
// Strip conditional directives regardless of the
// PRESERVE_COMMENTS setting.
if (value != null) {
((Comment) node).setData(value.replaceAll("<?!?\\[\\s*(?:end)?if[^]]*\\]>?", ""));
}
}
return;
}
if (node instanceof Element && node.getChildNodes().getLength() == 0) {
boolean isEmptyAllowed = false;
for (int i = 0; i < Constants.allowedEmptyTags.length; i++) {
if (Constants.allowedEmptyTags[i].equalsIgnoreCase(node.getNodeName())) {
isEmptyAllowed = true;
i = Constants.allowedEmptyTags.length;
}
}
if (!isEmptyAllowed) {
/*
* Wasn't in the list of allowed elements, so we'll nuke it.
*/
addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getNodeName()) });
node.getParentNode().removeChild(node);
return;
}
}
if ( node instanceof Text && Node.CDATA_SECTION_NODE == node.getNodeType() ) {
addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[] {HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())} );
//String encoded = HTMLEntityEncoder.htmlEntityEncode(node.getTextContent());
Node text = document.createTextNode(node.getTextContent());
node.getParentNode().insertBefore(text, node);
node.getParentNode().removeChild(node);
return;
}
if ( node instanceof ProcessingInstruction) {
addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[] {HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())} );
node.getParentNode().removeChild(node);
}
if (!(node instanceof Element)) {
return;
}
Element ele = (Element) node;
Node parentNode = ele.getParentNode();
Node tmp = null;
/*
* See if we have a policy for this tag. If we do, getTagByName() will
* retrieve its object representation.
*/
String tagName = ele.getNodeName();
Tag tag = policy.getTagByName(tagName.toLowerCase());
/*
* If <param> and no policy and isValidateParamAsEmbed and policy in
* place for <embed> and <embed> policy is to validate, use custom
* policy to get the tag through to the validator.
*/
boolean masqueradingParam = false;
if (tag == null && isValidateParamAsEmbed && "param".equals(tagName.toLowerCase())) {
Tag embedPolicy = policy.getTagByName("embed");
if (embedPolicy != null && Policy.ACTION_VALIDATE.equals(embedPolicy.getAction())) {
tag = Constants.BASIC_PARAM_TAG_RULE;
masqueradingParam = true;
}
}
if ((tag == null && "encode".equals(policy.getDirective("onUnknownTag"))) || (tag != null && "encode".equals(tag.getAction()))) {
addError(ErrorMessageUtil.ERROR_TAG_ENCODED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Transform the tag to text, HTML-encode it and promote the
* children. The tag will be kept in the fragment as one or two text
* Nodes located before and after the children; representing how the
* tag used to wrap them.
*/
encodeAndPromoteChildren(ele);
return;
} else if (tag == null || Policy.ACTION_FILTER.equals(tag.getAction())) {
if (tag == null) {
addError(ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
} else {
addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
}
/*
* We have to filter out the tags only. This means the content
* should remain. First step is to validate before promoting its
* children.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* Loop through and add the children node to the parent before
* removing the current node from the parent.
*
* We must get a fresh copy of the children nodes because validating
* the children may have resulted in us getting less or more
* children.
*/
promoteChildren(ele);
return;
} else if (Policy.ACTION_VALIDATE.equals(tag.getAction())) {
/*
* If doing <param> as <embed>, now is the time to convert it.
*/
String nameValue = null;
if (masqueradingParam) {
nameValue = ele.getAttribute("name");
if (nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute("value");
ele.setAttribute(nameValue, valueValue);
ele.removeAttribute("name");
ele.removeAttribute("value");
tag = policy.getTagByName("embed");
}
}
/*
* Check to see if it's a <style> tag. We have to special case this
* tag so we can hand it off to the custom style sheet validating
* parser.
*/
if ("style".equals(tagName.toLowerCase()) && policy.getTagByName("style") != null) {
/*
* Invoke the css parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
if (node.getFirstChild() != null) {
String toScan = node.getFirstChild().getNodeValue();
CleanResults cr = styleScanner.scanStyleSheet(toScan, policy.getMaxInputSize());
errorMessages.addAll(cr.getErrorMessages());
/*
* If IE gets an empty style tag, i.e. <style/> it will
* break all CSS on the page. I wish I was kidding. So,
* if after validation no CSS properties are left, we
* would normally be left with an empty style tag and
* break all CSS. To prevent that, we have this check.
*/
final String cleanHTML = cr.getCleanHTML();
if (cleanHTML == null || cleanHTML.equals("")) {
node.getFirstChild().setNodeValue("/* */");
} else {
node.getFirstChild().setNodeValue(cleanHTML);
}
}
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* This shouldn't be reachable anymore, but we'll leave it
* here because I'm hilariously dumb sometimes.
*/
} catch (ParseException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
/*
* Batik can throw NumberFormatExceptions (see bug #48).
*/
} catch (NumberFormatException e) {
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
parentNode.removeChild(node);
return;
}
}
/*
* Go through the attributes in the tainted tag and validate them
* against the values we have for them.
*
* If we don't have a rule for the attribute we remove the
* attribute.
*/
Node attribute = null;
for (int currentAttributeIndex = 0; currentAttributeIndex < ele.getAttributes().getLength(); currentAttributeIndex++) {
attribute = ele.getAttributes().item(currentAttributeIndex);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
Attribute attr = tag.getAttributeByName(name.toLowerCase());
/**
* If we there isn't an attribute by that name in our policy
* check to see if it's a globally defined attribute. Validate
* against that if so.
*/
if (attr == null) {
attr = policy.getGlobalAttributeByName(name);
}
boolean isAttributeValid = false;
/*
* We have to special case the "style" attribute since it's
* validated quite differently.
*/
if ("style".equals(name.toLowerCase()) && attr != null) {
/*
* Invoke the CSS parser on this element.
*/
CssScanner styleScanner = new CssScanner(policy, messages);
try {
CleanResults cr = styleScanner.scanInlineStyle(value, tagName, policy.getMaxInputSize());
attribute.setNodeValue(cr.getCleanHTML());
ArrayList cssScanErrorMessages = cr.getErrorMessages();
errorMessages.addAll(cssScanErrorMessages);
} catch (DOMException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
}
} else {
if (attr != null) {
Iterator allowedValues = attr.getAllowedValues().iterator();
while (allowedValues.hasNext() && !isAttributeValid) {
String allowedValue = (String) allowedValues.next();
if (allowedValue != null && allowedValue.toLowerCase().equals(value.toLowerCase())) {
isAttributeValid = true;
}
}
Iterator allowedRegexps = attr.getAllowedRegExp().iterator();
while (allowedRegexps.hasNext() && !isAttributeValid) {
Pattern pattern = (Pattern) allowedRegexps.next();
if (pattern != null && pattern.matcher(value.toLowerCase()).matches()) {
isAttributeValid = true;
}
}
if (!isAttributeValid) {
/*
* Document transgression and perform the
* "onInvalid" action. The default action is to
* strip the attribute and leave the rest intact.
*/
String onInvalidAction = attr.getOnInvalid();
if ("removeTag".equals(onInvalidAction)) {
/*
* Remove the tag and its contents.
*/
parentNode.removeChild(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,
new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
return;
} else if ("filterTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
promoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else if ("encodeTag".equals(onInvalidAction)) {
/*
* Remove the attribute and keep the rest of the
* tag.
*/
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was
* removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
encodeAndPromoteChildren(ele);
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_ENCODE, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
} else {
/*
* onInvalidAction = "removeAttribute"
*/
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
if ("removeTag".equals(onInvalidAction) || "filterTag".equals(onInvalidAction)) {
return; // can't process any more if we
// remove/filter the tag
}
}
}
} else { /*
* the attribute they specified isn't in our policy
* - remove it (whitelisting!)
*/
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
ele.removeAttribute(attribute.getNodeName());
currentAttributeIndex--;
} // end if attribute is or is not found in policy file
} // end while loop through attributes
} // loop through each attribute
if (isNofollowAnchors && "a".equals(tagName.toLowerCase())) {
ele.setAttribute("rel", "nofollow");
}
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
tmp = node.getChildNodes().item(i);
recursiveValidateTag(tmp);
/*
* This indicates the node was removed/failed validation.
*/
if (tmp.getParentNode() == null) {
i--;
}
}
/*
* If we have been dealing with a <param> that has been converted to
* an <embed>, convert it back
*/
if (masqueradingParam && nameValue != null && !"".equals(nameValue)) {
String valueValue = ele.getAttribute(nameValue);
ele.setAttribute("name", nameValue);
ele.setAttribute("value", valueValue);
ele.removeAttribute(nameValue);
}
return;
} else if (Policy.ACTION_TRUNCATE.equals(tag.getAction())) {
/*
* Remove all attributes. This is for tags like i, b, u, etc. Purely
* formatting without any need for attributes. It also removes any
* children.
*/
NamedNodeMap nnmap = ele.getAttributes();
while (nnmap.getLength() > 0) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(nnmap.item(0).getNodeName()) });
ele.removeAttribute(nnmap.item(0).getNodeName());
}
NodeList cList = ele.getChildNodes();
int i = 0;
int j = 0;
int length = cList.getLength();
while (i < length) {
Node nodeToRemove = cList.item(j);
if (nodeToRemove.getNodeType() != Node.TEXT_NODE) {
ele.removeChild(nodeToRemove);
} else {
j++;
}
i++;
}
} else {
/*
* If we reached this that means that the tag's action is "remove",
* which means to remove the tag (including its contents).
*/
addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(tagName) });
parentNode.removeChild(ele);
}
}
|
diff --git a/tests/org.eclipse.rap.rwt.test/src/org/eclipse/rwt/internal/lifecycle/RenderDispose_Test.java b/tests/org.eclipse.rap.rwt.test/src/org/eclipse/rwt/internal/lifecycle/RenderDispose_Test.java
index 4f0ab6eab..03646c0cf 100644
--- a/tests/org.eclipse.rap.rwt.test/src/org/eclipse/rwt/internal/lifecycle/RenderDispose_Test.java
+++ b/tests/org.eclipse.rap.rwt.test/src/org/eclipse/rwt/internal/lifecycle/RenderDispose_Test.java
@@ -1,127 +1,132 @@
/*******************************************************************************
* Copyright (c) 2002-2006 Innoopract Informationssysteme GmbH.
* 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:
* Innoopract Informationssysteme GmbH - initial API and implementation
******************************************************************************/
package org.eclipse.rwt.internal.lifecycle;
import java.io.IOException;
import junit.framework.TestCase;
import org.eclipse.rwt.Fixture;
import org.eclipse.rwt.internal.browser.Ie6;
import org.eclipse.rwt.internal.service.RequestParams;
import org.eclipse.rwt.lifecycle.*;
import org.eclipse.swt.RWTFixture;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
public class RenderDispose_Test extends TestCase {
private final PreserveWidgetsPhaseListener preserveWidgetsPhaseListener
= new PreserveWidgetsPhaseListener();
// TODO [rst] reactivate when PUSH button takes part in object pooling again
/*
public void testDispose() throws IOException {
RWTLifeCycle lifeCycle = new RWTLifeCycle();
// set up the test widget hierarchy
Display display = new Display();
Composite shell = new Shell( display , SWT.NONE );
final Button button = new Button( shell, SWT.PUSH );
String displayId = DisplayUtil.getAdapter( display ).getId();
// first rendering: html document that contains the javaScript 'application'
RWTFixture.fakeNewRequest();
lifeCycle.execute();
// second rendering: initial markup that constructs the above created
// widget hierarchy (display, shell and button)
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.execute();
// dispose of the button
button.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
button.dispose();
}
} );
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
String buttonId = WidgetUtil.getId( button );
Fixture.fakeRequestParam( JSConst.EVENT_WIDGET_SELECTED, buttonId );
lifeCycle.execute();
String expectedStart
= "org.eclipse.swt.EventUtil.suspendEventHandling();"
+ "var wm = org.eclipse.swt.WidgetManager.getInstance();"
+ "wm.registerResetHandler( ";
String functionHandler = ", function( w ) {";
String expectedEnd
= "} );wm.dispose( \"w3\" );"
+ "qx.ui.core.Widget.flushGlobalQueues();"
+ "org.eclipse.swt.EventUtil.resumeEventHandling();";
String allMarkup = Fixture.getAllMarkup();
assertTrue( allMarkup.startsWith( expectedStart ) );
assertTrue( allMarkup.indexOf( functionHandler ) != 0 );
assertTrue( allMarkup.endsWith( expectedEnd ) );
}
*/
public void testDisposeNotYetInitialized() throws IOException {
// set up the test widget hierarchy
Display display = new Display();
final Composite shell = new Shell( display , SWT.NONE );
String displayId = DisplayUtil.getAdapter( display ).getId();
// first rendering: html document that contains the javaScript 'application'
RWTLifeCycle lifeCycle = new RWTLifeCycle();
lifeCycle.execute();
// second rendering: initial markup that constructs the above created
// widget hierarchy (display, shell and button)
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.execute();
// create and dispose of the button
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
Button button = new Button( shell, SWT.PUSH );
button.dispose();
}
public void afterPhase( final PhaseEvent event ) {
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
lifeCycle.execute();
- String expected
+ String expectedStart
= "org.eclipse.swt.EventUtil.suspendEventHandling();"
- + "qx.ui.core.Widget.flushGlobalQueues();"
+ + "var req = org.eclipse.swt.Request.getInstance();"
+ + "req.setRequestCounter(";
+ String expectedEnd
+ = ");qx.ui.core.Widget.flushGlobalQueues();"
+ "org.eclipse.swt.EventUtil.resumeEventHandling();";
- assertEquals( expected, Fixture.getAllMarkup() );
+ String allMarkup = Fixture.getAllMarkup();
+ assertTrue( allMarkup.startsWith( expectedStart ) );
+ assertTrue( allMarkup.endsWith( expectedEnd ) );
}
protected void setUp() throws Exception {
RWTFixture.setUp();
Fixture.fakeResponseWriter();
Fixture.fakeBrowser( new Ie6( true, true ) );
PhaseListenerRegistry.add( preserveWidgetsPhaseListener );
}
protected void tearDown() throws Exception {
PhaseListenerRegistry.clear();
RWTFixture.tearDown();
}
}
| false | true |
public void testDisposeNotYetInitialized() throws IOException {
// set up the test widget hierarchy
Display display = new Display();
final Composite shell = new Shell( display , SWT.NONE );
String displayId = DisplayUtil.getAdapter( display ).getId();
// first rendering: html document that contains the javaScript 'application'
RWTLifeCycle lifeCycle = new RWTLifeCycle();
lifeCycle.execute();
// second rendering: initial markup that constructs the above created
// widget hierarchy (display, shell and button)
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.execute();
// create and dispose of the button
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
Button button = new Button( shell, SWT.PUSH );
button.dispose();
}
public void afterPhase( final PhaseEvent event ) {
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
lifeCycle.execute();
String expected
= "org.eclipse.swt.EventUtil.suspendEventHandling();"
+ "qx.ui.core.Widget.flushGlobalQueues();"
+ "org.eclipse.swt.EventUtil.resumeEventHandling();";
assertEquals( expected, Fixture.getAllMarkup() );
}
|
public void testDisposeNotYetInitialized() throws IOException {
// set up the test widget hierarchy
Display display = new Display();
final Composite shell = new Shell( display , SWT.NONE );
String displayId = DisplayUtil.getAdapter( display ).getId();
// first rendering: html document that contains the javaScript 'application'
RWTLifeCycle lifeCycle = new RWTLifeCycle();
lifeCycle.execute();
// second rendering: initial markup that constructs the above created
// widget hierarchy (display, shell and button)
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.execute();
// create and dispose of the button
RWTFixture.fakeNewRequest();
Fixture.fakeRequestParam( RequestParams.UIROOT, displayId );
lifeCycle.addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
Button button = new Button( shell, SWT.PUSH );
button.dispose();
}
public void afterPhase( final PhaseEvent event ) {
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
lifeCycle.execute();
String expectedStart
= "org.eclipse.swt.EventUtil.suspendEventHandling();"
+ "var req = org.eclipse.swt.Request.getInstance();"
+ "req.setRequestCounter(";
String expectedEnd
= ");qx.ui.core.Widget.flushGlobalQueues();"
+ "org.eclipse.swt.EventUtil.resumeEventHandling();";
String allMarkup = Fixture.getAllMarkup();
assertTrue( allMarkup.startsWith( expectedStart ) );
assertTrue( allMarkup.endsWith( expectedEnd ) );
}
|
diff --git a/src/fr/eurecom/messaging/Receiver.java b/src/fr/eurecom/messaging/Receiver.java
index 2709219..b38350b 100644
--- a/src/fr/eurecom/messaging/Receiver.java
+++ b/src/fr/eurecom/messaging/Receiver.java
@@ -1,78 +1,78 @@
package fr.eurecom.messaging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class Receiver extends AsyncTask<String, Void, JSONObject> {
private static final String TAG = "Receiver";
private boolean listening;
private Client client;
private ServerSocket socket;
public Receiver(Client client) {
Log.d(Receiver.TAG, "Constructor");
listening = true;
this.client = client;
}
@Override
protected JSONObject doInBackground(String... params) {
try {
- ServerSocket socket = new ServerSocket(Config.PORT);
+ socket = new ServerSocket(Config.PORT);
Log.d(Receiver.TAG, "Client: Socket opened!!");
while (listening) {
// Wait for incoming message
Socket sender = socket.accept();
// Read incoming message
BufferedReader in = new BufferedReader(new InputStreamReader(sender.getInputStream()));
// Transform message to JSON Object
JSONObject json = new JSONObject(in.readLine());
// Send message to client
Log.d("Tekst fra host", "Inputstreamen er: " + json.toString());
receiveMessage(json, sender.getInetAddress());
sender.close();
}
} catch (IOException e) {
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void receiveMessage(JSONObject json, InetAddress sender){
try {
Action action = Action.values()[json.getInt("action")];
String subject = json.getString("subject");
Message message = new Message(action, subject);
message.setSender(sender);
client.handleMessage(message);
} catch (JSONException e){
Log.e("ClientInterpreter:receiveMessage", e.getMessage());
}
}
public void stopListening(){
this.listening = false;
try {
this.socket.close();
} catch (IOException e) {
Log.e("Receiver:stopListening", e.getMessage());
}
}
}
| true | true |
protected JSONObject doInBackground(String... params) {
try {
ServerSocket socket = new ServerSocket(Config.PORT);
Log.d(Receiver.TAG, "Client: Socket opened!!");
while (listening) {
// Wait for incoming message
Socket sender = socket.accept();
// Read incoming message
BufferedReader in = new BufferedReader(new InputStreamReader(sender.getInputStream()));
// Transform message to JSON Object
JSONObject json = new JSONObject(in.readLine());
// Send message to client
Log.d("Tekst fra host", "Inputstreamen er: " + json.toString());
receiveMessage(json, sender.getInetAddress());
sender.close();
}
} catch (IOException e) {
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
protected JSONObject doInBackground(String... params) {
try {
socket = new ServerSocket(Config.PORT);
Log.d(Receiver.TAG, "Client: Socket opened!!");
while (listening) {
// Wait for incoming message
Socket sender = socket.accept();
// Read incoming message
BufferedReader in = new BufferedReader(new InputStreamReader(sender.getInputStream()));
// Transform message to JSON Object
JSONObject json = new JSONObject(in.readLine());
// Send message to client
Log.d("Tekst fra host", "Inputstreamen er: " + json.toString());
receiveMessage(json, sender.getInetAddress());
sender.close();
}
} catch (IOException e) {
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
diff --git a/src/main/java/pt/ua/tm/trigner/model/ModelFeaturePipeline.java b/src/main/java/pt/ua/tm/trigner/model/ModelFeaturePipeline.java
index 5be360f..6b5e9d3 100644
--- a/src/main/java/pt/ua/tm/trigner/model/ModelFeaturePipeline.java
+++ b/src/main/java/pt/ua/tm/trigner/model/ModelFeaturePipeline.java
@@ -1,137 +1,137 @@
package pt.ua.tm.trigner.model;
import cc.mallet.pipe.Pipe;
import cc.mallet.pipe.PrintTokenSequenceFeatures;
import cc.mallet.pipe.SerialPipes;
import cc.mallet.pipe.TokenSequence2FeatureVectorSequence;
import cc.mallet.pipe.tsf.*;
import pt.ua.tm.gimli.features.mallet.*;
import pt.ua.tm.trigner.model.configuration.ModelConfiguration;
import pt.ua.tm.trigner.model.features.NGramsUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* Created with IntelliJ IDEA.
* User: david
* Date: 19/03/13
* Time: 13:59
* To change this template use File | Settings | File Templates.
*/
public class ModelFeaturePipeline {
private static final String CAPS = "[A-Z]";
private static final String LOW = "[a-z]";
public static Pipe get(final ModelConfiguration mc, final String dictionaryPath) {
ArrayList<Pipe> pipe = new ArrayList<>();
// Input parsing
pipe.add(new pt.ua.tm.trigner.model.pipe.Input2TokenSequence(mc));
// Capitalization
if (mc.isProperty("capitalization")) {
pipe.add(new RegexMatches("InitCap", Pattern.compile(CAPS + ".*")));
pipe.add(new RegexMatches("EndCap", Pattern.compile(".*" + CAPS)));
pipe.add(new RegexMatches("AllCaps", Pattern.compile(CAPS + "+")));
pipe.add(new RegexMatches("Lowercase", Pattern.compile(LOW + "+")));
pipe.add(new MixCase());
pipe.add(new RegexMatches("DigitsLettersAndSymbol", Pattern.compile("[0-9a-zA-z]+[-%/\\[\\]:;()'\"*=+][0-9a-zA-z]+")));
}
// Counting
if (mc.isProperty("counting")) {
pipe.add(new NumberOfCap());
pipe.add(new NumberOfDigit());
pipe.add(new WordLength());
}
// Symbols
if (mc.isProperty("symbols")) {
pipe.add(new RegexMatches("Hyphen", Pattern.compile(".*[-].*")));
pipe.add(new RegexMatches("BackSlash", Pattern.compile(".*[/].*")));
pipe.add(new RegexMatches("OpenSquare", Pattern.compile(".*[\\[].*")));
pipe.add(new RegexMatches("CloseSquare", Pattern.compile(".*[\\]].*")));
pipe.add(new RegexMatches("Colon", Pattern.compile(".*[:].*")));
pipe.add(new RegexMatches("SemiColon", Pattern.compile(".*[;].*")));
pipe.add(new RegexMatches("Percent", Pattern.compile(".*[%].*")));
pipe.add(new RegexMatches("OpenParen", Pattern.compile(".*[(].*")));
pipe.add(new RegexMatches("CloseParen", Pattern.compile(".*[)].*")));
pipe.add(new RegexMatches("Comma", Pattern.compile(".*[,].*")));
pipe.add(new RegexMatches("Dot", Pattern.compile(".*[\\.].*")));
pipe.add(new RegexMatches("Apostrophe", Pattern.compile(".*['].*")));
pipe.add(new RegexMatches("QuotationMark", Pattern.compile(".*[\"].*")));
pipe.add(new RegexMatches("Star", Pattern.compile(".*[*].*")));
pipe.add(new RegexMatches("Equal", Pattern.compile(".*[=].*")));
pipe.add(new RegexMatches("Plus", Pattern.compile(".*[+].*")));
}
// Char n-gram
if (mc.isProperty("char_ngrams")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("char_ngrams_sizes"));
pipe.add(new TokenTextCharNGrams("CHARNGRAM=", ngrams));
}
// Suffixes
if (mc.isProperty("suffix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("suffix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharSuffix(ngram + "SUFFIX=", ngram));
}
}
// Prefixes
if (mc.isProperty("prefix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("prefix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharPrefix(ngram + "PREFIX=", ngram));
}
}
// Word shape
if (mc.isProperty("word_shape")) {
pipe.add(new WordShape());
}
if (mc.isProperty("triggers")) {
File file = new File(dictionaryPath);
try {
pipe.add(new TrieLexiconMembership("TRIGGER", file, true));
} catch (FileNotFoundException ex) {
throw new RuntimeException("There was a problem reading the dictionary for triggers matching: " + file.getName(), ex);
}
}
ModelConfiguration.ContextType context = ModelConfiguration.ContextType.valueOf(mc.getProperty("context"));
switch (context) {
case NONE:
break;
case WINDOW:
// pipe.add(new FeaturesInWindow("WINDOW=", -3, 3));
- pipe.add(new FeaturesInWindow("WINDOW=", -1, 0, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
- pipe.add(new FeaturesInWindow("WINDOW=", -2, -1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
- pipe.add(new FeaturesInWindow("WINDOW=", 0, 1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
- pipe.add(new FeaturesInWindow("WINDOW=", -1, 1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
- pipe.add(new FeaturesInWindow("WINDOW=", -3, -1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
+ pipe.add(new FeaturesInWindow("WINDOW=", -1, 0, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
+ pipe.add(new FeaturesInWindow("WINDOW=", -2, -1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
+ pipe.add(new FeaturesInWindow("WINDOW=", 0, 1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
+ pipe.add(new FeaturesInWindow("WINDOW=", -1, 1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
+ pipe.add(new FeaturesInWindow("WINDOW=", -3, -1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
break;
case CONJUNCTIONS:
pipe.add(new OffsetConjunctions(true, Pattern.compile("WORD=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("LEMMA=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("POS=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
break;
}
// Print
// pipe.add(new PrintTokenSequenceFeatures());
pipe.add(new TokenSequence2FeatureVectorSequence(true, true));
return new SerialPipes(pipe);
}
}
| true | true |
public static Pipe get(final ModelConfiguration mc, final String dictionaryPath) {
ArrayList<Pipe> pipe = new ArrayList<>();
// Input parsing
pipe.add(new pt.ua.tm.trigner.model.pipe.Input2TokenSequence(mc));
// Capitalization
if (mc.isProperty("capitalization")) {
pipe.add(new RegexMatches("InitCap", Pattern.compile(CAPS + ".*")));
pipe.add(new RegexMatches("EndCap", Pattern.compile(".*" + CAPS)));
pipe.add(new RegexMatches("AllCaps", Pattern.compile(CAPS + "+")));
pipe.add(new RegexMatches("Lowercase", Pattern.compile(LOW + "+")));
pipe.add(new MixCase());
pipe.add(new RegexMatches("DigitsLettersAndSymbol", Pattern.compile("[0-9a-zA-z]+[-%/\\[\\]:;()'\"*=+][0-9a-zA-z]+")));
}
// Counting
if (mc.isProperty("counting")) {
pipe.add(new NumberOfCap());
pipe.add(new NumberOfDigit());
pipe.add(new WordLength());
}
// Symbols
if (mc.isProperty("symbols")) {
pipe.add(new RegexMatches("Hyphen", Pattern.compile(".*[-].*")));
pipe.add(new RegexMatches("BackSlash", Pattern.compile(".*[/].*")));
pipe.add(new RegexMatches("OpenSquare", Pattern.compile(".*[\\[].*")));
pipe.add(new RegexMatches("CloseSquare", Pattern.compile(".*[\\]].*")));
pipe.add(new RegexMatches("Colon", Pattern.compile(".*[:].*")));
pipe.add(new RegexMatches("SemiColon", Pattern.compile(".*[;].*")));
pipe.add(new RegexMatches("Percent", Pattern.compile(".*[%].*")));
pipe.add(new RegexMatches("OpenParen", Pattern.compile(".*[(].*")));
pipe.add(new RegexMatches("CloseParen", Pattern.compile(".*[)].*")));
pipe.add(new RegexMatches("Comma", Pattern.compile(".*[,].*")));
pipe.add(new RegexMatches("Dot", Pattern.compile(".*[\\.].*")));
pipe.add(new RegexMatches("Apostrophe", Pattern.compile(".*['].*")));
pipe.add(new RegexMatches("QuotationMark", Pattern.compile(".*[\"].*")));
pipe.add(new RegexMatches("Star", Pattern.compile(".*[*].*")));
pipe.add(new RegexMatches("Equal", Pattern.compile(".*[=].*")));
pipe.add(new RegexMatches("Plus", Pattern.compile(".*[+].*")));
}
// Char n-gram
if (mc.isProperty("char_ngrams")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("char_ngrams_sizes"));
pipe.add(new TokenTextCharNGrams("CHARNGRAM=", ngrams));
}
// Suffixes
if (mc.isProperty("suffix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("suffix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharSuffix(ngram + "SUFFIX=", ngram));
}
}
// Prefixes
if (mc.isProperty("prefix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("prefix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharPrefix(ngram + "PREFIX=", ngram));
}
}
// Word shape
if (mc.isProperty("word_shape")) {
pipe.add(new WordShape());
}
if (mc.isProperty("triggers")) {
File file = new File(dictionaryPath);
try {
pipe.add(new TrieLexiconMembership("TRIGGER", file, true));
} catch (FileNotFoundException ex) {
throw new RuntimeException("There was a problem reading the dictionary for triggers matching: " + file.getName(), ex);
}
}
ModelConfiguration.ContextType context = ModelConfiguration.ContextType.valueOf(mc.getProperty("context"));
switch (context) {
case NONE:
break;
case WINDOW:
// pipe.add(new FeaturesInWindow("WINDOW=", -3, 3));
pipe.add(new FeaturesInWindow("WINDOW=", -1, 0, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -2, -1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", 0, 1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -1, 1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -3, -1, Pattern.compile("[WORD|LEMMA|POS|CHUNK]=.*"), true));
break;
case CONJUNCTIONS:
pipe.add(new OffsetConjunctions(true, Pattern.compile("WORD=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("LEMMA=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("POS=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
break;
}
// Print
// pipe.add(new PrintTokenSequenceFeatures());
pipe.add(new TokenSequence2FeatureVectorSequence(true, true));
return new SerialPipes(pipe);
}
|
public static Pipe get(final ModelConfiguration mc, final String dictionaryPath) {
ArrayList<Pipe> pipe = new ArrayList<>();
// Input parsing
pipe.add(new pt.ua.tm.trigner.model.pipe.Input2TokenSequence(mc));
// Capitalization
if (mc.isProperty("capitalization")) {
pipe.add(new RegexMatches("InitCap", Pattern.compile(CAPS + ".*")));
pipe.add(new RegexMatches("EndCap", Pattern.compile(".*" + CAPS)));
pipe.add(new RegexMatches("AllCaps", Pattern.compile(CAPS + "+")));
pipe.add(new RegexMatches("Lowercase", Pattern.compile(LOW + "+")));
pipe.add(new MixCase());
pipe.add(new RegexMatches("DigitsLettersAndSymbol", Pattern.compile("[0-9a-zA-z]+[-%/\\[\\]:;()'\"*=+][0-9a-zA-z]+")));
}
// Counting
if (mc.isProperty("counting")) {
pipe.add(new NumberOfCap());
pipe.add(new NumberOfDigit());
pipe.add(new WordLength());
}
// Symbols
if (mc.isProperty("symbols")) {
pipe.add(new RegexMatches("Hyphen", Pattern.compile(".*[-].*")));
pipe.add(new RegexMatches("BackSlash", Pattern.compile(".*[/].*")));
pipe.add(new RegexMatches("OpenSquare", Pattern.compile(".*[\\[].*")));
pipe.add(new RegexMatches("CloseSquare", Pattern.compile(".*[\\]].*")));
pipe.add(new RegexMatches("Colon", Pattern.compile(".*[:].*")));
pipe.add(new RegexMatches("SemiColon", Pattern.compile(".*[;].*")));
pipe.add(new RegexMatches("Percent", Pattern.compile(".*[%].*")));
pipe.add(new RegexMatches("OpenParen", Pattern.compile(".*[(].*")));
pipe.add(new RegexMatches("CloseParen", Pattern.compile(".*[)].*")));
pipe.add(new RegexMatches("Comma", Pattern.compile(".*[,].*")));
pipe.add(new RegexMatches("Dot", Pattern.compile(".*[\\.].*")));
pipe.add(new RegexMatches("Apostrophe", Pattern.compile(".*['].*")));
pipe.add(new RegexMatches("QuotationMark", Pattern.compile(".*[\"].*")));
pipe.add(new RegexMatches("Star", Pattern.compile(".*[*].*")));
pipe.add(new RegexMatches("Equal", Pattern.compile(".*[=].*")));
pipe.add(new RegexMatches("Plus", Pattern.compile(".*[+].*")));
}
// Char n-gram
if (mc.isProperty("char_ngrams")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("char_ngrams_sizes"));
pipe.add(new TokenTextCharNGrams("CHARNGRAM=", ngrams));
}
// Suffixes
if (mc.isProperty("suffix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("suffix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharSuffix(ngram + "SUFFIX=", ngram));
}
}
// Prefixes
if (mc.isProperty("prefix")) {
int[] ngrams = NGramsUtil.fromString(mc.getProperty("prefix_sizes"));
for (int ngram : ngrams) {
pipe.add(new TokenTextCharPrefix(ngram + "PREFIX=", ngram));
}
}
// Word shape
if (mc.isProperty("word_shape")) {
pipe.add(new WordShape());
}
if (mc.isProperty("triggers")) {
File file = new File(dictionaryPath);
try {
pipe.add(new TrieLexiconMembership("TRIGGER", file, true));
} catch (FileNotFoundException ex) {
throw new RuntimeException("There was a problem reading the dictionary for triggers matching: " + file.getName(), ex);
}
}
ModelConfiguration.ContextType context = ModelConfiguration.ContextType.valueOf(mc.getProperty("context"));
switch (context) {
case NONE:
break;
case WINDOW:
// pipe.add(new FeaturesInWindow("WINDOW=", -3, 3));
pipe.add(new FeaturesInWindow("WINDOW=", -1, 0, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -2, -1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", 0, 1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -1, 1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
pipe.add(new FeaturesInWindow("WINDOW=", -3, -1, Pattern.compile("(WORD|LEMMA|POS|CHUNK)=.*"), true));
break;
case CONJUNCTIONS:
pipe.add(new OffsetConjunctions(true, Pattern.compile("WORD=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("LEMMA=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
pipe.add(new OffsetConjunctions(true, Pattern.compile("POS=.*"), new int[][]{{-1, 0}, {-2, -1}, {0, 1}, {-1, 1}, {-3, -1}}));
break;
}
// Print
// pipe.add(new PrintTokenSequenceFeatures());
pipe.add(new TokenSequence2FeatureVectorSequence(true, true));
return new SerialPipes(pipe);
}
|
diff --git a/src/main/org/codehaus/groovy/ant/Groovyc.java b/src/main/org/codehaus/groovy/ant/Groovyc.java
index ad7d930b2..9903bf5d1 100644
--- a/src/main/org/codehaus/groovy/ant/Groovyc.java
+++ b/src/main/org/codehaus/groovy/ant/Groovyc.java
@@ -1,401 +1,401 @@
/*
$Id$
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.codehaus.groovy.ant;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.SourceFileScanner;
import org.codehaus.groovy.tools.FileSystemCompiler;
/**
* Compiles Groovy source files. This task can take the following
* arguments:
* <ul>
* <li>sourcedir
* <li>destdir
* <li>classpath
* </ul>
* Of these arguments, the <b>sourcedir</b> and <b>destdir</b> are required.
* <p>
* When this task executes, it will recursively scan the sourcedir and
* destdir looking for Groovy source files to compile. This task makes its
* compile decision based on timestamp.
*
* Based heavily on the Javac implementation in Ant
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class Groovyc extends MatchingTask {
private FileSystemCompiler compiler = new FileSystemCompiler();
private Path src;
private File destDir;
private Path compileClasspath;
private Path compileSourcepath;
protected boolean failOnError = true;
protected boolean listFiles = false;
protected File[] compileList = new File[0];
public Groovyc() {
}
/**
* Adds a path for source compilation.
*
* @return a nested src element.
*/
public Path createSrc() {
if (src == null) {
src = new Path(getProject());
}
return src.createPath();
}
/**
* Recreate src.
*
* @return a nested src element.
*/
protected Path recreateSrc() {
src = null;
return createSrc();
}
/**
* Set the source directories to find the source Java files.
* @param srcDir the source directories as a path
*/
public void setSrcdir(Path srcDir) {
if (src == null) {
src = srcDir;
}
else {
src.append(srcDir);
}
}
/**
* Gets the source dirs to find the source java files.
* @return the source directorys as a path
*/
public Path getSrcdir() {
return src;
}
/**
* Set the destination directory into which the Java source
* files should be compiled.
* @param destDir the destination director
*/
public void setDestdir(File destDir) {
this.destDir = destDir;
}
/**
* Enable verbose compiling which will display which files
* are being compiled
* @param verbose
*/
public void setVerbose(boolean verbose) {
compiler.setVerbose(verbose);
}
/**
* Gets the destination directory into which the java source files
* should be compiled.
* @return the destination directory
*/
public File getDestdir() {
return destDir;
}
/**
* Set the sourcepath to be used for this compilation.
* @param sourcepath the source path
*/
public void setSourcepath(Path sourcepath) {
if (compileSourcepath == null) {
compileSourcepath = sourcepath;
}
else {
compileSourcepath.append(sourcepath);
}
}
/**
* Gets the sourcepath to be used for this compilation.
* @return the source path
*/
public Path getSourcepath() {
return compileSourcepath;
}
/**
* Adds a path to sourcepath.
* @return a sourcepath to be configured
*/
public Path createSourcepath() {
if (compileSourcepath == null) {
compileSourcepath = new Path(getProject());
}
return compileSourcepath.createPath();
}
/**
* Adds a reference to a source path defined elsewhere.
* @param r a reference to a source path
*/
public void setSourcepathRef(Reference r) {
createSourcepath().setRefid(r);
}
/**
* Set the classpath to be used for this compilation.
*
* @param classpath an Ant Path object containing the compilation classpath.
*/
public void setClasspath(Path classpath) {
if (compileClasspath == null) {
compileClasspath = classpath;
}
else {
compileClasspath.append(classpath);
}
}
/**
* Gets the classpath to be used for this compilation.
* @return the class path
*/
public Path getClasspath() {
return compileClasspath;
}
/**
* Adds a path to the classpath.
* @return a class path to be configured
*/
public Path createClasspath() {
if (compileClasspath == null) {
compileClasspath = new Path(getProject());
}
return compileClasspath.createPath();
}
/**
* Adds a reference to a classpath defined elsewhere.
* @param r a reference to a classpath
*/
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
/**
* If true, list the source files being handed off to the compiler.
* @param list if true list the source files
*/
public void setListfiles(boolean list) {
listFiles = list;
}
/**
* Get the listfiles flag.
* @return the listfiles flag
*/
public boolean getListfiles() {
return listFiles;
}
/**
* Indicates whether the build will continue
* even if there are compilation errors; defaults to true.
* @param fail if true halt the build on failure
*/
public void setFailonerror(boolean fail) {
failOnError = fail;
}
/**
* @ant.attribute ignore="true"
* @param proceed inverse of failoferror
*/
public void setProceed(boolean proceed) {
failOnError = !proceed;
}
/**
* Gets the failonerror flag.
* @return the failonerror flag
*/
public boolean getFailonerror() {
return failOnError;
}
/**
* Executes the task.
* @exception BuildException if an error occurs
*/
public void execute() throws BuildException {
checkParameters();
resetFileLists();
// scan source directories and dest directory to build up
// compile lists
String[] list = src.list();
for (int i = 0; i < list.length; i++) {
File srcDir = getProject().resolveFile(list[i]);
if (!srcDir.exists()) {
throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation());
}
DirectoryScanner ds = this.getDirectoryScanner(srcDir);
String[] files = ds.getIncludedFiles();
scanDir(srcDir, destDir != null ? destDir : srcDir, files);
}
compile();
}
/**
* Clear the list of files to be compiled and copied..
*/
protected void resetFileLists() {
compileList = new File[0];
}
/**
* Scans the directory looking for source files to be compiled.
* The results are returned in the class variable compileList
*
* @param srcDir The source directory
* @param destDir The destination directory
* @param files An array of filenames
*/
protected void scanDir(File srcDir, File destDir, String[] files) {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("*.groovy");
m.setTo("*.class");
SourceFileScanner sfs = new SourceFileScanner(this);
File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m);
if (newFiles.length > 0) {
File[] newCompileList = new File[compileList.length + newFiles.length];
System.arraycopy(compileList, 0, newCompileList, 0, compileList.length);
System.arraycopy(newFiles, 0, newCompileList, compileList.length, newFiles.length);
compileList = newCompileList;
}
}
/**
* Gets the list of files to be compiled.
* @return the list of files as an array
*/
public File[] getFileList() {
return compileList;
}
protected void checkParameters() throws BuildException {
if (src == null) {
throw new BuildException("srcdir attribute must be set!", getLocation());
}
if (src.size() == 0) {
throw new BuildException("srcdir attribute must be set!", getLocation());
}
if (destDir != null && !destDir.isDirectory()) {
throw new BuildException(
"destination directory \"" + destDir + "\" does not exist " + "or is not a directory",
getLocation());
}
}
protected void compile() {
if (compileList.length > 0) {
log(
"Compiling "
+ compileList.length
+ " source file"
+ (compileList.length == 1 ? "" : "s")
+ (destDir != null ? " to " + destDir : ""));
if (listFiles) {
for (int i = 0; i < compileList.length; i++) {
String filename = compileList[i].getAbsolutePath();
log(filename);
}
}
try {
- String classpath = getClasspath().toString();
+ Path classpath = getClasspath();
if (classpath != null) {
- compiler.setClasspath(classpath);
+ compiler.setClasspath(classpath.toString());
}
compiler.setOutputDir(destDir);
compiler.compile(compileList);
}
catch (Exception e) {
String message = "Compile failed: " + e;
if (failOnError) {
throw new BuildException(message, e, getLocation());
}
else {
log(message, Project.MSG_ERR);
}
}
}
}
}
| false | true |
protected void compile() {
if (compileList.length > 0) {
log(
"Compiling "
+ compileList.length
+ " source file"
+ (compileList.length == 1 ? "" : "s")
+ (destDir != null ? " to " + destDir : ""));
if (listFiles) {
for (int i = 0; i < compileList.length; i++) {
String filename = compileList[i].getAbsolutePath();
log(filename);
}
}
try {
String classpath = getClasspath().toString();
if (classpath != null) {
compiler.setClasspath(classpath);
}
compiler.setOutputDir(destDir);
compiler.compile(compileList);
}
catch (Exception e) {
String message = "Compile failed: " + e;
if (failOnError) {
throw new BuildException(message, e, getLocation());
}
else {
log(message, Project.MSG_ERR);
}
}
}
}
|
protected void compile() {
if (compileList.length > 0) {
log(
"Compiling "
+ compileList.length
+ " source file"
+ (compileList.length == 1 ? "" : "s")
+ (destDir != null ? " to " + destDir : ""));
if (listFiles) {
for (int i = 0; i < compileList.length; i++) {
String filename = compileList[i].getAbsolutePath();
log(filename);
}
}
try {
Path classpath = getClasspath();
if (classpath != null) {
compiler.setClasspath(classpath.toString());
}
compiler.setOutputDir(destDir);
compiler.compile(compileList);
}
catch (Exception e) {
String message = "Compile failed: " + e;
if (failOnError) {
throw new BuildException(message, e, getLocation());
}
else {
log(message, Project.MSG_ERR);
}
}
}
}
|
diff --git a/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java b/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java
index bb08bb6bbf..dfe322327d 100644
--- a/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java
+++ b/drools-core/src/test/java/org/drools/reteoo/RuleFlowGroupTest.java
@@ -1,295 +1,298 @@
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.util.ArrayList;
import java.util.List;
import org.drools.DroolsTestCase;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;
import org.drools.common.DefaultFactHandle;
import org.drools.common.InternalAgenda;
import org.drools.common.PropagationContextImpl;
import org.drools.common.RuleFlowGroupImpl;
import org.drools.rule.Rule;
import org.drools.ruleflow.common.instance.IProcessInstance;
import org.drools.ruleflow.core.IConnection;
import org.drools.ruleflow.core.IEndNode;
import org.drools.ruleflow.core.IJoin;
import org.drools.ruleflow.core.IRuleFlowProcess;
import org.drools.ruleflow.core.IRuleSetNode;
import org.drools.ruleflow.core.ISplit;
import org.drools.ruleflow.core.IStartNode;
import org.drools.ruleflow.core.impl.Connection;
import org.drools.ruleflow.core.impl.EndNode;
import org.drools.ruleflow.core.impl.Join;
import org.drools.ruleflow.core.impl.RuleFlowProcess;
import org.drools.ruleflow.core.impl.RuleSetNode;
import org.drools.ruleflow.core.impl.Split;
import org.drools.ruleflow.core.impl.StartNode;
import org.drools.ruleflow.instance.IRuleFlowProcessInstance;
import org.drools.ruleflow.instance.impl.RuleFlowProcessInstance;
import org.drools.spi.Consequence;
import org.drools.spi.KnowledgeHelper;
import org.drools.spi.PropagationContext;
/**
* @author mproctor
*/
public class RuleFlowGroupTest extends DroolsTestCase {
public void testRuleFlowGroup() {
final RuleBase ruleBase = RuleBaseFactory.newRuleBase();
final ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newWorkingMemory();
final InternalAgenda agenda = (InternalAgenda) workingMemory.getAgenda();
final List list = new ArrayList();
// create the consequence
final Consequence consequence = new Consequence() {
/**
*
*/
private static final long serialVersionUID = -2596133893109870505L;
public void evaluate(KnowledgeHelper knowledgeHelper,
WorkingMemory workingMemory) {
list.add( knowledgeHelper.getRule() );
}
};
// create a rule for each rule flow groups
final Rule rule0 = new Rule( "test-rule0" );
rule0.setRuleFlowGroup( "rule-flow-group-0" );
rule0.setConsequence( consequence );
final RuleTerminalNode node0 = new RuleTerminalNode( 3,
new MockTupleSource( 2 ),
rule0,
rule0.getLhs() );
final Rule rule1 = new Rule( "test-rule1" );
rule1.setRuleFlowGroup( "rule-flow-group-1" );
rule1.setConsequence( consequence );
final RuleTerminalNode node1 = new RuleTerminalNode( 4,
new MockTupleSource( 2 ),
rule1,
rule1.getLhs() );
final Rule rule2 = new Rule( "test-rule2" );
rule2.setRuleFlowGroup( "rule-flow-group-2" );
rule2.setConsequence( consequence );
rule2.setSalience( 10 );
final RuleTerminalNode node2 = new RuleTerminalNode( 5,
new MockTupleSource( 2 ),
rule2,
rule2.getLhs() );
final Rule rule3 = new Rule( "test-rule3" );
rule3.setRuleFlowGroup( "rule-flow-group-3" );
rule3.setConsequence( consequence );
final RuleTerminalNode node3 = new RuleTerminalNode( 6,
new MockTupleSource( 2 ),
rule3,
rule3.getLhs() );
final PropagationContext context0 = new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
rule0,
null );
// nodes
final IStartNode start = new StartNode();
final IRuleSetNode ruleSet0 = new RuleSetNode();
ruleSet0.setRuleFlowGroup( "rule-flow-group-0" );
final IRuleSetNode ruleSet1 = new RuleSetNode();
ruleSet1.setRuleFlowGroup( "rule-flow-group-1" );
final IRuleSetNode ruleSet2 = new RuleSetNode();
ruleSet2.setRuleFlowGroup( "rule-flow-group-2" );
final IRuleSetNode ruleSet3 = new RuleSetNode();
ruleSet3.setRuleFlowGroup( "rule-flow-group-3" );
final ISplit split = new Split();
split.setType( ISplit.TYPE_AND );
final IJoin join = new Join();
join.setType( IJoin.TYPE_AND );
final IEndNode end = new EndNode();
// connections
new Connection( start,
ruleSet0,
IConnection.TYPE_NORMAL );
new Connection( ruleSet0,
split,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet1,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet2,
IConnection.TYPE_NORMAL );
new Connection( ruleSet1,
join,
IConnection.TYPE_NORMAL );
new Connection( ruleSet2,
join,
IConnection.TYPE_NORMAL );
new Connection( join,
ruleSet3,
IConnection.TYPE_NORMAL );
new Connection( ruleSet3,
end,
IConnection.TYPE_NORMAL );
// process
final IRuleFlowProcess process = new RuleFlowProcess();
process.addNode( start );
process.addNode( ruleSet0 );
process.addNode( ruleSet1 );
process.addNode( ruleSet2 );
process.addNode( ruleSet3 );
process.addNode( split );
process.addNode( join );
process.addNode( end );
// proces instance
final IRuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
processInstance.setAgenda( agenda );
processInstance.setProcess( process );
assertEquals( IProcessInstance.STATE_PENDING,
processInstance.getState() );
final RuleFlowGroupImpl ruleFlowGroup0 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-0" );
final RuleFlowGroupImpl ruleFlowGroup1 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-1" );
final RuleFlowGroupImpl ruleFlowGroup2 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-2" );
final RuleFlowGroupImpl ruleFlowGroup3 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-3" );
final ReteTuple tuple0 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple0,
context0,
workingMemory );
final ReteTuple tuple1 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple1,
context0,
workingMemory );
final ReteTuple tuple2 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node1.assertTuple( tuple2,
context0,
workingMemory );
final ReteTuple tuple3 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node2.assertTuple( tuple3,
context0,
workingMemory );
final ReteTuple tuple4 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node3.assertTuple( tuple4,
context0,
workingMemory );
// RuleFlowGroups should be populated, but the agenda shouldn't
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
// Activate process instance, the activations stay in the group,
// but should now also be in the Agenda
processInstance.start();
assertEquals( IProcessInstance.STATE_ACTIVE,
processInstance.getState() );
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 2,
agenda.agendaSize() );
// As we fire each rule they are removed from both the Agenda and the RuleFlowGroup
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup0.size() );
assertEquals( 1,
agenda.agendaSize() );
// on firing the last activation the child rule flow groups should
// activate and thus repopulate the agenda
agenda.fireNextItem( null );
+ workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 2,
agenda.agendaSize() );
// we set the salience higher on rule2, so it sould fire first and empty ruleFlowGroup2
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule1, which should activate AND-join and thus group 3
agenda.fireNextItem( null );
+ workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule3, and finishing execution
agenda.fireNextItem( null );
+ workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 0,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
assertEquals( IProcessInstance.STATE_COMPLETED,
processInstance.getState() );
}
}
| false | true |
public void testRuleFlowGroup() {
final RuleBase ruleBase = RuleBaseFactory.newRuleBase();
final ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newWorkingMemory();
final InternalAgenda agenda = (InternalAgenda) workingMemory.getAgenda();
final List list = new ArrayList();
// create the consequence
final Consequence consequence = new Consequence() {
/**
*
*/
private static final long serialVersionUID = -2596133893109870505L;
public void evaluate(KnowledgeHelper knowledgeHelper,
WorkingMemory workingMemory) {
list.add( knowledgeHelper.getRule() );
}
};
// create a rule for each rule flow groups
final Rule rule0 = new Rule( "test-rule0" );
rule0.setRuleFlowGroup( "rule-flow-group-0" );
rule0.setConsequence( consequence );
final RuleTerminalNode node0 = new RuleTerminalNode( 3,
new MockTupleSource( 2 ),
rule0,
rule0.getLhs() );
final Rule rule1 = new Rule( "test-rule1" );
rule1.setRuleFlowGroup( "rule-flow-group-1" );
rule1.setConsequence( consequence );
final RuleTerminalNode node1 = new RuleTerminalNode( 4,
new MockTupleSource( 2 ),
rule1,
rule1.getLhs() );
final Rule rule2 = new Rule( "test-rule2" );
rule2.setRuleFlowGroup( "rule-flow-group-2" );
rule2.setConsequence( consequence );
rule2.setSalience( 10 );
final RuleTerminalNode node2 = new RuleTerminalNode( 5,
new MockTupleSource( 2 ),
rule2,
rule2.getLhs() );
final Rule rule3 = new Rule( "test-rule3" );
rule3.setRuleFlowGroup( "rule-flow-group-3" );
rule3.setConsequence( consequence );
final RuleTerminalNode node3 = new RuleTerminalNode( 6,
new MockTupleSource( 2 ),
rule3,
rule3.getLhs() );
final PropagationContext context0 = new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
rule0,
null );
// nodes
final IStartNode start = new StartNode();
final IRuleSetNode ruleSet0 = new RuleSetNode();
ruleSet0.setRuleFlowGroup( "rule-flow-group-0" );
final IRuleSetNode ruleSet1 = new RuleSetNode();
ruleSet1.setRuleFlowGroup( "rule-flow-group-1" );
final IRuleSetNode ruleSet2 = new RuleSetNode();
ruleSet2.setRuleFlowGroup( "rule-flow-group-2" );
final IRuleSetNode ruleSet3 = new RuleSetNode();
ruleSet3.setRuleFlowGroup( "rule-flow-group-3" );
final ISplit split = new Split();
split.setType( ISplit.TYPE_AND );
final IJoin join = new Join();
join.setType( IJoin.TYPE_AND );
final IEndNode end = new EndNode();
// connections
new Connection( start,
ruleSet0,
IConnection.TYPE_NORMAL );
new Connection( ruleSet0,
split,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet1,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet2,
IConnection.TYPE_NORMAL );
new Connection( ruleSet1,
join,
IConnection.TYPE_NORMAL );
new Connection( ruleSet2,
join,
IConnection.TYPE_NORMAL );
new Connection( join,
ruleSet3,
IConnection.TYPE_NORMAL );
new Connection( ruleSet3,
end,
IConnection.TYPE_NORMAL );
// process
final IRuleFlowProcess process = new RuleFlowProcess();
process.addNode( start );
process.addNode( ruleSet0 );
process.addNode( ruleSet1 );
process.addNode( ruleSet2 );
process.addNode( ruleSet3 );
process.addNode( split );
process.addNode( join );
process.addNode( end );
// proces instance
final IRuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
processInstance.setAgenda( agenda );
processInstance.setProcess( process );
assertEquals( IProcessInstance.STATE_PENDING,
processInstance.getState() );
final RuleFlowGroupImpl ruleFlowGroup0 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-0" );
final RuleFlowGroupImpl ruleFlowGroup1 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-1" );
final RuleFlowGroupImpl ruleFlowGroup2 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-2" );
final RuleFlowGroupImpl ruleFlowGroup3 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-3" );
final ReteTuple tuple0 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple0,
context0,
workingMemory );
final ReteTuple tuple1 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple1,
context0,
workingMemory );
final ReteTuple tuple2 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node1.assertTuple( tuple2,
context0,
workingMemory );
final ReteTuple tuple3 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node2.assertTuple( tuple3,
context0,
workingMemory );
final ReteTuple tuple4 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node3.assertTuple( tuple4,
context0,
workingMemory );
// RuleFlowGroups should be populated, but the agenda shouldn't
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
// Activate process instance, the activations stay in the group,
// but should now also be in the Agenda
processInstance.start();
assertEquals( IProcessInstance.STATE_ACTIVE,
processInstance.getState() );
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 2,
agenda.agendaSize() );
// As we fire each rule they are removed from both the Agenda and the RuleFlowGroup
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup0.size() );
assertEquals( 1,
agenda.agendaSize() );
// on firing the last activation the child rule flow groups should
// activate and thus repopulate the agenda
agenda.fireNextItem( null );
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 2,
agenda.agendaSize() );
// we set the salience higher on rule2, so it sould fire first and empty ruleFlowGroup2
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule1, which should activate AND-join and thus group 3
agenda.fireNextItem( null );
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule3, and finishing execution
agenda.fireNextItem( null );
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 0,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
assertEquals( IProcessInstance.STATE_COMPLETED,
processInstance.getState() );
}
|
public void testRuleFlowGroup() {
final RuleBase ruleBase = RuleBaseFactory.newRuleBase();
final ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newWorkingMemory();
final InternalAgenda agenda = (InternalAgenda) workingMemory.getAgenda();
final List list = new ArrayList();
// create the consequence
final Consequence consequence = new Consequence() {
/**
*
*/
private static final long serialVersionUID = -2596133893109870505L;
public void evaluate(KnowledgeHelper knowledgeHelper,
WorkingMemory workingMemory) {
list.add( knowledgeHelper.getRule() );
}
};
// create a rule for each rule flow groups
final Rule rule0 = new Rule( "test-rule0" );
rule0.setRuleFlowGroup( "rule-flow-group-0" );
rule0.setConsequence( consequence );
final RuleTerminalNode node0 = new RuleTerminalNode( 3,
new MockTupleSource( 2 ),
rule0,
rule0.getLhs() );
final Rule rule1 = new Rule( "test-rule1" );
rule1.setRuleFlowGroup( "rule-flow-group-1" );
rule1.setConsequence( consequence );
final RuleTerminalNode node1 = new RuleTerminalNode( 4,
new MockTupleSource( 2 ),
rule1,
rule1.getLhs() );
final Rule rule2 = new Rule( "test-rule2" );
rule2.setRuleFlowGroup( "rule-flow-group-2" );
rule2.setConsequence( consequence );
rule2.setSalience( 10 );
final RuleTerminalNode node2 = new RuleTerminalNode( 5,
new MockTupleSource( 2 ),
rule2,
rule2.getLhs() );
final Rule rule3 = new Rule( "test-rule3" );
rule3.setRuleFlowGroup( "rule-flow-group-3" );
rule3.setConsequence( consequence );
final RuleTerminalNode node3 = new RuleTerminalNode( 6,
new MockTupleSource( 2 ),
rule3,
rule3.getLhs() );
final PropagationContext context0 = new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
rule0,
null );
// nodes
final IStartNode start = new StartNode();
final IRuleSetNode ruleSet0 = new RuleSetNode();
ruleSet0.setRuleFlowGroup( "rule-flow-group-0" );
final IRuleSetNode ruleSet1 = new RuleSetNode();
ruleSet1.setRuleFlowGroup( "rule-flow-group-1" );
final IRuleSetNode ruleSet2 = new RuleSetNode();
ruleSet2.setRuleFlowGroup( "rule-flow-group-2" );
final IRuleSetNode ruleSet3 = new RuleSetNode();
ruleSet3.setRuleFlowGroup( "rule-flow-group-3" );
final ISplit split = new Split();
split.setType( ISplit.TYPE_AND );
final IJoin join = new Join();
join.setType( IJoin.TYPE_AND );
final IEndNode end = new EndNode();
// connections
new Connection( start,
ruleSet0,
IConnection.TYPE_NORMAL );
new Connection( ruleSet0,
split,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet1,
IConnection.TYPE_NORMAL );
new Connection( split,
ruleSet2,
IConnection.TYPE_NORMAL );
new Connection( ruleSet1,
join,
IConnection.TYPE_NORMAL );
new Connection( ruleSet2,
join,
IConnection.TYPE_NORMAL );
new Connection( join,
ruleSet3,
IConnection.TYPE_NORMAL );
new Connection( ruleSet3,
end,
IConnection.TYPE_NORMAL );
// process
final IRuleFlowProcess process = new RuleFlowProcess();
process.addNode( start );
process.addNode( ruleSet0 );
process.addNode( ruleSet1 );
process.addNode( ruleSet2 );
process.addNode( ruleSet3 );
process.addNode( split );
process.addNode( join );
process.addNode( end );
// proces instance
final IRuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
processInstance.setAgenda( agenda );
processInstance.setProcess( process );
assertEquals( IProcessInstance.STATE_PENDING,
processInstance.getState() );
final RuleFlowGroupImpl ruleFlowGroup0 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-0" );
final RuleFlowGroupImpl ruleFlowGroup1 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-1" );
final RuleFlowGroupImpl ruleFlowGroup2 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-2" );
final RuleFlowGroupImpl ruleFlowGroup3 = (RuleFlowGroupImpl) agenda.getRuleFlowGroup( "rule-flow-group-3" );
final ReteTuple tuple0 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple0,
context0,
workingMemory );
final ReteTuple tuple1 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node0.assertTuple( tuple1,
context0,
workingMemory );
final ReteTuple tuple2 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node1.assertTuple( tuple2,
context0,
workingMemory );
final ReteTuple tuple3 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node2.assertTuple( tuple3,
context0,
workingMemory );
final ReteTuple tuple4 = new ReteTuple( new DefaultFactHandle( 1,
"cheese" ) );
node3.assertTuple( tuple4,
context0,
workingMemory );
// RuleFlowGroups should be populated, but the agenda shouldn't
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
// Activate process instance, the activations stay in the group,
// but should now also be in the Agenda
processInstance.start();
assertEquals( IProcessInstance.STATE_ACTIVE,
processInstance.getState() );
assertEquals( 2,
ruleFlowGroup0.size() );
assertEquals( 2,
agenda.agendaSize() );
// As we fire each rule they are removed from both the Agenda and the RuleFlowGroup
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup0.size() );
assertEquals( 1,
agenda.agendaSize() );
// on firing the last activation the child rule flow groups should
// activate and thus repopulate the agenda
agenda.fireNextItem( null );
workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 1,
ruleFlowGroup2.size() );
assertEquals( 2,
agenda.agendaSize() );
// we set the salience higher on rule2, so it sould fire first and empty ruleFlowGroup2
agenda.fireNextItem( null );
assertEquals( 1,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule1, which should activate AND-join and thus group 3
agenda.fireNextItem( null );
workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 1,
ruleFlowGroup3.size() );
assertEquals( 1,
agenda.agendaSize() );
// executing rule3, and finishing execution
agenda.fireNextItem( null );
workingMemory.executeQueuedActions();
assertEquals( 0,
ruleFlowGroup0.size() );
assertEquals( 0,
ruleFlowGroup1.size() );
assertEquals( 0,
ruleFlowGroup2.size() );
assertEquals( 0,
ruleFlowGroup3.size() );
assertEquals( 0,
agenda.agendaSize() );
assertEquals( IProcessInstance.STATE_COMPLETED,
processInstance.getState() );
}
|
diff --git a/components/dotnet-executable/src/main/java/npanday/executable/CommandExecutor.java b/components/dotnet-executable/src/main/java/npanday/executable/CommandExecutor.java
index 9736c5bf..cde1e527 100644
--- a/components/dotnet-executable/src/main/java/npanday/executable/CommandExecutor.java
+++ b/components/dotnet-executable/src/main/java/npanday/executable/CommandExecutor.java
@@ -1,495 +1,495 @@
/*
* 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 npanday.executable;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.cli.*;
import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.StringUtils;
//import org.codehaus.plexus.util.cli.shell.BourneShell;
//import org.codehaus.plexus.util.cli.shell.CmdShell;
//import org.codehaus.plexus.util.cli.shell.CommandShell;
import org.codehaus.plexus.util.cli.shell.Shell;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.io.File;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.lang.reflect.*;
/**
* Provides services for executing commands (executables or compilers). A <code>NetExecutable</code> or
* <code>CompilerExecutable</code> implementation can use the services of this interface for executing commands.
*
* @author Shane Isbell
*/
public interface CommandExecutor
{
/**
* Sets the plexus logger.
*
* @param logger the plexus logger
*/
void setLogger( Logger logger );
/**
* Executes the command for the specified executable and list of command options.
*
* @param executable the name of the executable (csc, xsd, etc).
* @param commands the command options for the compiler/executable
* @throws ExecutionException if compiler or executable writes anything to the standard error stream or if the process
* returns a process result != 0.
*/
void executeCommand( String executable, List<String> commands )
throws ExecutionException;
/**
* Executes the command for the specified executable and list of command options.
*
* @param executable the name of the executable (csc, xsd, etc).
* @param commands the commands options for the compiler/executable
* @param failsOnErrorOutput if true, throws an <code>ExecutionException</code> if there the compiler or executable
* writes anything to the error output stream. By default, this value is true
* @throws ExecutionException if compiler or executable writes anything to the standard error stream (provided the
* failsOnErrorOutput is not false) or if the process returns a process result != 0.
*/
void executeCommand( String executable, List<String> commands, boolean failsOnErrorOutput )
throws ExecutionException;
/**
* Executes the command for the specified executable and list of command options. If the compiler or executable is
* not within the environmental path, you should use this method to specify the working directory. Always use this
* method for executables located within the local maven repository.
*
* @param executable the name of the executable (csc, xsd, etc).
* @param commands the command options for the compiler/executable
* @param workingDirectory the directory where the command will be executed
* @throws ExecutionException if compiler or executable writes anything to the standard error stream (provided the
* failsOnErrorOutput is not false) or if the process returns a process result != 0.
*/
void executeCommand( String executable, List<String> commands, File workingDirectory, boolean failsOnErrorOutput )
throws ExecutionException;
/**
* Returns the process result of executing the command. Typically a value of 0 means that the process executed
* successfully.
*
* @return the process result of executing the command
*/
int getResult();
/**
* Returns the standard output from executing the command.
*
* @return the standard output from executing the command
*/
String getStandardOut();
/**
* Returns the standard error from executing the command.
*
* @return the standard error from executing the command
*/
String getStandardError();
/**
* Provides factory services for creating a default instance of the command executor.
*/
public static class Factory
{
/**
* Constructor
*/
private Factory()
{
}
/**
* Returns a default instance of the command executor
*
* @return a default instance of the command executor
*/
public static CommandExecutor createDefaultCommmandExecutor()
{
return new CommandExecutor()
{
/**
* Instance of a plugin logger.
*/
private Logger logger;
/**
* Standard Out
*/
private StreamConsumer stdOut;
/**
* Standard Error
*/
private ErrorStreamConsumer stdErr;
/**
* Process result
*/
private int result;
public void setLogger( Logger logger )
{
this.logger = logger;
}
public void executeCommand( String executable, List<String> commands )
throws ExecutionException
{
executeCommand( executable, commands, null, true );
}
public void executeCommand( String executable, List<String> commands, boolean failsOnErrorOutput )
throws ExecutionException
{
executeCommand( executable, commands, null, failsOnErrorOutput );
}
public void executeCommand( String executable, List<String> commands, File workingDirectory,
boolean failsOnErrorOutput )
throws ExecutionException
{
if ( commands == null )
{
commands = new ArrayList<String>();
}
stdOut = new StreamConsumerImpl();
stdErr = new ErrorStreamConsumer();
Commandline commandline = new Commandline()
{
protected Map envVars = Collections.synchronizedMap( new LinkedHashMap() );
public Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
//verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = getWorkingDirectory();
try
{
String cmd = this.toString();
if ( workingDir == null )
{
//process = Runtime.getRuntime().exec( getShellCommandline(), environment );
process = Runtime.getRuntime().exec( cmd, environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
//process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
process = Runtime.getRuntime().exec( cmd, environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
}
public String[] getEnvironmentVariables()
throws CommandLineException
{
try
{
addSystemEnvironment();
}
catch ( Exception e )
{
throw new CommandLineException( "Error setting up environmental variables", e );
}
String[] environmentVars = new String[envVars.size()];
int i = 0;
for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); )
{
String name = (String) iterator.next();
String value = (String) envVars.get( name );
environmentVars[i] = name + "=" + value;
i++;
}
return environmentVars;
}
public void addEnvironment( String name, String value )
{
//envVars.add( name + "=" + value );
envVars.put( name, value );
}
/**
* Add system environment variables
*/
public void addSystemEnvironment()
throws Exception
{
Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
if ( !envVars.containsKey( key ) )
{
addEnvironment( key, systemEnvVars.getProperty( key ) );
}
}
}
public String toString()
{
StringBuffer strBuff = new StringBuffer("");
for(String command : getShellCommandline())
{
strBuff.append(" ");
strBuff.append(escapeCmdParams(command));
}
return strBuff.toString().trim();
}
// escaped to make use of dotnet style of command escapes .
// Eg. /define:"CONFIG=\"Debug\",DEBUG=-1,TRACE=-1,_MyType=\"Windows\",PLATFORM=\"AnyCPU\""
private String escapeCmdParams(String param)
{
if(param == null)
return null;
String str = param;
if(param.startsWith("/") && param.indexOf(":") > 0)
{
int delem = param.indexOf(":") + 1;
String command = param.substring(0, delem);
String value = param.substring(delem);
if(value.indexOf(" ") > 0 || value.indexOf("\"") > 0)
{
value = "\"" + value.replaceAll("\"", "\\\\\"") + "\"";
}
str = command + value;
}
else if(param.startsWith("@"))
{
str = param;
}
else if(param.indexOf(" ") > 0)
{
str = "\"" + param + "\"";
}
return str;
}
};
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()]));
if ( workingDirectory != null && workingDirectory.exists() )
{
commandline.setWorkingDirectory( workingDirectory.getAbsolutePath() );
}
try
{
result = CommandLineUtils.executeCommandLine( commandline, stdOut, stdErr );
if ( logger != null )
{
logger.debug( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
else
{
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
if ( ( failsOnErrorOutput && stdErr.hasError() ) || result != 0 )
{
throw new ExecutionException( "NPANDAY-040-001: Could not execute: Command = " +
commandline.toString() + ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new ExecutionException(
"NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
public int getResult()
{
return result;
}
public String getStandardOut()
{
return stdOut.toString();
}
public String getStandardError()
{
return stdErr.toString();
}
/**
* Provides behavior for determining whether the command utility wrote anything to the Standard Error Stream.
* NOTE: I am using this to decide whether to fail the NPanday build. If the compiler implementation chooses
* to write warnings to the error stream, then the build will fail on warnings!!!
*/
class ErrorStreamConsumer
implements StreamConsumer
{
/**
* Is true if there was anything consumed from the stream, otherwise false
*/
private boolean error;
/**
* Buffer to store the stream
*/
private StringBuffer sbe = new StringBuffer();
public ErrorStreamConsumer()
{
if ( logger == null )
{
System.out.println( "NPANDAY-040-003: Error Log not set: Will not output error logs" );
}
error = false;
}
public void consumeLine( String line )
{
sbe.append( line );
if ( logger != null )
{
- logger.error( line );
+ logger.info( line );
}
error = true;
}
/**
* Returns false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*
* @return false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*/
public boolean hasError()
{
return error;
}
/**
* Returns the error stream
*
* @return error stream
*/
public String toString()
{
return sbe.toString();
}
}
/**
* StreamConsumer instance that buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
};
}
}
}
| true | true |
public static CommandExecutor createDefaultCommmandExecutor()
{
return new CommandExecutor()
{
/**
* Instance of a plugin logger.
*/
private Logger logger;
/**
* Standard Out
*/
private StreamConsumer stdOut;
/**
* Standard Error
*/
private ErrorStreamConsumer stdErr;
/**
* Process result
*/
private int result;
public void setLogger( Logger logger )
{
this.logger = logger;
}
public void executeCommand( String executable, List<String> commands )
throws ExecutionException
{
executeCommand( executable, commands, null, true );
}
public void executeCommand( String executable, List<String> commands, boolean failsOnErrorOutput )
throws ExecutionException
{
executeCommand( executable, commands, null, failsOnErrorOutput );
}
public void executeCommand( String executable, List<String> commands, File workingDirectory,
boolean failsOnErrorOutput )
throws ExecutionException
{
if ( commands == null )
{
commands = new ArrayList<String>();
}
stdOut = new StreamConsumerImpl();
stdErr = new ErrorStreamConsumer();
Commandline commandline = new Commandline()
{
protected Map envVars = Collections.synchronizedMap( new LinkedHashMap() );
public Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
//verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = getWorkingDirectory();
try
{
String cmd = this.toString();
if ( workingDir == null )
{
//process = Runtime.getRuntime().exec( getShellCommandline(), environment );
process = Runtime.getRuntime().exec( cmd, environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
//process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
process = Runtime.getRuntime().exec( cmd, environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
}
public String[] getEnvironmentVariables()
throws CommandLineException
{
try
{
addSystemEnvironment();
}
catch ( Exception e )
{
throw new CommandLineException( "Error setting up environmental variables", e );
}
String[] environmentVars = new String[envVars.size()];
int i = 0;
for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); )
{
String name = (String) iterator.next();
String value = (String) envVars.get( name );
environmentVars[i] = name + "=" + value;
i++;
}
return environmentVars;
}
public void addEnvironment( String name, String value )
{
//envVars.add( name + "=" + value );
envVars.put( name, value );
}
/**
* Add system environment variables
*/
public void addSystemEnvironment()
throws Exception
{
Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
if ( !envVars.containsKey( key ) )
{
addEnvironment( key, systemEnvVars.getProperty( key ) );
}
}
}
public String toString()
{
StringBuffer strBuff = new StringBuffer("");
for(String command : getShellCommandline())
{
strBuff.append(" ");
strBuff.append(escapeCmdParams(command));
}
return strBuff.toString().trim();
}
// escaped to make use of dotnet style of command escapes .
// Eg. /define:"CONFIG=\"Debug\",DEBUG=-1,TRACE=-1,_MyType=\"Windows\",PLATFORM=\"AnyCPU\""
private String escapeCmdParams(String param)
{
if(param == null)
return null;
String str = param;
if(param.startsWith("/") && param.indexOf(":") > 0)
{
int delem = param.indexOf(":") + 1;
String command = param.substring(0, delem);
String value = param.substring(delem);
if(value.indexOf(" ") > 0 || value.indexOf("\"") > 0)
{
value = "\"" + value.replaceAll("\"", "\\\\\"") + "\"";
}
str = command + value;
}
else if(param.startsWith("@"))
{
str = param;
}
else if(param.indexOf(" ") > 0)
{
str = "\"" + param + "\"";
}
return str;
}
};
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()]));
if ( workingDirectory != null && workingDirectory.exists() )
{
commandline.setWorkingDirectory( workingDirectory.getAbsolutePath() );
}
try
{
result = CommandLineUtils.executeCommandLine( commandline, stdOut, stdErr );
if ( logger != null )
{
logger.debug( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
else
{
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
if ( ( failsOnErrorOutput && stdErr.hasError() ) || result != 0 )
{
throw new ExecutionException( "NPANDAY-040-001: Could not execute: Command = " +
commandline.toString() + ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new ExecutionException(
"NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
public int getResult()
{
return result;
}
public String getStandardOut()
{
return stdOut.toString();
}
public String getStandardError()
{
return stdErr.toString();
}
/**
* Provides behavior for determining whether the command utility wrote anything to the Standard Error Stream.
* NOTE: I am using this to decide whether to fail the NPanday build. If the compiler implementation chooses
* to write warnings to the error stream, then the build will fail on warnings!!!
*/
class ErrorStreamConsumer
implements StreamConsumer
{
/**
* Is true if there was anything consumed from the stream, otherwise false
*/
private boolean error;
/**
* Buffer to store the stream
*/
private StringBuffer sbe = new StringBuffer();
public ErrorStreamConsumer()
{
if ( logger == null )
{
System.out.println( "NPANDAY-040-003: Error Log not set: Will not output error logs" );
}
error = false;
}
public void consumeLine( String line )
{
sbe.append( line );
if ( logger != null )
{
logger.error( line );
}
error = true;
}
/**
* Returns false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*
* @return false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*/
public boolean hasError()
{
return error;
}
/**
* Returns the error stream
*
* @return error stream
*/
public String toString()
{
return sbe.toString();
}
}
/**
* StreamConsumer instance that buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
};
}
|
public static CommandExecutor createDefaultCommmandExecutor()
{
return new CommandExecutor()
{
/**
* Instance of a plugin logger.
*/
private Logger logger;
/**
* Standard Out
*/
private StreamConsumer stdOut;
/**
* Standard Error
*/
private ErrorStreamConsumer stdErr;
/**
* Process result
*/
private int result;
public void setLogger( Logger logger )
{
this.logger = logger;
}
public void executeCommand( String executable, List<String> commands )
throws ExecutionException
{
executeCommand( executable, commands, null, true );
}
public void executeCommand( String executable, List<String> commands, boolean failsOnErrorOutput )
throws ExecutionException
{
executeCommand( executable, commands, null, failsOnErrorOutput );
}
public void executeCommand( String executable, List<String> commands, File workingDirectory,
boolean failsOnErrorOutput )
throws ExecutionException
{
if ( commands == null )
{
commands = new ArrayList<String>();
}
stdOut = new StreamConsumerImpl();
stdErr = new ErrorStreamConsumer();
Commandline commandline = new Commandline()
{
protected Map envVars = Collections.synchronizedMap( new LinkedHashMap() );
public Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
//verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = getWorkingDirectory();
try
{
String cmd = this.toString();
if ( workingDir == null )
{
//process = Runtime.getRuntime().exec( getShellCommandline(), environment );
process = Runtime.getRuntime().exec( cmd, environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
//process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
process = Runtime.getRuntime().exec( cmd, environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
}
public String[] getEnvironmentVariables()
throws CommandLineException
{
try
{
addSystemEnvironment();
}
catch ( Exception e )
{
throw new CommandLineException( "Error setting up environmental variables", e );
}
String[] environmentVars = new String[envVars.size()];
int i = 0;
for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); )
{
String name = (String) iterator.next();
String value = (String) envVars.get( name );
environmentVars[i] = name + "=" + value;
i++;
}
return environmentVars;
}
public void addEnvironment( String name, String value )
{
//envVars.add( name + "=" + value );
envVars.put( name, value );
}
/**
* Add system environment variables
*/
public void addSystemEnvironment()
throws Exception
{
Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
if ( !envVars.containsKey( key ) )
{
addEnvironment( key, systemEnvVars.getProperty( key ) );
}
}
}
public String toString()
{
StringBuffer strBuff = new StringBuffer("");
for(String command : getShellCommandline())
{
strBuff.append(" ");
strBuff.append(escapeCmdParams(command));
}
return strBuff.toString().trim();
}
// escaped to make use of dotnet style of command escapes .
// Eg. /define:"CONFIG=\"Debug\",DEBUG=-1,TRACE=-1,_MyType=\"Windows\",PLATFORM=\"AnyCPU\""
private String escapeCmdParams(String param)
{
if(param == null)
return null;
String str = param;
if(param.startsWith("/") && param.indexOf(":") > 0)
{
int delem = param.indexOf(":") + 1;
String command = param.substring(0, delem);
String value = param.substring(delem);
if(value.indexOf(" ") > 0 || value.indexOf("\"") > 0)
{
value = "\"" + value.replaceAll("\"", "\\\\\"") + "\"";
}
str = command + value;
}
else if(param.startsWith("@"))
{
str = param;
}
else if(param.indexOf(" ") > 0)
{
str = "\"" + param + "\"";
}
return str;
}
};
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()]));
if ( workingDirectory != null && workingDirectory.exists() )
{
commandline.setWorkingDirectory( workingDirectory.getAbsolutePath() );
}
try
{
result = CommandLineUtils.executeCommandLine( commandline, stdOut, stdErr );
if ( logger != null )
{
logger.debug( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
else
{
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline +
", Result = " + result );
}
if ( ( failsOnErrorOutput && stdErr.hasError() ) || result != 0 )
{
throw new ExecutionException( "NPANDAY-040-001: Could not execute: Command = " +
commandline.toString() + ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new ExecutionException(
"NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
public int getResult()
{
return result;
}
public String getStandardOut()
{
return stdOut.toString();
}
public String getStandardError()
{
return stdErr.toString();
}
/**
* Provides behavior for determining whether the command utility wrote anything to the Standard Error Stream.
* NOTE: I am using this to decide whether to fail the NPanday build. If the compiler implementation chooses
* to write warnings to the error stream, then the build will fail on warnings!!!
*/
class ErrorStreamConsumer
implements StreamConsumer
{
/**
* Is true if there was anything consumed from the stream, otherwise false
*/
private boolean error;
/**
* Buffer to store the stream
*/
private StringBuffer sbe = new StringBuffer();
public ErrorStreamConsumer()
{
if ( logger == null )
{
System.out.println( "NPANDAY-040-003: Error Log not set: Will not output error logs" );
}
error = false;
}
public void consumeLine( String line )
{
sbe.append( line );
if ( logger != null )
{
logger.info( line );
}
error = true;
}
/**
* Returns false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*
* @return false if the command utility wrote to the Standard Error Stream, otherwise returns true.
*/
public boolean hasError()
{
return error;
}
/**
* Returns the error stream
*
* @return error stream
*/
public String toString()
{
return sbe.toString();
}
}
/**
* StreamConsumer instance that buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
};
}
|
diff --git a/src/test/java/org/neo4j/examples/osgi/OSGiTest.java b/src/test/java/org/neo4j/examples/osgi/OSGiTest.java
index 1e32d6c..112d705 100644
--- a/src/test/java/org/neo4j/examples/osgi/OSGiTest.java
+++ b/src/test/java/org/neo4j/examples/osgi/OSGiTest.java
@@ -1,52 +1,52 @@
package org.neo4j.examples.osgi;
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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, see <http://www.gnu.org/licenses/>.
*/
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import org.junit.Test;
import org.ops4j.pax.exam.player.Player;
import org.ops4j.pax.exam.testforge.SingleClassProvider;
import org.ops4j.pax.exam.testforge.WaitForService;
import org.osgi.service.log.LogService;
import org.slf4j.LoggerFactory;
public class OSGiTest {
@Test
public void lessonTest()
throws Exception
{
new Player().with(
options(
mavenBundle().groupId( "org.ops4j.pax.logging" ).artifactId( "pax-logging-service" ).version( "1.6.2" ),
mavenBundle().groupId( "org.apache.geronimo.specs" ).artifactId( "geronimo-jta_1.1_spec" ).version( "1.1" ).start(),
- mavenBundle().groupId( "org.neo4j" ).artifactId( "neo4j-kernel" ).version( "1.3" ).start()
+ mavenBundle().groupId( "org.neo4j" ).artifactId( "neo4j-kernel" ).version( "1.4.M03" ).start()
)
)
.test( WaitForService.class, LogService.class.getName(), 5000 )
// set skip systembundle=true because equinox is indeed loading LoggerFactory from a different source.
.test( SingleClassProvider.class, LoggerFactory.class.getName(), true )
.play();
}
}
| true | true |
public void lessonTest()
throws Exception
{
new Player().with(
options(
mavenBundle().groupId( "org.ops4j.pax.logging" ).artifactId( "pax-logging-service" ).version( "1.6.2" ),
mavenBundle().groupId( "org.apache.geronimo.specs" ).artifactId( "geronimo-jta_1.1_spec" ).version( "1.1" ).start(),
mavenBundle().groupId( "org.neo4j" ).artifactId( "neo4j-kernel" ).version( "1.3" ).start()
)
)
.test( WaitForService.class, LogService.class.getName(), 5000 )
// set skip systembundle=true because equinox is indeed loading LoggerFactory from a different source.
.test( SingleClassProvider.class, LoggerFactory.class.getName(), true )
.play();
}
|
public void lessonTest()
throws Exception
{
new Player().with(
options(
mavenBundle().groupId( "org.ops4j.pax.logging" ).artifactId( "pax-logging-service" ).version( "1.6.2" ),
mavenBundle().groupId( "org.apache.geronimo.specs" ).artifactId( "geronimo-jta_1.1_spec" ).version( "1.1" ).start(),
mavenBundle().groupId( "org.neo4j" ).artifactId( "neo4j-kernel" ).version( "1.4.M03" ).start()
)
)
.test( WaitForService.class, LogService.class.getName(), 5000 )
// set skip systembundle=true because equinox is indeed loading LoggerFactory from a different source.
.test( SingleClassProvider.class, LoggerFactory.class.getName(), true )
.play();
}
|
diff --git a/src/main/java/net/croxis/plugins/research/RInventoryListener.java b/src/main/java/net/croxis/plugins/research/RInventoryListener.java
index e2c0b78..651dc23 100644
--- a/src/main/java/net/croxis/plugins/research/RInventoryListener.java
+++ b/src/main/java/net/croxis/plugins/research/RInventoryListener.java
@@ -1,21 +1,22 @@
package net.croxis.plugins.research;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import java.util.HashSet;
@SuppressWarnings("unused")
public class RInventoryListener implements Listener{
@EventHandler
public void onInventoryCraft(CraftItemEvent event){
if (event.getWhoClicked().hasPermission("research")){
//if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getResult().getTypeId()) && event.getPlayer().hasPermission("research"))
+ Research.logDebug("Craft Event: " + event.getWhoClicked().getName() + "|" + Integer.toString(event.getRecipe().getResult().getTypeId()) +"|"+ event.getRecipe().toString());
if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getRecipe().getResult().getTypeId())){
- Research.logDebug("Canceling Craft: " + event.getWhoClicked().getName() + "|" + event.getRecipe().toString());
+ Research.logDebug("Canceling Craft: " + event.getWhoClicked().getName() + "|" + Integer.toString(event.getRecipe().getResult().getTypeId()) +"|"+ event.getRecipe().toString());
event.setCancelled(true);
}
}
}
}
| false | true |
public void onInventoryCraft(CraftItemEvent event){
if (event.getWhoClicked().hasPermission("research")){
//if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getResult().getTypeId()) && event.getPlayer().hasPermission("research"))
if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getRecipe().getResult().getTypeId())){
Research.logDebug("Canceling Craft: " + event.getWhoClicked().getName() + "|" + event.getRecipe().toString());
event.setCancelled(true);
}
}
}
|
public void onInventoryCraft(CraftItemEvent event){
if (event.getWhoClicked().hasPermission("research")){
//if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getResult().getTypeId()) && event.getPlayer().hasPermission("research"))
Research.logDebug("Craft Event: " + event.getWhoClicked().getName() + "|" + Integer.toString(event.getRecipe().getResult().getTypeId()) +"|"+ event.getRecipe().toString());
if(TechManager.players.get(event.getWhoClicked()).cantCraft.contains(event.getRecipe().getResult().getTypeId())){
Research.logDebug("Canceling Craft: " + event.getWhoClicked().getName() + "|" + Integer.toString(event.getRecipe().getResult().getTypeId()) +"|"+ event.getRecipe().toString());
event.setCancelled(true);
}
}
}
|
diff --git a/ZPI1/src/com/pwr/zpi/ChartActivity.java b/ZPI1/src/com/pwr/zpi/ChartActivity.java
index 74c0ba9..5f91520 100644
--- a/ZPI1/src/com/pwr/zpi/ChartActivity.java
+++ b/ZPI1/src/com/pwr/zpi/ChartActivity.java
@@ -1,84 +1,90 @@
package com.pwr.zpi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import com.fima.chartview.ChartView;
import com.fima.chartview.LinearSeries;
import com.fima.chartview.LinearSeries.LinearPoint;
import com.pwr.zpi.adapters.ValueLabelAdapter;
import com.pwr.zpi.adapters.ValueLabelAdapter.LabelOrientation;
import com.pwr.zpi.utils.ChartDataHelperContainter;
public class ChartActivity extends Activity {
public static final String CHART_DATA_KEY = "chart_data";
ChartView speed;
ChartView altitude;
ChartDataHelperContainter container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart_activity);
speed = (ChartView) findViewById(R.id.speed_chart_view);
altitude = (ChartView) findViewById(R.id.altitude_chart_view);
container = getChartDataFromIntent();
new ChartDataLoader().execute(null, null); //overloaded method, two nulls to distinct
}
private ChartDataHelperContainter getChartDataFromIntent() {
return getIntent().getParcelableExtra(CHART_DATA_KEY);
}
private class ChartDataLoader extends AsyncTask<Void, Void, Void> {
LinearSeries seriesSpeed;
LinearSeries seriesAltitude;
@Override
protected Void doInBackground(Void... params) {
seriesSpeed = new LinearSeries();
seriesSpeed.setLineColor(getResources().getColor(R.color.chart_speed));
seriesSpeed.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
seriesAltitude = new LinearSeries();
seriesAltitude.setLineColor(getResources().getColor(R.color.chart_altitude));
seriesAltitude.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
double distance[] = container.getDistance();
double altitude[] = container.getAltitude();
double speed[] = container.getSpeed();
for (int i = 0; i < distance.length; i++) {
- seriesSpeed.addPoint(new LinearPoint(distance[i], speed[i]));
- seriesAltitude.addPoint(new LinearPoint(distance[i], altitude[i]));
+ if (container.getDistanceMin() <= distance[i] && distance[i] <= container.getDistanceMax()) {
+ if (container.getSpeedMin() <= speed[i] && speed[i] <= container.getSpeedMax()) {
+ seriesSpeed.addPoint(new LinearPoint(distance[i], speed[i]));
+ }
+ if (container.getAltitudeMin() <= altitude[i] && altitude[i] <= container.getAltitudeMax()) {
+ seriesAltitude.addPoint(new LinearPoint(distance[i], altitude[i]));
+ }
+ }
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Add chart view data
speed.addSeries(seriesSpeed);
speed.setLeftLabelAdapter(new ValueLabelAdapter(ChartActivity.this, LabelOrientation.VERTICAL));
speed.setBottomLabelAdapter(new ValueLabelAdapter(ChartActivity.this, LabelOrientation.HORIZONTAL));
altitude.addSeries(seriesAltitude);
altitude.setLeftLabelAdapter(new ValueLabelAdapter(ChartActivity.this, LabelOrientation.VERTICAL));
altitude.setBottomLabelAdapter(new ValueLabelAdapter(ChartActivity.this, LabelOrientation.HORIZONTAL));
speed.setVisibility(View.VISIBLE);
altitude.setVisibility(View.VISIBLE);
findViewById(R.id.progressBarSpeed).setVisibility(View.GONE);
findViewById(R.id.progressBarAltitude).setVisibility(View.GONE);
}
}
}
| true | true |
protected Void doInBackground(Void... params) {
seriesSpeed = new LinearSeries();
seriesSpeed.setLineColor(getResources().getColor(R.color.chart_speed));
seriesSpeed.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
seriesAltitude = new LinearSeries();
seriesAltitude.setLineColor(getResources().getColor(R.color.chart_altitude));
seriesAltitude.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
double distance[] = container.getDistance();
double altitude[] = container.getAltitude();
double speed[] = container.getSpeed();
for (int i = 0; i < distance.length; i++) {
seriesSpeed.addPoint(new LinearPoint(distance[i], speed[i]));
seriesAltitude.addPoint(new LinearPoint(distance[i], altitude[i]));
}
return null;
}
|
protected Void doInBackground(Void... params) {
seriesSpeed = new LinearSeries();
seriesSpeed.setLineColor(getResources().getColor(R.color.chart_speed));
seriesSpeed.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
seriesAltitude = new LinearSeries();
seriesAltitude.setLineColor(getResources().getColor(R.color.chart_altitude));
seriesAltitude.setLineWidth(getResources().getDimension(R.dimen.chart_line_width));
double distance[] = container.getDistance();
double altitude[] = container.getAltitude();
double speed[] = container.getSpeed();
for (int i = 0; i < distance.length; i++) {
if (container.getDistanceMin() <= distance[i] && distance[i] <= container.getDistanceMax()) {
if (container.getSpeedMin() <= speed[i] && speed[i] <= container.getSpeedMax()) {
seriesSpeed.addPoint(new LinearPoint(distance[i], speed[i]));
}
if (container.getAltitudeMin() <= altitude[i] && altitude[i] <= container.getAltitudeMax()) {
seriesAltitude.addPoint(new LinearPoint(distance[i], altitude[i]));
}
}
}
return null;
}
|
diff --git a/app/utils/CloudifyUtils.java b/app/utils/CloudifyUtils.java
index 3e05638..5ff125c 100644
--- a/app/utils/CloudifyUtils.java
+++ b/app/utils/CloudifyUtils.java
@@ -1,219 +1,218 @@
/*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. 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 utils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.NovaAsyncApi;
import org.jclouds.openstack.nova.v2_0.domain.Ingress;
import org.jclouds.openstack.nova.v2_0.domain.IpProtocol;
import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
import org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;
import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;
import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;
import org.jclouds.rest.RestContext;
import server.ApplicationContext;
import server.exceptions.ServerException;
import beans.config.ServerConfig.CloudBootstrapConfiguration;
import com.google.common.collect.FluentIterable;
/**
* This class provides different static cloudify utilities methods.
* @author adaml
*
*/
public class CloudifyUtils {
/**
* Creates a cloud folder containing all necessary credentials
* for bootstrapping to the HP cloud.
*
* @param cloudConf
* The configuration used to start the cloud.
* @return
* A path to the newly created cloud folder.
* @throws IOException
*/
public static File createCloudFolder(String userName, String apiKey, ComputeServiceContext context) throws IOException {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
- String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.getEnvironment()
- .get("CLOUDIFY_HOME").toString();
+ String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.cloudifyHome;
File cloudifyEscFolder = new File(cloudifyBuildFolder, cloudConf.cloudifyEscDirRelativePath);
//copy the content of hp configuration files to a new folder
File destFolder = new File(cloudifyEscFolder, cloudConf.cloudName + getTempSuffix());
FileUtils.copyDirectory(new File(cloudifyEscFolder, cloudConf.cloudName), destFolder);
// create new pem file using new credentials.
File pemFolder = new File(destFolder, cloudConf.cloudifyHpUploadDirName);
File newPemFile = createPemFile( context );
FileUtils.copyFile(newPemFile, new File(pemFolder, newPemFile.getName() +".pem"), true);
int colonIndex = userName.indexOf(":");
List<String> cloudProperties = new ArrayList<String>();
cloudProperties.add("tenant=" + '"' + userName.substring(0, colonIndex) + '"');
cloudProperties.add("user=" + '"' + userName.substring(colonIndex + 1, userName.length()) + '"');
cloudProperties.add("apiKey=" + '"' + apiKey + '"');
cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId + '"');
cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId + '"');
//create new props file and init with custom credentials.
File newPropertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName + ".new" );
newPropertiesFile.createNewFile();
FileUtils.writeLines(newPropertiesFile, cloudProperties);
//delete old props file
File propertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName );
if (propertiesFile.exists()) {
propertiesFile.delete();
}
//rename new props file.
if (!newPropertiesFile.renameTo(propertiesFile)){
throw new ServerException("Failed creating custom cloud folder." +
" Failed renaming custom cloud properties file.");
}
return destFolder;
}
/**
* returns the private key used for starting the remote machines.
*
* @param cloudFolder
* The folder used to bootstrap to the cloud.
* @param cloudBootstrapConfig
* The cloud configuration used to bootstrap to the cloud.
* @return
* The private key used for starting the remote machines
* @throws IOException
*/
public static String getCloudPrivateKey(File cloudFolder) throws IOException {
File pemFile = getPemFile(cloudFolder);
if (pemFile == null) {
return null;
}
return FileUtils.readFileToString(pemFile);
}
// creates a new pem file for a given hp cloud account.
private static File createPemFile( ComputeServiceContext context ){
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi api = novaClient.getApi();
KeyPairApi keyPairApi = api.getKeyPairExtensionForZone( cloudConf.zoneName ).get();
KeyPair keyPair = keyPairApi.create( cloudConf.keyPairName + getTempSuffix());
File pemFile = new File(System.getProperty("java.io.tmpdir"), keyPair.getName());
pemFile.createNewFile();
FileUtils.writeStringToFile(pemFile, keyPair.getPrivateKey());
return pemFile;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* Create a security group with all ports open.
*
* @param context The jClouds context.
*/
public static void createCloudifySecurityGroup( ComputeServiceContext context ) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi novaApi = novaClient.getApi();
SecurityGroupApi securityGroupClient = novaApi.getSecurityGroupExtensionForZone(cloudConf.zoneName).get();
//Check if group already exists.
FluentIterable<? extends SecurityGroup> groupsList = securityGroupClient.list();
for (Object group : groupsList) {
if (((SecurityGroup)group).getName().equals(cloudConf.securityGroup)) {
return;
}
}
//Create a new security group with open port range of 80-65535.
Ingress ingress = Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(80).toPort(65535).build();
SecurityGroup securityGroup = securityGroupClient.createWithDescription(cloudConf.securityGroup, "All ports open.");
securityGroupClient.createRuleAllowingCidrBlock(securityGroup.getId(), ingress, "0.0.0.0/0");
}
catch (Exception e) {
throw new RuntimeException("Failed creating security group.", e);
}
}
/**
* Create an HP cloud context.
* @param userName HP cloud username.
* @param apiKey HP cloud API key.
* @return the HP lClouds compute context.
*/
public static ComputeServiceContext createJcloudsContext(String userName,
String apiKey) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
ComputeServiceContext context;
Properties overrides = new Properties();
overrides.put("jclouds.keystone.credential-type", "apiAccessKeyCredentials");
context = ContextBuilder.newBuilder( cloudConf.cloudProvider )
.credentials( userName, apiKey )
.overrides(overrides)
.buildView(ComputeServiceContext.class);
return context;
}
private static String getTempSuffix() {
String currTime = Long.toString(System.currentTimeMillis());
return currTime.substring(currTime.length() - 4);
}
private static File getPemFile(File cloudFolder) {
final CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
File uploadDir = new File(cloudFolder, cloudConf.cloudifyHpUploadDirName);
File[] filesList = uploadDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(cloudConf.keyPairName)
&& name.endsWith( "pem" );
}
});
if ( filesList.length == 0 || filesList.length > 1) {
return null;
}
return filesList[0];
}
}
| true | true |
public static File createCloudFolder(String userName, String apiKey, ComputeServiceContext context) throws IOException {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.getEnvironment()
.get("CLOUDIFY_HOME").toString();
File cloudifyEscFolder = new File(cloudifyBuildFolder, cloudConf.cloudifyEscDirRelativePath);
//copy the content of hp configuration files to a new folder
File destFolder = new File(cloudifyEscFolder, cloudConf.cloudName + getTempSuffix());
FileUtils.copyDirectory(new File(cloudifyEscFolder, cloudConf.cloudName), destFolder);
// create new pem file using new credentials.
File pemFolder = new File(destFolder, cloudConf.cloudifyHpUploadDirName);
File newPemFile = createPemFile( context );
FileUtils.copyFile(newPemFile, new File(pemFolder, newPemFile.getName() +".pem"), true);
int colonIndex = userName.indexOf(":");
List<String> cloudProperties = new ArrayList<String>();
cloudProperties.add("tenant=" + '"' + userName.substring(0, colonIndex) + '"');
cloudProperties.add("user=" + '"' + userName.substring(colonIndex + 1, userName.length()) + '"');
cloudProperties.add("apiKey=" + '"' + apiKey + '"');
cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId + '"');
cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId + '"');
//create new props file and init with custom credentials.
File newPropertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName + ".new" );
newPropertiesFile.createNewFile();
FileUtils.writeLines(newPropertiesFile, cloudProperties);
//delete old props file
File propertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName );
if (propertiesFile.exists()) {
propertiesFile.delete();
}
//rename new props file.
if (!newPropertiesFile.renameTo(propertiesFile)){
throw new ServerException("Failed creating custom cloud folder." +
" Failed renaming custom cloud properties file.");
}
return destFolder;
}
|
public static File createCloudFolder(String userName, String apiKey, ComputeServiceContext context) throws IOException {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.cloudifyHome;
File cloudifyEscFolder = new File(cloudifyBuildFolder, cloudConf.cloudifyEscDirRelativePath);
//copy the content of hp configuration files to a new folder
File destFolder = new File(cloudifyEscFolder, cloudConf.cloudName + getTempSuffix());
FileUtils.copyDirectory(new File(cloudifyEscFolder, cloudConf.cloudName), destFolder);
// create new pem file using new credentials.
File pemFolder = new File(destFolder, cloudConf.cloudifyHpUploadDirName);
File newPemFile = createPemFile( context );
FileUtils.copyFile(newPemFile, new File(pemFolder, newPemFile.getName() +".pem"), true);
int colonIndex = userName.indexOf(":");
List<String> cloudProperties = new ArrayList<String>();
cloudProperties.add("tenant=" + '"' + userName.substring(0, colonIndex) + '"');
cloudProperties.add("user=" + '"' + userName.substring(colonIndex + 1, userName.length()) + '"');
cloudProperties.add("apiKey=" + '"' + apiKey + '"');
cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId + '"');
cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId + '"');
//create new props file and init with custom credentials.
File newPropertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName + ".new" );
newPropertiesFile.createNewFile();
FileUtils.writeLines(newPropertiesFile, cloudProperties);
//delete old props file
File propertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName );
if (propertiesFile.exists()) {
propertiesFile.delete();
}
//rename new props file.
if (!newPropertiesFile.renameTo(propertiesFile)){
throw new ServerException("Failed creating custom cloud folder." +
" Failed renaming custom cloud properties file.");
}
return destFolder;
}
|
diff --git a/src/com/vividsolutions/jump/workbench/ui/cursortool/editing/MoveVertexTool.java b/src/com/vividsolutions/jump/workbench/ui/cursortool/editing/MoveVertexTool.java
index 9fea0312..185981cf 100644
--- a/src/com/vividsolutions/jump/workbench/ui/cursortool/editing/MoveVertexTool.java
+++ b/src/com/vividsolutions/jump/workbench/ui/cursortool/editing/MoveVertexTool.java
@@ -1,216 +1,216 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* Copyright (C) 2003 Vivid Solutions
*
* 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.
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jump.workbench.ui.cursortool.editing;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.JComponent;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateFilter;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.workbench.model.Layer;
import com.vividsolutions.jump.workbench.plugin.EnableCheck;
import com.vividsolutions.jump.workbench.plugin.EnableCheckFactory;
import com.vividsolutions.jump.workbench.ui.EditTransaction;
import com.vividsolutions.jump.workbench.ui.cursortool.DragTool;
import com.vividsolutions.jump.workbench.ui.images.IconLoader;
public class MoveVertexTool extends DragTool {
public final static int TOLERANCE = 5;
private EnableCheckFactory checkFactory;
public MoveVertexTool(EnableCheckFactory checkFactory) {
this.checkFactory = checkFactory;
setColor(new Color(194, 179, 205));
setStrokeWidth(5);
allowSnapping();
}
public Cursor getCursor() {
return createCursor(IconLoader.icon("MoveVertexCursor3.gif").getImage());
}
public Icon getIcon() {
return IconLoader.icon("MoveVertex.gif");
}
protected void gestureFinished() throws Exception {
reportNothingToUndoYet();
//#execute(UndoableCommand) will be called. [Jon Aquino]
moveVertices(getModelSource(), getModelDestination());
}
public void mousePressed(final MouseEvent e) {
try {
if (!check(checkFactory.createAtLeastNLayersMustBeEditableCheck(1))) {
return;
}
if (!check(checkFactory.createAtLeastNItemsMustBeSelectedCheck(1))) {
return;
}
// [mmichaud 2012-12-16] if getClickCount == 2, insert instead of move
if (e.getClickCount() == 2) {
InsertVertexTool ivt = new InsertVertexTool(checkFactory);
ivt.activate(this.getPanel());
ivt.mousePressed(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_PRESSED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.mouseReleased(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_RELEASED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.deactivate();
return;
}
- if (!insertMode && !check(new EnableCheck() {
+ if (!check(new EnableCheck() {
public String check(JComponent component) {
try {
return !nearSelectionHandle(e.getPoint())
? I18N.get("ui.cursortool.MoveVertexTool.no-editable-selection-handles-here")
: null;
} catch (Exception e) {
return e.toString(); }
}
})) {
return;
}
super.mousePressed(e);
} catch (Throwable t) {
getPanel().getContext().handleThrowable(t);
}
}
private boolean nearSelectionHandle(Point2D p) throws NoninvertibleTransformException {
final Envelope buffer = vertexBuffer(getPanel().getViewport().toModelCoordinate(p));
final boolean[] result = new boolean[] { false };
for (Iterator i = getPanel().getSelectionManager().getLayersWithSelectedItems().iterator();
i.hasNext();
) {
Layer layer = (Layer) i.next();
if (!layer.isEditable()) {
continue;
}
for (Iterator j = getPanel().getSelectionManager().getSelectedItems(layer).iterator();
j.hasNext();
) {
Geometry item = (Geometry) j.next();
item.apply(new CoordinateFilter() {
public void filter(Coordinate coord) {
if (buffer.contains(coord)) {
result[0] = true;
}
}
});
}
}
return result[0];
}
private Envelope vertexBuffer(Coordinate c) throws NoninvertibleTransformException {
double tolerance = TOLERANCE / getPanel().getViewport().getScale();
return vertexBuffer(c, tolerance);
}
public void moveVertices(Coordinate initialLocation, Coordinate finalLocation)
throws Exception {
final Envelope oldVertexBuffer = vertexBuffer(initialLocation);
final Coordinate newVertex = finalLocation;
ArrayList transactions = new ArrayList();
for (Iterator i = getPanel().getSelectionManager().getLayersWithSelectedItems().iterator();
i.hasNext();
) {
Layer layerWithSelectedItems = (Layer) i.next();
if (!layerWithSelectedItems.isEditable()) {
continue;
}
transactions.add(createTransaction(layerWithSelectedItems, oldVertexBuffer, newVertex));
}
EditTransaction.commit(transactions);
}
private EditTransaction createTransaction(
Layer layer,
final Envelope oldVertexBuffer,
final Coordinate newVertex) {
return EditTransaction.createTransactionOnSelection(new EditTransaction.SelectionEditor() {
public Geometry edit(Geometry geometryWithSelectedItems, Collection selectedItems) {
for (Iterator j = selectedItems.iterator(); j.hasNext();) {
Geometry item = (Geometry) j.next();
edit(item);
}
return geometryWithSelectedItems;
}
private void edit(Geometry selectedItem) {
selectedItem.apply(new CoordinateFilter() {
public void filter(Coordinate coordinate) {
if (oldVertexBuffer.contains(coordinate)) {
coordinate.x = newVertex.x;
coordinate.y = newVertex.y;
}
}
});
}
}, getPanel(), getPanel().getContext(), getName(), layer, isRollingBackInvalidEdits(), false);
}
protected Shape getShape(Point2D source, Point2D destination) throws Exception {
double radius = 20;
return new Ellipse2D.Double(
destination.getX() - (radius / 2),
destination.getY() - (radius / 2),
radius,
radius);
}
private Envelope vertexBuffer(Coordinate vertex, double tolerance) {
return new Envelope(
vertex.x - tolerance,
vertex.x + tolerance,
vertex.y - tolerance,
vertex.y + tolerance);
}
}
| true | true |
public void mousePressed(final MouseEvent e) {
try {
if (!check(checkFactory.createAtLeastNLayersMustBeEditableCheck(1))) {
return;
}
if (!check(checkFactory.createAtLeastNItemsMustBeSelectedCheck(1))) {
return;
}
// [mmichaud 2012-12-16] if getClickCount == 2, insert instead of move
if (e.getClickCount() == 2) {
InsertVertexTool ivt = new InsertVertexTool(checkFactory);
ivt.activate(this.getPanel());
ivt.mousePressed(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_PRESSED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.mouseReleased(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_RELEASED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.deactivate();
return;
}
if (!insertMode && !check(new EnableCheck() {
public String check(JComponent component) {
try {
return !nearSelectionHandle(e.getPoint())
? I18N.get("ui.cursortool.MoveVertexTool.no-editable-selection-handles-here")
: null;
} catch (Exception e) {
return e.toString(); }
}
})) {
return;
}
super.mousePressed(e);
} catch (Throwable t) {
getPanel().getContext().handleThrowable(t);
}
}
|
public void mousePressed(final MouseEvent e) {
try {
if (!check(checkFactory.createAtLeastNLayersMustBeEditableCheck(1))) {
return;
}
if (!check(checkFactory.createAtLeastNItemsMustBeSelectedCheck(1))) {
return;
}
// [mmichaud 2012-12-16] if getClickCount == 2, insert instead of move
if (e.getClickCount() == 2) {
InsertVertexTool ivt = new InsertVertexTool(checkFactory);
ivt.activate(this.getPanel());
ivt.mousePressed(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_PRESSED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.mouseReleased(new MouseEvent((java.awt.Component)e.getSource(), MouseEvent.MOUSE_RELEASED, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), 1, false));
ivt.deactivate();
return;
}
if (!check(new EnableCheck() {
public String check(JComponent component) {
try {
return !nearSelectionHandle(e.getPoint())
? I18N.get("ui.cursortool.MoveVertexTool.no-editable-selection-handles-here")
: null;
} catch (Exception e) {
return e.toString(); }
}
})) {
return;
}
super.mousePressed(e);
} catch (Throwable t) {
getPanel().getContext().handleThrowable(t);
}
}
|
diff --git a/src/com/csipsimple/wizards/impl/Pbxes.java b/src/com/csipsimple/wizards/impl/Pbxes.java
index d4ecaee3..8e975b67 100644
--- a/src/com/csipsimple/wizards/impl/Pbxes.java
+++ b/src/com/csipsimple/wizards/impl/Pbxes.java
@@ -1,65 +1,65 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.wizards.impl;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.PreferencesWrapper;
public class Pbxes extends SimpleImplementation {
@Override
protected String getDomain() {
return "pbxes.org";
}
@Override
protected String getDefaultName() {
return "Pbxes.org";
}
@Override
public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
- acc.vm_nbr = "*43";
+ acc.vm_nbr = "*97";
return acc;
}
@Override
public void setDefaultParams(PreferencesWrapper prefs) {
super.setDefaultParams(prefs);
// We need to change T1 value because pbxes.org drop registrations when retransmition are made by SIP client
prefs.setPreferenceStringValue(SipConfigManager.TSX_T1_TIMEOUT, "1000");
}
@Override
public boolean needRestart() {
return true;
}
@Override
protected boolean canTcp() {
return false; // Cause there is something really wrong on the pbxes.org server
}
}
| true | true |
public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
acc.vm_nbr = "*43";
return acc;
}
|
public SipProfile buildAccount(SipProfile account) {
SipProfile acc = super.buildAccount(account);
acc.vm_nbr = "*97";
return acc;
}
|
diff --git a/code/br.ufpe.cin.reviewer.ui.rcp/src/br/ufpe/cin/reviewer/ui/rcp/literaturereview/ManualStudyView.java b/code/br.ufpe.cin.reviewer.ui.rcp/src/br/ufpe/cin/reviewer/ui/rcp/literaturereview/ManualStudyView.java
index 6e87b24..a30fe6b 100644
--- a/code/br.ufpe.cin.reviewer.ui.rcp/src/br/ufpe/cin/reviewer/ui/rcp/literaturereview/ManualStudyView.java
+++ b/code/br.ufpe.cin.reviewer.ui.rcp/src/br/ufpe/cin/reviewer/ui/rcp/literaturereview/ManualStudyView.java
@@ -1,162 +1,163 @@
package br.ufpe.cin.reviewer.ui.rcp.literaturereview;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Section;
import br.ufpe.cin.reviewer.ui.rcp.common.BaseView;
import br.ufpe.cin.reviewer.ui.rcp.common.ReviewerViewRegister;
public class ManualStudyView extends BaseView {
public static final String ID = "br.ufpe.cin.reviewer.ui.rcp.literaturereview.ManualStudyView";
private SashForm sash;
private Section section;
private Section sectionInfo;
private Section sectionAbstract;
private Composite sectionComposite;
private Composite infoComposite;
private Composite abstractComposite;
private Composite buttonsComposite;
private Text abstractText;
private Text titleText;
private Text typeText;
private Text sourceText;
private Text authorsText;
private Text institutionsText;
private Text countriesText;
private Text yearText;
private Button cancelButton;
private Button saveButton;
public ManualStudyView() {
ReviewerViewRegister.putView(ID, this);
}
public void createPartControlImpl(Composite parent) {
configureView(parent);
createStudyWidgets(parent);
}
private void configureView(Composite parent) {
super.form.setText(super.form.getText() + " - Manual Study");
form.getBody().setLayout(new GridLayout(2, false));
}
private void createStudyWidgets(Composite parent) {
section = toolkit.createSection(form.getBody(), Section.SHORT_TITLE_BAR);
section.setLayout(new GridLayout(1, false));
section.setText("INFO");
GridData sectionLayout = new GridData(GridData.FILL_BOTH);
sectionLayout.grabExcessVerticalSpace = true;
sectionLayout.horizontalSpan = 1;
section.setLayoutData(sectionLayout);
sectionComposite = toolkit.createComposite(section);
sectionComposite.setLayout(new GridLayout(1, false));
sectionComposite.setLayoutData(new GridData());
sash = new SashForm(sectionComposite,SWT.HORIZONTAL);
sash.setLayout(new GridLayout(2, false));
GridData sashLayout = new GridData(GridData.FILL_BOTH);
sashLayout.horizontalSpan = 1;
sash.setLayoutData(sashLayout);
sash.getMaximizedControl();
sectionInfo = toolkit.createSection(sash, Section.NO_TITLE);
sectionInfo.setLayout(new GridLayout(1, false));
GridData sectionInfoLayout = new GridData(GridData.FILL_VERTICAL);
sectionInfoLayout.grabExcessVerticalSpace = true;
sectionInfoLayout.horizontalSpan = 1;
sectionInfo.setLayoutData(sectionInfoLayout);
sectionAbstract = toolkit.createSection(sash, Section.NO_TITLE);
sectionAbstract.setLayout(new GridLayout(1, false));
GridData sectionAbstractLayout = new GridData(GridData.FILL_VERTICAL);
sectionAbstractLayout.grabExcessVerticalSpace = true;
sectionAbstractLayout.horizontalSpan = 1;
sectionAbstract.setLayoutData(sectionAbstractLayout);
infoComposite = toolkit.createComposite(sectionInfo);
infoComposite.setLayout(new GridLayout(2, false));
infoComposite.setLayoutData(new GridData());
abstractComposite = toolkit.createComposite(sectionAbstract);
abstractComposite.setLayout(new GridLayout(1, false));
abstractComposite.setLayoutData(new GridData());
//Info
Label titleLabel = toolkit.createLabel(infoComposite, "Title: ");
titleText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
titleText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label typeLabel = toolkit.createLabel(infoComposite, "Type: ");
typeText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
typeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label sourceLabel = toolkit.createLabel(infoComposite, "Source: ");
sourceText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
sourceText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label authorsLabel = toolkit.createLabel(infoComposite, "Authors: ");
authorsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
authorsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label institutionsLabel = toolkit.createLabel(infoComposite, "Institutions: ");
institutionsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
institutionsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label countriesLabel = toolkit.createLabel(infoComposite, "Countries: ");
countriesText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
countriesText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label yearLabel = toolkit.createLabel(infoComposite, "Year: ");
yearText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
yearText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
//Abstract
Label abstractLabel = toolkit.createLabel(abstractComposite, "Abstract: ");
abstractText = toolkit.createText(abstractComposite, "", SWT.WRAP | SWT.BORDER);
abstractText.setLayoutData(new GridData(GridData.FILL_BOTH));
//abstractText.addFocusListener(new SearchTextHandler());
//TableWrapData td = new TableWrapData(TableWrapData.FILL_GRAB);
//abstractText.setLayoutData(td);
buttonsComposite = toolkit.createComposite(sectionComposite);
buttonsComposite.setLayout(new GridLayout(2, false));
GridData buttonCompositeLayout = new GridData(GridData.FILL_HORIZONTAL);
buttonsComposite.setLayoutData(buttonCompositeLayout);
cancelButton = toolkit.createButton(buttonsComposite, "Cancel", SWT.PUSH);
GridData cancelButtonLayoutData = new GridData();
cancelButtonLayoutData.horizontalAlignment = SWT.RIGHT;
cancelButtonLayoutData.grabExcessHorizontalSpace = true;
cancelButton.setLayoutData(cancelButtonLayoutData);
saveButton = toolkit.createButton(buttonsComposite, "Save", SWT.PUSH);
GridData saveButtonLayoutData = new GridData();
saveButtonLayoutData.horizontalAlignment = SWT.RIGHT;
- saveButton.setLayoutData(cancelButtonLayoutData);
+ //saveButtonLayoutData.grabExcessHorizontalSpace = true;
+ saveButton.setLayoutData(saveButtonLayoutData);
section.setClient(sectionComposite);
sectionInfo.setClient(infoComposite);
sectionAbstract.setClient(abstractComposite);
}
public void setFocus() {
}
}
| true | true |
private void createStudyWidgets(Composite parent) {
section = toolkit.createSection(form.getBody(), Section.SHORT_TITLE_BAR);
section.setLayout(new GridLayout(1, false));
section.setText("INFO");
GridData sectionLayout = new GridData(GridData.FILL_BOTH);
sectionLayout.grabExcessVerticalSpace = true;
sectionLayout.horizontalSpan = 1;
section.setLayoutData(sectionLayout);
sectionComposite = toolkit.createComposite(section);
sectionComposite.setLayout(new GridLayout(1, false));
sectionComposite.setLayoutData(new GridData());
sash = new SashForm(sectionComposite,SWT.HORIZONTAL);
sash.setLayout(new GridLayout(2, false));
GridData sashLayout = new GridData(GridData.FILL_BOTH);
sashLayout.horizontalSpan = 1;
sash.setLayoutData(sashLayout);
sash.getMaximizedControl();
sectionInfo = toolkit.createSection(sash, Section.NO_TITLE);
sectionInfo.setLayout(new GridLayout(1, false));
GridData sectionInfoLayout = new GridData(GridData.FILL_VERTICAL);
sectionInfoLayout.grabExcessVerticalSpace = true;
sectionInfoLayout.horizontalSpan = 1;
sectionInfo.setLayoutData(sectionInfoLayout);
sectionAbstract = toolkit.createSection(sash, Section.NO_TITLE);
sectionAbstract.setLayout(new GridLayout(1, false));
GridData sectionAbstractLayout = new GridData(GridData.FILL_VERTICAL);
sectionAbstractLayout.grabExcessVerticalSpace = true;
sectionAbstractLayout.horizontalSpan = 1;
sectionAbstract.setLayoutData(sectionAbstractLayout);
infoComposite = toolkit.createComposite(sectionInfo);
infoComposite.setLayout(new GridLayout(2, false));
infoComposite.setLayoutData(new GridData());
abstractComposite = toolkit.createComposite(sectionAbstract);
abstractComposite.setLayout(new GridLayout(1, false));
abstractComposite.setLayoutData(new GridData());
//Info
Label titleLabel = toolkit.createLabel(infoComposite, "Title: ");
titleText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
titleText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label typeLabel = toolkit.createLabel(infoComposite, "Type: ");
typeText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
typeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label sourceLabel = toolkit.createLabel(infoComposite, "Source: ");
sourceText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
sourceText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label authorsLabel = toolkit.createLabel(infoComposite, "Authors: ");
authorsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
authorsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label institutionsLabel = toolkit.createLabel(infoComposite, "Institutions: ");
institutionsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
institutionsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label countriesLabel = toolkit.createLabel(infoComposite, "Countries: ");
countriesText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
countriesText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label yearLabel = toolkit.createLabel(infoComposite, "Year: ");
yearText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
yearText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
//Abstract
Label abstractLabel = toolkit.createLabel(abstractComposite, "Abstract: ");
abstractText = toolkit.createText(abstractComposite, "", SWT.WRAP | SWT.BORDER);
abstractText.setLayoutData(new GridData(GridData.FILL_BOTH));
//abstractText.addFocusListener(new SearchTextHandler());
//TableWrapData td = new TableWrapData(TableWrapData.FILL_GRAB);
//abstractText.setLayoutData(td);
buttonsComposite = toolkit.createComposite(sectionComposite);
buttonsComposite.setLayout(new GridLayout(2, false));
GridData buttonCompositeLayout = new GridData(GridData.FILL_HORIZONTAL);
buttonsComposite.setLayoutData(buttonCompositeLayout);
cancelButton = toolkit.createButton(buttonsComposite, "Cancel", SWT.PUSH);
GridData cancelButtonLayoutData = new GridData();
cancelButtonLayoutData.horizontalAlignment = SWT.RIGHT;
cancelButtonLayoutData.grabExcessHorizontalSpace = true;
cancelButton.setLayoutData(cancelButtonLayoutData);
saveButton = toolkit.createButton(buttonsComposite, "Save", SWT.PUSH);
GridData saveButtonLayoutData = new GridData();
saveButtonLayoutData.horizontalAlignment = SWT.RIGHT;
saveButton.setLayoutData(cancelButtonLayoutData);
section.setClient(sectionComposite);
sectionInfo.setClient(infoComposite);
sectionAbstract.setClient(abstractComposite);
}
|
private void createStudyWidgets(Composite parent) {
section = toolkit.createSection(form.getBody(), Section.SHORT_TITLE_BAR);
section.setLayout(new GridLayout(1, false));
section.setText("INFO");
GridData sectionLayout = new GridData(GridData.FILL_BOTH);
sectionLayout.grabExcessVerticalSpace = true;
sectionLayout.horizontalSpan = 1;
section.setLayoutData(sectionLayout);
sectionComposite = toolkit.createComposite(section);
sectionComposite.setLayout(new GridLayout(1, false));
sectionComposite.setLayoutData(new GridData());
sash = new SashForm(sectionComposite,SWT.HORIZONTAL);
sash.setLayout(new GridLayout(2, false));
GridData sashLayout = new GridData(GridData.FILL_BOTH);
sashLayout.horizontalSpan = 1;
sash.setLayoutData(sashLayout);
sash.getMaximizedControl();
sectionInfo = toolkit.createSection(sash, Section.NO_TITLE);
sectionInfo.setLayout(new GridLayout(1, false));
GridData sectionInfoLayout = new GridData(GridData.FILL_VERTICAL);
sectionInfoLayout.grabExcessVerticalSpace = true;
sectionInfoLayout.horizontalSpan = 1;
sectionInfo.setLayoutData(sectionInfoLayout);
sectionAbstract = toolkit.createSection(sash, Section.NO_TITLE);
sectionAbstract.setLayout(new GridLayout(1, false));
GridData sectionAbstractLayout = new GridData(GridData.FILL_VERTICAL);
sectionAbstractLayout.grabExcessVerticalSpace = true;
sectionAbstractLayout.horizontalSpan = 1;
sectionAbstract.setLayoutData(sectionAbstractLayout);
infoComposite = toolkit.createComposite(sectionInfo);
infoComposite.setLayout(new GridLayout(2, false));
infoComposite.setLayoutData(new GridData());
abstractComposite = toolkit.createComposite(sectionAbstract);
abstractComposite.setLayout(new GridLayout(1, false));
abstractComposite.setLayoutData(new GridData());
//Info
Label titleLabel = toolkit.createLabel(infoComposite, "Title: ");
titleText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
titleText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label typeLabel = toolkit.createLabel(infoComposite, "Type: ");
typeText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
typeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label sourceLabel = toolkit.createLabel(infoComposite, "Source: ");
sourceText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
sourceText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label authorsLabel = toolkit.createLabel(infoComposite, "Authors: ");
authorsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
authorsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label institutionsLabel = toolkit.createLabel(infoComposite, "Institutions: ");
institutionsText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
institutionsText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label countriesLabel = toolkit.createLabel(infoComposite, "Countries: ");
countriesText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
countriesText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label yearLabel = toolkit.createLabel(infoComposite, "Year: ");
yearText = toolkit.createText(infoComposite, "", SWT.WRAP | SWT.BORDER);
yearText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
//Abstract
Label abstractLabel = toolkit.createLabel(abstractComposite, "Abstract: ");
abstractText = toolkit.createText(abstractComposite, "", SWT.WRAP | SWT.BORDER);
abstractText.setLayoutData(new GridData(GridData.FILL_BOTH));
//abstractText.addFocusListener(new SearchTextHandler());
//TableWrapData td = new TableWrapData(TableWrapData.FILL_GRAB);
//abstractText.setLayoutData(td);
buttonsComposite = toolkit.createComposite(sectionComposite);
buttonsComposite.setLayout(new GridLayout(2, false));
GridData buttonCompositeLayout = new GridData(GridData.FILL_HORIZONTAL);
buttonsComposite.setLayoutData(buttonCompositeLayout);
cancelButton = toolkit.createButton(buttonsComposite, "Cancel", SWT.PUSH);
GridData cancelButtonLayoutData = new GridData();
cancelButtonLayoutData.horizontalAlignment = SWT.RIGHT;
cancelButtonLayoutData.grabExcessHorizontalSpace = true;
cancelButton.setLayoutData(cancelButtonLayoutData);
saveButton = toolkit.createButton(buttonsComposite, "Save", SWT.PUSH);
GridData saveButtonLayoutData = new GridData();
saveButtonLayoutData.horizontalAlignment = SWT.RIGHT;
//saveButtonLayoutData.grabExcessHorizontalSpace = true;
saveButton.setLayoutData(saveButtonLayoutData);
section.setClient(sectionComposite);
sectionInfo.setClient(infoComposite);
sectionAbstract.setClient(abstractComposite);
}
|
diff --git a/src/org/newdawn/slick/tiled/TiledMap.java b/src/org/newdawn/slick/tiled/TiledMap.java
index 7a66570..187cc01 100644
--- a/src/org/newdawn/slick/tiled/TiledMap.java
+++ b/src/org/newdawn/slick/tiled/TiledMap.java
@@ -1,677 +1,678 @@
package org.newdawn.slick.tiled;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.newdawn.slick.Color;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.ResourceLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class is intended to parse TilED maps. TilED is a generic tool for tile map editing and can
* be found at:
*
* http://mapeditor.org/
*
* @author kevin
*/
public class TiledMap {
/** The code used to decode Base64 encoding */
private static byte[] baseCodes = new byte[256];
/**
* Static initialiser for the codes created against Base64
*/
static {
for (int i = 0; i < 256; i++)
baseCodes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
baseCodes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
baseCodes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
baseCodes[i] = (byte) (52 + i - '0');
baseCodes['+'] = 62;
baseCodes['/'] = 63;
}
/** The width of the map */
protected int width;
/** The height of the map */
protected int height;
/** The width of the tiles used on the map */
protected int tileWidth;
/** The height of the tiles used on the map */
protected int tileHeight;
/** The location prefix where we can find tileset images */
protected String tilesLocation;
/** The list of tilesets defined in the map */
protected ArrayList tileSets = new ArrayList();
/** The list of layers defined in the map */
protected ArrayList layers = new ArrayList();
/**
* Create a new tile map based on a given TMX file
*
* @param ref The location of the tile map to load
* @throws SlickException Indicates a failure to load the tilemap
*/
public TiledMap(String ref) throws SlickException {
ref = ref.replace('\\','/');
load(ResourceLoader.getResourceAsStream(ref), ref.substring(0,ref.lastIndexOf("/")));
}
/**
* Create a new tile map based on a given TMX file
*
* @param ref The location of the tile map to load
* @param tileSetsLocation The location where we can find the tileset images and other resources
* @throws SlickException Indicates a failure to load the tilemap
*/
public TiledMap(String ref, String tileSetsLocation) throws SlickException {
load(ResourceLoader.getResourceAsStream(ref), tileSetsLocation);
}
/**
* Load a tile map from an arbitary input stream
*
* @param in The input stream to load from
* @throws SlickException Indicates a failure to load the tilemap
*/
public TiledMap(InputStream in) throws SlickException {
load(in, "");
}
/**
* Load a tile map from an arbitary input stream
*
* @param in The input stream to load from
* @param tileSetsLocation The location at which we can find tileset images
* @throws SlickException Indicates a failure to load the tilemap
*/
public TiledMap(InputStream in, String tileSetsLocation) throws SlickException {
load(in, tileSetsLocation);
}
/**
* Get the width of the map
*
* @return The width of the map (in tiles)
*/
public int getWidth() {
return width;
}
/**
* Get the height of the map
*
* @return The height of the map (in tiles)
*/
public int getHeight() {
return height;
}
/**
* Get the height of a single tile
*
* @return The height of a single tile (in pixels)
*/
public int getTileHeight() {
return tileHeight;
}
/**
* Get the width of a single tile
*
* @return The height of a single tile (in pixels)
*/
public int getTileWidth() {
return tileWidth;
}
/**
* Get the global ID of a tile at specified location in the map
*
* @param x
* The x location of the tile
* @param y
* The y location of the tile
* @param layerIndex
* The index of the layer to retireve the tile from
* @return The global ID of the tile
*/
public int getTileId(int x,int y,int layerIndex) {
Layer layer = (Layer) layers.get(layerIndex);
return layer.getTileID(x,y);
}
/**
* Get a propety given to a particular tile. Note that this method will
* not perform well and should not be used as part of the default code
* path in the game loop.
*
* @param tileID The global ID of the tile to retrieve
* @param propertyName The name of the property to retireve
* @param def The default value to return
* @return The value assigned to the property on the tile (or the default value if none is supplied)
*/
public String getTileProperty(int tileID, String propertyName, String def) {
if (tileID == 0) {
return def;
}
TileSet set = findTileSet(tileID);
Properties props = set.getProperties(tileID);
if (props == null) {
return def;
}
return props.getProperty(propertyName, def);
}
/**
* Render the whole tile map at a given location
*
* @param x The x location to render at
* @param y The y location to render at
*/
public void render(int x,int y) {
render(x,y,0,0,width,height,false);
}
/**
* Render a section of the tile map
*
* @param x The x location to render at
* @param y The y location to render at
* @param sx The x tile location to start rendering
* @param sy The y tile location to start rendering
* @param width The width of the section to render (in tiles)
* @param height The height of the secton to render (in tiles)
*/
public void render(int x,int y,int sx,int sy,int width,int height) {
render(x,y,sx,sy,width,height,false);
}
/**
* Render a section of the tile map
*
* @param x The x location to render at
* @param y The y location to render at
* @param sx The x tile location to start rendering
* @param sy The y tile location to start rendering
* @param width The width of the section to render (in tiles)
* @param height The height of the secton to render (in tiles)
* @param lineByLine True if we should render line by line, i.e. giving us a chance
* to render something else between lines (@see {@link #renderedLine(int, int, int)}
*/
public void render(int x,int y,int sx,int sy,int width,int height, boolean lineByLine) {
for (int ty=0;ty<height;ty++) {
for (int i=0;i<layers.size();i++) {
Layer layer = (Layer) layers.get(i);
layer.render(x,y,sx,sy,width, ty,lineByLine);
}
}
}
/**
* Load a TilED map
*
* @param in The input stream from which to load the map
* @param tileSetsLocation The location from which we can retrieve tileset images
* @throws SlickException Indicates a failure to parse the map or find a tileset
*/
private void load(InputStream in, String tileSetsLocation) throws SlickException {
tilesLocation = tileSetsLocation;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
String orient = docElement.getAttribute("orientation");
if (!orient.equals("orthogonal")) {
throw new SlickException("Only orthogonal maps supported, found: "+orient);
}
width = Integer.parseInt(docElement.getAttribute("width"));
height = Integer.parseInt(docElement.getAttribute("height"));
tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth"));
tileHeight = Integer.parseInt(docElement.getAttribute("tileheight"));
TileSet tileSet = null;
TileSet lastSet = null;
NodeList setNodes = docElement.getElementsByTagName("tileset");
for (int i=0;i<setNodes.getLength();i++) {
Element current = (Element) setNodes.item(i);
tileSet = new TileSet(current);
tileSet.index = i;
if (lastSet != null) {
lastSet.setLimit(tileSet.firstGID-1);
}
lastSet = tileSet;
tileSets.add(tileSet);
}
NodeList layerNodes = docElement.getElementsByTagName("layer");
for (int i=0;i<layerNodes.getLength();i++) {
Element current = (Element) layerNodes.item(i);
Layer layer = new Layer(current);
layer.index = i;
layers.add(layer);
}
} catch (Exception e) {
Log.error(e);
throw new SlickException("Failed to parse tilemap", e);
}
}
/**
* Find a tile for a given global tile id
*
* @param gid The global tile id we're looking for
* @return The tileset in which that tile lives
*/
private TileSet findTileSet(int gid) {
for (int i=0;i<tileSets.size();i++) {
TileSet set = (TileSet) tileSets.get(i);
if (set.contains(gid)) {
return set;
}
}
throw new RuntimeException("Global tile id "+gid+" not found");
}
/**
* A holder for tileset information
*
* @author kevin
*/
protected class TileSet {
/** The index of the tile set */
public int index;
/** The name of the tile set */
public String name;
/** The first global tile id in the set */
public int firstGID;
/** The local global tile id in the set */
public int lastGID = Integer.MAX_VALUE;
/** The width of the tiles */
public int tileWidth;
/** The height of the tiles */
public int tileHeight;
/** The image containing the tiles */
public SpriteSheet tiles;
/** The number of tiles across the sprite sheet */
public int tilesAcross;
/** The number of tiles down the sprite sheet */
public int tilesDown;
/** The properties for each tile */
private HashMap props = new HashMap();
/**
* Create a tile set based on an XML definition
*
* @param element The XML describing the tileset
* @throws SlickException Indicates a failure to parse the tileset
*/
public TileSet(Element element) throws SlickException {
name = element.getAttribute("name");
firstGID = Integer.parseInt(element.getAttribute("firstgid"));
String source = element.getAttribute("source");
if ((source != null) && (!source.equals(""))) {
try {
InputStream in = ResourceLoader.getResourceAsStream(tilesLocation + "/" + source);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
element = docElement; //(Element) docElement.getElementsByTagName("tileset").item(0);
} catch (Exception e) {
Log.error(e);
throw new SlickException("Unable to load or parse sourced tileset: "+tilesLocation+"/"+source);
}
}
tileWidth = Integer.parseInt(element.getAttribute("tilewidth"));
tileHeight = Integer.parseInt(element.getAttribute("tileheight"));
int spacing = 0;
- if (element.getAttribute("spacing") != null) {
- spacing = Integer.parseInt(element.getAttribute("spacing"));
+ String sv = element.getAttribute("spacing");
+ if ((sv != null) && (!sv.equals(""))) {
+ spacing = Integer.parseInt(sv);
}
NodeList list = element.getElementsByTagName("image");
Element imageNode = (Element) list.item(0);
String ref = imageNode.getAttribute("source");
Color trans = null;
String t = imageNode.getAttribute("trans");
if ((t != null) && (t.length() > 0)) {
int c = Integer.parseInt(t, 16);
trans = new Color(c);
}
System.out.println(spacing+" : "+trans);
Image image = new Image(tilesLocation+"/"+ref,true,Image.FILTER_NEAREST,trans);
tiles = new SpriteSheet(image , tileWidth, tileHeight, spacing);
tilesAcross = tiles.getWidth() / (tileWidth + spacing);
tilesDown = tiles.getHeight() / (tileHeight + spacing);
NodeList pElements = element.getElementsByTagName("tile");
for (int i=0;i<pElements.getLength();i++) {
Element tileElement = (Element) pElements.item(i);
int id = Integer.parseInt(tileElement.getAttribute("id"));
id += firstGID;
Properties tileProps = new Properties();
Element propsElement = (Element) tileElement.getElementsByTagName("properties").item(0);
NodeList properties = propsElement.getElementsByTagName("property");
for (int p=0;p<properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
tileProps.setProperty(name, value);
}
props.put(new Integer(id), tileProps);
}
}
/**
* Get the properties for a specific tile in this tileset
*
* @param globalID The global ID of the tile whose properties should be retrieved
* @return The properties for the specified tile, or null if no properties are defined
*/
public Properties getProperties(int globalID) {
return (Properties) props.get(new Integer(globalID));
}
/**
* Get the x position of a tile on this sheet
*
* @param id The tileset specific ID (i.e. not the global one)
* @return The index of the tile on the x-axis
*/
public int getTileX(int id) {
return id % tilesAcross;
}
/**
* Get the y position of a tile on this sheet
*
* @param id The tileset specific ID (i.e. not the global one)
* @return The index of the tile on the y-axis
*/
public int getTileY(int id) {
return id / tilesAcross;
}
/**
* Set the limit of the tiles in this set
*
* @param limit The limit of the tiles in this set
*/
public void setLimit(int limit) {
lastGID = limit;
}
/**
* Check if this tileset contains a particular tile
*
* @param gid The global id to seach for
* @return True if the ID is contained in this tileset
*/
public boolean contains(int gid) {
return (gid >= firstGID) && (gid <= lastGID);
}
}
/**
* A layer of tiles on the map
*
* @author kevin
*/
protected class Layer {
/** The index of this layer */
public int index;
/** The name of this layer - read from the XML */
public String name;
/** The tile data representing this data, index 0 = tileset, index 1 = tile id */
public int[][][] data;
/** The width of this layer */
public int width;
/** The height of this layer */
public int height;
/**
* Create a new layer based on the XML definition
*
* @param element The XML element describing the layer
* @throws SlickException Indicates a failure to parse the XML layer
*/
public Layer(Element element) throws SlickException {
name = element.getAttribute("name");
width = Integer.parseInt(element.getAttribute("width"));
height = Integer.parseInt(element.getAttribute("height"));
data = new int[width][height][3];
Element dataNode = (Element) element.getElementsByTagName("data").item(0);
String encoding = dataNode.getAttribute("encoding");
String compression = dataNode.getAttribute("compression");
if (encoding.equals("base64") && compression.equals("gzip")) {
try {
Node cdata = dataNode.getFirstChild();
char[] enc = cdata.getNodeValue().trim().toCharArray();
byte[] dec = decodeBase64(enc);
GZIPInputStream is = new GZIPInputStream(new ByteArrayInputStream(dec));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int tileId = 0;
tileId |= is.read();
tileId |= is.read() << 8;
tileId |= is.read() << 16;
tileId |= is.read() << 24;
if (tileId == 0) {
data[x][y][0] = -1;
data[x][y][1] = 0;
data[x][y][2] = 0;
} else {
TileSet set = findTileSet(tileId);
data[x][y][0] = set.index;
data[x][y][1] = tileId - set.firstGID;
data[x][y][2] = tileId;
}
}
}
} catch (IOException e) {
Log.error(e);
throw new SlickException("Unable to decode base 64 block");
}
} else {
throw new SlickException("Unsupport tiled map type: "+encoding+","+compression+" (only gzip base64 supported)");
}
}
/**
* Get the gloal ID of the tile at the specified location in
* this layer
*
* @param x The x coorindate of the tile
* @param y The y coorindate of the tile
* @return The global ID of the tile
*/
public int getTileID(int x, int y) {
return data[x][y][2];
}
/**
* Set the global tile ID at a specified location
*
* @param x The x location to set
* @param y The y location to set
* @param tile The tile value to set
*/
public void setTileID(int x, int y, int tile) {
if (tile == 0) {
data[x][y][0] = -1;
data[x][y][1] = 0;
data[x][y][2] = 0;
} else {
TileSet set = findTileSet(tile);
data[x][y][0] = set.index;
data[x][y][1] = tile - set.firstGID;
data[x][y][2] = tile;
}
}
/**
* Render a section of this layer
*
* @param x
* The x location to render at
* @param y
* The y location to render at
* @param sx
* The x tile location to start rendering
* @param sy
* The y tile location to start rendering
* @param width The number of tiles across to render
* @param ty The line of tiles to render
* @param lineByLine
* True if we should render line by line, i.e. giving us a
* chance to render something else between lines
*/
public void render(int x,int y,int sx,int sy,int width, int ty,boolean lineByLine) {
for (int tileset=0;tileset<tileSets.size();tileset++) {
TileSet set = null;
for (int tx=0;tx<width;tx++) {
if ((sx+tx < 0) || (sy+ty < 0)) {
continue;
}
if ((sx+tx >= this.width) || (sy+ty >= this.height)) {
continue;
}
if (data[sx+tx][sy+ty][0] == tileset) {
if (set == null) {
set = (TileSet) tileSets.get(tileset);
set.tiles.startUse();
}
int sheetX = set.getTileX(data[sx+tx][sy+ty][1]);
int sheetY = set.getTileY(data[sx+tx][sy+ty][1]);
set.tiles.renderInUse(x+(tx*set.tileWidth), y+(ty*set.tileHeight), sheetX, sheetY);
}
}
if (lineByLine) {
if (set != null) {
set.tiles.endUse();
set = null;
}
renderedLine(ty, ty+sy, index);
}
if (set != null) {
set.tiles.endUse();
}
}
}
}
/**
* Overrideable to allow other sprites to be rendered between lines of the
* map
*
* @param visualY The visual Y coordinate, i.e. 0->height
* @param mapY The map Y coordinate, i.e. y->y+height
* @param layer The layer being rendered
*/
protected void renderedLine(int visualY, int mapY,int layer) {
}
/**
* Decode a Base64 string as encoded by TilED
*
* @param data The string of character to decode
* @return The byte array represented by character encoding
*/
private byte[] decodeBase64(char[] data) {
int temp = data.length;
for (int ix = 0; ix < data.length; ix++) {
if ((data[ix] > 255) || baseCodes[data[ix]] < 0) {
--temp;
}
}
int len = (temp / 4) * 3;
if ((temp % 4) == 3)
len += 2;
if ((temp % 4) == 2)
len += 1;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = (data[ix] > 255) ? -1 : baseCodes[data[ix]];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length) {
throw new RuntimeException(
"Data length appears to be wrong (wrote " + index
+ " should be " + out.length + ")");
}
return out;
}
}
| true | true |
public TileSet(Element element) throws SlickException {
name = element.getAttribute("name");
firstGID = Integer.parseInt(element.getAttribute("firstgid"));
String source = element.getAttribute("source");
if ((source != null) && (!source.equals(""))) {
try {
InputStream in = ResourceLoader.getResourceAsStream(tilesLocation + "/" + source);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
element = docElement; //(Element) docElement.getElementsByTagName("tileset").item(0);
} catch (Exception e) {
Log.error(e);
throw new SlickException("Unable to load or parse sourced tileset: "+tilesLocation+"/"+source);
}
}
tileWidth = Integer.parseInt(element.getAttribute("tilewidth"));
tileHeight = Integer.parseInt(element.getAttribute("tileheight"));
int spacing = 0;
if (element.getAttribute("spacing") != null) {
spacing = Integer.parseInt(element.getAttribute("spacing"));
}
NodeList list = element.getElementsByTagName("image");
Element imageNode = (Element) list.item(0);
String ref = imageNode.getAttribute("source");
Color trans = null;
String t = imageNode.getAttribute("trans");
if ((t != null) && (t.length() > 0)) {
int c = Integer.parseInt(t, 16);
trans = new Color(c);
}
System.out.println(spacing+" : "+trans);
Image image = new Image(tilesLocation+"/"+ref,true,Image.FILTER_NEAREST,trans);
tiles = new SpriteSheet(image , tileWidth, tileHeight, spacing);
tilesAcross = tiles.getWidth() / (tileWidth + spacing);
tilesDown = tiles.getHeight() / (tileHeight + spacing);
NodeList pElements = element.getElementsByTagName("tile");
for (int i=0;i<pElements.getLength();i++) {
Element tileElement = (Element) pElements.item(i);
int id = Integer.parseInt(tileElement.getAttribute("id"));
id += firstGID;
Properties tileProps = new Properties();
Element propsElement = (Element) tileElement.getElementsByTagName("properties").item(0);
NodeList properties = propsElement.getElementsByTagName("property");
for (int p=0;p<properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
tileProps.setProperty(name, value);
}
props.put(new Integer(id), tileProps);
}
}
|
public TileSet(Element element) throws SlickException {
name = element.getAttribute("name");
firstGID = Integer.parseInt(element.getAttribute("firstgid"));
String source = element.getAttribute("source");
if ((source != null) && (!source.equals(""))) {
try {
InputStream in = ResourceLoader.getResourceAsStream(tilesLocation + "/" + source);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
element = docElement; //(Element) docElement.getElementsByTagName("tileset").item(0);
} catch (Exception e) {
Log.error(e);
throw new SlickException("Unable to load or parse sourced tileset: "+tilesLocation+"/"+source);
}
}
tileWidth = Integer.parseInt(element.getAttribute("tilewidth"));
tileHeight = Integer.parseInt(element.getAttribute("tileheight"));
int spacing = 0;
String sv = element.getAttribute("spacing");
if ((sv != null) && (!sv.equals(""))) {
spacing = Integer.parseInt(sv);
}
NodeList list = element.getElementsByTagName("image");
Element imageNode = (Element) list.item(0);
String ref = imageNode.getAttribute("source");
Color trans = null;
String t = imageNode.getAttribute("trans");
if ((t != null) && (t.length() > 0)) {
int c = Integer.parseInt(t, 16);
trans = new Color(c);
}
System.out.println(spacing+" : "+trans);
Image image = new Image(tilesLocation+"/"+ref,true,Image.FILTER_NEAREST,trans);
tiles = new SpriteSheet(image , tileWidth, tileHeight, spacing);
tilesAcross = tiles.getWidth() / (tileWidth + spacing);
tilesDown = tiles.getHeight() / (tileHeight + spacing);
NodeList pElements = element.getElementsByTagName("tile");
for (int i=0;i<pElements.getLength();i++) {
Element tileElement = (Element) pElements.item(i);
int id = Integer.parseInt(tileElement.getAttribute("id"));
id += firstGID;
Properties tileProps = new Properties();
Element propsElement = (Element) tileElement.getElementsByTagName("properties").item(0);
NodeList properties = propsElement.getElementsByTagName("property");
for (int p=0;p<properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
tileProps.setProperty(name, value);
}
props.put(new Integer(id), tileProps);
}
}
|
diff --git a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMDebugger.java b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMDebugger.java
index c7fcefa02..4a96a3c6c 100644
--- a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMDebugger.java
+++ b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/sdm/core/SDMDebugger.java
@@ -1,527 +1,521 @@
/*******************************************************************************
* Copyright (c) 2005 The Regents of the University of California.
* This material was produced under U.S. Government contract W-7405-ENG-36
* for Los Alamos National Laboratory, which is operated by the University
* of California for the U.S. Department of Energy. The U.S. Government has
* rights to use, reproduce, and distribute this software. NEITHER THE
* GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, 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
*
* LA-CC 04-115
*******************************************************************************/
package org.eclipse.ptp.debug.sdm.core;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.Random;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
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.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ptp.core.IPTPLaunchConfigurationConstants;
import org.eclipse.ptp.core.PTPCorePlugin;
import org.eclipse.ptp.core.Preferences;
import org.eclipse.ptp.core.elements.IPJob;
import org.eclipse.ptp.core.elements.IPNode;
import org.eclipse.ptp.core.elements.IPResourceManager;
import org.eclipse.ptp.debug.core.IPDebugger;
import org.eclipse.ptp.debug.core.launch.IPLaunch;
import org.eclipse.ptp.debug.core.pdi.IPDIDebugger;
import org.eclipse.ptp.debug.core.pdi.IPDISession;
import org.eclipse.ptp.debug.core.pdi.PDIException;
import org.eclipse.ptp.debug.core.pdi.Session;
import org.eclipse.ptp.debug.core.pdi.event.IPDIEventFactory;
import org.eclipse.ptp.debug.core.pdi.manager.IPDIManagerFactory;
import org.eclipse.ptp.debug.core.pdi.model.IPDIModelFactory;
import org.eclipse.ptp.debug.core.pdi.request.IPDIRequestFactory;
import org.eclipse.ptp.debug.sdm.core.SDMRunner.SDMMasterState;
import org.eclipse.ptp.debug.sdm.core.messages.Messages;
import org.eclipse.ptp.debug.sdm.core.pdi.PDIDebugger;
import org.eclipse.ptp.debug.sdm.core.utils.DebugUtil;
import org.eclipse.ptp.remote.core.IRemoteConnection;
import org.eclipse.ptp.remote.core.IRemoteConnectionManager;
import org.eclipse.ptp.remote.core.IRemoteFileManager;
import org.eclipse.ptp.remote.core.IRemoteServices;
import org.eclipse.ptp.remote.core.PTPRemoteCorePlugin;
import org.eclipse.ptp.rmsystem.IResourceManager;
import org.eclipse.ptp.rmsystem.IResourceManagerComponentConfiguration;
import org.eclipse.ptp.utils.core.BitSetIterable;
/**
* Main SDM debugger specified using the parallelDebugger extension point.
*
* A new instance of this class is created for each debug session.
*
* @author clement
*
*/
public class SDMDebugger implements IPDebugger {
private final IPDIDebugger fPdiDebugger = new PDIDebugger();
private final IPDIModelFactory fModelFactory = new SDMModelFactory();
private final IPDIManagerFactory fManagerFactory = new SDMManagerFactory();
private final IPDIEventFactory fEventFactory = new SDMEventFactory();
private final IPDIRequestFactory fRequestFactory = new SDMRequestFactory();
private IFileStore fRoutingFileStore = null;
private SDMRunner fSdmRunner = null;
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.debug.core.IPDebugger#cleanup(org.eclipse.ptp.debug.core
* .launch.IPLaunch)
*/
public synchronized void cleanup(IPLaunch launch) {
if (fSdmRunner != null) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMDebugger_8);
new Thread(Messages.SDMDebugger_7) {
@Override
public void run() {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMDebugger_9);
synchronized (this) {
// Give the runner a chance to finish itself
try {
wait(5000);
} catch (InterruptedException e) {
// Ignore
}
if (fSdmRunner.getSdmState() == SDMMasterState.RUNNING) {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMDebugger_11);
fSdmRunner.cancel();
try {
fSdmRunner.join();
} catch (InterruptedException e) {
// Not much we can do at this point
}
} else {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMDebugger_13);
}
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING_MORE, Messages.SDMDebugger_14);
fSdmRunner = null;
}
}
}.start();
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.debug.core.IPDebugger#createDebugSession(long,
* org.eclipse.ptp.debug.core.launch.IPLaunch,
* org.eclipse.core.runtime.IPath)
*/
/**
* @since 5.0
*/
public synchronized IPDISession createDebugSession(long timeout, final IPLaunch launch, IProgressMonitor monitor)
throws CoreException {
int jobSize = getJobSize(launch);
IPDISession session;
try {
session = new Session(fManagerFactory, fRequestFactory, fEventFactory, fModelFactory, launch.getLaunchConfiguration(),
timeout, fPdiDebugger, launch.getJobId(), jobSize);
} catch (PDIException e) {
throw newCoreException(e.getLocalizedMessage());
}
if (fRoutingFileStore != null) {
/*
* Writing the routing file actually starts the SDM servers.
*/
writeRoutingFile(launch, monitor);
/*
* Delay starting the master SDM (aka SDM client), to wait until SDM
* servers have started and until the sessions are listening on the
* debugger socket.
*/
fSdmRunner.setJob(launch.getJobId());
fSdmRunner.schedule();
}
return session;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.debug.core.IPDebugger#initialize(org.eclipse.debug.core
* .ILaunchConfiguration, org.eclipse.core.runtime.IProgressMonitor)
*/
/**
* @since 5.0
*/
public synchronized void initialize(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, 30);
try {
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_CLIENT_ENABLED)) {
int level = Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUG_CLIENT_LEVEL);
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING) {
DebugUtil.SDM_MASTER_TRACING = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) {
DebugUtil.SDM_MASTER_TRACING_MORE = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) == SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) {
DebugUtil.SDM_MASTER_OUTPUT_TRACING = true;
}
}
ILaunchConfigurationWorkingCopy workingCopy = configuration.getWorkingCopy();
List<String> dbgArgs = new ArrayList<String>();
try {
fPdiDebugger.initialize(configuration, dbgArgs, progress.newChild(10));
} catch (PDIException e) {
throw newCoreException(e.getLocalizedMessage());
}
String localAddress = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_HOST, "localhost"); //$NON-NLS-1$
dbgArgs.add("--host=" + localAddress); //$NON-NLS-1$
String debuggerBackend = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_TYPE);
debuggerBackend = configuration
.getAttribute(SDMLaunchConfigurationConstants.ATTR_DEBUGGER_SDM_BACKEND, debuggerBackend);
dbgArgs.add("--debugger=" + debuggerBackend); //$NON-NLS-1$
String dbgPath = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_PATH);
if (dbgPath.length() > 0) {
dbgArgs.add("--debugger_path=" + dbgPath); //$NON-NLS-1$
}
String dbgExtraArgs = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_ARGS);
if (dbgExtraArgs.length() > 0) {
dbgArgs.addAll(Arrays.asList(dbgExtraArgs.split(" "))); //$NON-NLS-1$
}
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_ENABLED)) {
dbgArgs.add("--debug=" + Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_LEVEL)); //$NON-NLS-1$
}
- String args = workingCopy.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, (String) null);
- if (args == null) {
- args = stringify(dbgArgs);
- } else {
- args += " " + stringify(dbgArgs); //$NON-NLS-1$
- }
- workingCopy.setAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, args);
+ workingCopy.setAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, stringify(dbgArgs));
String dbgExePath = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_EXECUTABLE_PATH, ""); //$NON-NLS-1$
verifyResource(dbgExePath, configuration, progress.newChild(10));
/*
* Prepare the Master SDM controller thread if required by the RM.
*/
IResourceManager rm = getResourceManager(configuration);
if (rm.getConfiguration().needsDebuggerLaunchHelp()) {
/*
* Store information to create routing file later.
*/
prepareRoutingFile(configuration, progress.newChild(10));
/*
* Create SDM master thread
*/
fSdmRunner = new SDMRunner(rm);
/*
* Set SDM command line.
*/
List<String> sdmCommand = new ArrayList<String>();
sdmCommand.add(dbgExePath);
sdmCommand.add("--master"); //$NON-NLS-1$
sdmCommand.addAll(dbgArgs);
fSdmRunner.setCommand(sdmCommand);
fSdmRunner.setWorkDir(getWorkingDirectory(configuration));
}
workingCopy.doSave();
} finally {
if (monitor != null) {
monitor.done();
}
}
}
/**
* Work out the expected number of processes in the job. If it hasn't been
* specified, assume one.
*
* @param launch
* job that was launched
* @return number of processes
*/
private int getJobSize(IPLaunch launch) {
int nprocs = 1;
IResourceManager rmc = launch.getResourceManager();
if (rmc != null) {
IPResourceManager rm = (IPResourceManager) rmc.getAdapter(IPResourceManager.class);
if (rm != null) {
IPJob job = rm.getJobById(launch.getJobId());
if (job != null) {
nprocs = job.getProcessJobRanks().cardinality();
if (nprocs == 0) {
nprocs = 1;
}
}
}
}
return nprocs;
}
/**
* Helper method to locate the resource manager used by the launch
* configuration
*
* @param configuration
* launch configuration
* @return resource manager or null if none specified
* @throws CoreException
*/
private IResourceManager getResourceManager(ILaunchConfiguration configuration) throws CoreException {
String rmUniqueName = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_RESOURCE_MANAGER_UNIQUENAME,
(String) null);
IResourceManager rm = PTPCorePlugin.getDefault().getModelManager().getResourceManagerFromUniqueName(rmUniqueName);
if (rm.getState().equals(IResourceManager.STARTED_STATE)) {
return rm;
}
return null;
}
private String getWorkingDirectory(ILaunchConfiguration configuration) throws CoreException {
String wd = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_WORKING_DIR, (String) null);
if (wd == null || wd.equals("")) { //$NON-NLS-1$
wd = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_WORKING_DIR, (String) null);
if (wd == null || wd.equals("")) { //$NON-NLS-1$
String execPath = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_EXECUTABLE_PATH, (String) null);
if (execPath == null) {
throw newCoreException(Messages.SDMDebugger_NoWorkingDir);
}
wd = new Path(execPath).removeLastSegments(1).toString();
}
}
return wd;
}
/**
* Create a CoreException that can be thrown
*
* @param exception
* @return CoreException
*/
private CoreException newCoreException(String message) {
Status status = new Status(IStatus.ERROR, SDMDebugCorePlugin.getUniqueIdentifier(), message, null);
return new CoreException(status);
}
/**
* Initialize the routing file for this debug session.
*
* @param configuration
* launch configuration
* @param monitor
* progress monitor
* @throws CoreException
*/
private void prepareRoutingFile(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, 10);
try {
IPath routingFilePath = new Path(getWorkingDirectory(configuration));
routingFilePath = routingFilePath.append("routing_file"); //$NON-NLS-1$
IResourceManager rm = getResourceManager(configuration);
IResourceManagerComponentConfiguration conf = rm.getControlConfiguration();
IRemoteServices remoteServices = PTPRemoteCorePlugin.getDefault().getRemoteServices(conf.getRemoteServicesId(),
progress.newChild(5));
if (progress.isCanceled()) {
throw newCoreException(Messages.SDMDebugger_Operation_canceled_by_user);
}
IRemoteConnectionManager rconnMgr = remoteServices.getConnectionManager();
IRemoteConnection rconn = rconnMgr.getConnection(conf.getConnectionName());
IRemoteFileManager remoteFileManager = remoteServices.getFileManager(rconn);
fRoutingFileStore = remoteFileManager.getResource(routingFilePath.toString());
if (fRoutingFileStore.fetchInfo(EFS.NONE, progress.newChild(3)).exists()) {
try {
fRoutingFileStore.delete(0, progress.newChild(2));
} catch (CoreException e) {
throw newCoreException(e.getLocalizedMessage());
}
fRoutingFileStore.fetchInfo();
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
/**
* Create a string containing each element of the list separated by a space
*
* @param list
* @return
*/
private String stringify(List<String> list) {
String result = ""; //$NON-NLS-1$
for (int i = 0; i < list.size(); i++) {
if (i > 0) {
result += " "; //$NON-NLS-1$
}
result += list.get(i);
}
return result;
}
/**
* Verify that the resource "path" actually exists. This just checks that
* the path references something real.
*
* @param path
* path to verify
* @param configuration
* launch configuration
* @return IPath representing the path
* @throws CoreException
* is thrown if the verification fails or the user cancels the
* progress monitor
* @since 5.0
*/
private IPath verifyResource(String path, ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
IResourceManager rm = getResourceManager(configuration);
if (rm == null) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.PLUGIN_ID, Messages.SDMDebugger_4));
}
IResourceManagerComponentConfiguration conf = rm.getControlConfiguration();
IRemoteServices remoteServices = PTPRemoteCorePlugin.getDefault().getRemoteServices(conf.getRemoteServicesId(), monitor);
if (monitor.isCanceled()) {
throw newCoreException(Messages.SDMDebugger_Operation_canceled_by_user);
}
if (remoteServices == null) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.PLUGIN_ID, Messages.SDMDebugger_0));
}
IRemoteConnectionManager connMgr = remoteServices.getConnectionManager();
if (connMgr == null) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.PLUGIN_ID, Messages.SDMDebugger_1));
}
IRemoteConnection conn = connMgr.getConnection(conf.getConnectionName());
if (conn == null) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.PLUGIN_ID, Messages.SDMDebugger_2));
}
IRemoteFileManager fileManager = remoteServices.getFileManager(conn);
if (fileManager == null) {
throw new CoreException(new Status(IStatus.ERROR, SDMDebugCorePlugin.PLUGIN_ID, Messages.SDMDebugger_3));
}
if (!fileManager.getResource(path).fetchInfo().exists()) {
throw new CoreException(new Status(IStatus.INFO, SDMDebugCorePlugin.PLUGIN_ID, NLS.bind(Messages.SDMDebugger_5,
new Object[] { path })));
}
return new Path(path);
}
/**
* Generate the routing file once the debugger has launched.
*
* NOTE: This currently assumes a shared filesystem that all debugger
* processes have access to. The plan is to replace this with a routing
* distribution operation in the debugger.
*
* @param launch
* launch configuration
* @throws CoreException
*/
private void writeRoutingFile(IPLaunch launch, IProgressMonitor monitor) throws CoreException {
DebugUtil.trace(DebugUtil.SDM_MASTER_TRACING, Messages.SDMDebugger_12);
SubMonitor progress = SubMonitor.convert(monitor, 100);
try {
OutputStream os = null;
try {
os = fRoutingFileStore.openOutputStream(0, progress.newChild(10));
} catch (CoreException e) {
throw newCoreException(e.getLocalizedMessage());
}
progress.subTask(Messages.SDMDebugger_6);
PrintWriter pw = new PrintWriter(os);
final String jobId = launch.getJobId();
final IPResourceManager rm = (IPResourceManager) launch.getResourceManager().getAdapter(IPResourceManager.class);
if (rm != null) {
final IPJob pJob = rm.getJobById(jobId);
BitSet processJobRanks = pJob.getProcessJobRanks();
pw.format("%d\n", processJobRanks.cardinality()); //$NON-NLS-1$
int base = 50000;
int range = 10000;
Random random = new Random();
for (Integer processIndex : new BitSetIterable(processJobRanks)) {
String nodeId = pJob.getProcessNodeId(processIndex);
if (nodeId == null) {
progress.subTask(Messages.SDMDebugger_10);
while (nodeId == null && !progress.isCanceled()) {
try {
wait(1000);
} catch (InterruptedException e) {
// ignore
}
nodeId = pJob.getProcessNodeId(processIndex);
progress.worked(1);
}
}
if (progress.isCanceled()) {
throw newCoreException(Messages.SDMDebugger_Operation_canceled_by_user);
}
IPNode node = rm.getNodeById(nodeId);
if (node == null) {
throw newCoreException(Messages.SDMDebugger_15);
}
String nodeName = node.getName();
int portNumber = base + random.nextInt(range);
pw.format("%s %s %d\n", processIndex, nodeName, portNumber); //$NON-NLS-1$
progress.setWorkRemaining(60);
progress.worked(10);
}
pw.close();
}
try {
os.close();
} catch (IOException e) {
throw newCoreException(e.getLocalizedMessage());
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
}
| true | true |
public synchronized void initialize(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, 30);
try {
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_CLIENT_ENABLED)) {
int level = Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUG_CLIENT_LEVEL);
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING) {
DebugUtil.SDM_MASTER_TRACING = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) {
DebugUtil.SDM_MASTER_TRACING_MORE = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) == SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) {
DebugUtil.SDM_MASTER_OUTPUT_TRACING = true;
}
}
ILaunchConfigurationWorkingCopy workingCopy = configuration.getWorkingCopy();
List<String> dbgArgs = new ArrayList<String>();
try {
fPdiDebugger.initialize(configuration, dbgArgs, progress.newChild(10));
} catch (PDIException e) {
throw newCoreException(e.getLocalizedMessage());
}
String localAddress = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_HOST, "localhost"); //$NON-NLS-1$
dbgArgs.add("--host=" + localAddress); //$NON-NLS-1$
String debuggerBackend = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_TYPE);
debuggerBackend = configuration
.getAttribute(SDMLaunchConfigurationConstants.ATTR_DEBUGGER_SDM_BACKEND, debuggerBackend);
dbgArgs.add("--debugger=" + debuggerBackend); //$NON-NLS-1$
String dbgPath = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_PATH);
if (dbgPath.length() > 0) {
dbgArgs.add("--debugger_path=" + dbgPath); //$NON-NLS-1$
}
String dbgExtraArgs = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_ARGS);
if (dbgExtraArgs.length() > 0) {
dbgArgs.addAll(Arrays.asList(dbgExtraArgs.split(" "))); //$NON-NLS-1$
}
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_ENABLED)) {
dbgArgs.add("--debug=" + Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_LEVEL)); //$NON-NLS-1$
}
String args = workingCopy.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, (String) null);
if (args == null) {
args = stringify(dbgArgs);
} else {
args += " " + stringify(dbgArgs); //$NON-NLS-1$
}
workingCopy.setAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, args);
String dbgExePath = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_EXECUTABLE_PATH, ""); //$NON-NLS-1$
verifyResource(dbgExePath, configuration, progress.newChild(10));
/*
* Prepare the Master SDM controller thread if required by the RM.
*/
IResourceManager rm = getResourceManager(configuration);
if (rm.getConfiguration().needsDebuggerLaunchHelp()) {
/*
* Store information to create routing file later.
*/
prepareRoutingFile(configuration, progress.newChild(10));
/*
* Create SDM master thread
*/
fSdmRunner = new SDMRunner(rm);
/*
* Set SDM command line.
*/
List<String> sdmCommand = new ArrayList<String>();
sdmCommand.add(dbgExePath);
sdmCommand.add("--master"); //$NON-NLS-1$
sdmCommand.addAll(dbgArgs);
fSdmRunner.setCommand(sdmCommand);
fSdmRunner.setWorkDir(getWorkingDirectory(configuration));
}
workingCopy.doSave();
} finally {
if (monitor != null) {
monitor.done();
}
}
}
|
public synchronized void initialize(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, 30);
try {
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_CLIENT_ENABLED)) {
int level = Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUG_CLIENT_LEVEL);
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING) {
DebugUtil.SDM_MASTER_TRACING = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) == SDMPreferenceConstants.DEBUG_CLIENT_TRACING_MORE) {
DebugUtil.SDM_MASTER_TRACING_MORE = true;
}
if ((level & SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) == SDMPreferenceConstants.DEBUG_CLIENT_OUTPUT) {
DebugUtil.SDM_MASTER_OUTPUT_TRACING = true;
}
}
ILaunchConfigurationWorkingCopy workingCopy = configuration.getWorkingCopy();
List<String> dbgArgs = new ArrayList<String>();
try {
fPdiDebugger.initialize(configuration, dbgArgs, progress.newChild(10));
} catch (PDIException e) {
throw newCoreException(e.getLocalizedMessage());
}
String localAddress = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_HOST, "localhost"); //$NON-NLS-1$
dbgArgs.add("--host=" + localAddress); //$NON-NLS-1$
String debuggerBackend = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_TYPE);
debuggerBackend = configuration
.getAttribute(SDMLaunchConfigurationConstants.ATTR_DEBUGGER_SDM_BACKEND, debuggerBackend);
dbgArgs.add("--debugger=" + debuggerBackend); //$NON-NLS-1$
String dbgPath = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_BACKEND_PATH);
if (dbgPath.length() > 0) {
dbgArgs.add("--debugger_path=" + dbgPath); //$NON-NLS-1$
}
String dbgExtraArgs = Preferences.getString(SDMDebugCorePlugin.getUniqueIdentifier(),
SDMPreferenceConstants.SDM_DEBUGGER_ARGS);
if (dbgExtraArgs.length() > 0) {
dbgArgs.addAll(Arrays.asList(dbgExtraArgs.split(" "))); //$NON-NLS-1$
}
if (Preferences.getBoolean(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_ENABLED)) {
dbgArgs.add("--debug=" + Preferences.getInt(SDMDebugCorePlugin.getUniqueIdentifier(), SDMPreferenceConstants.SDM_DEBUG_LEVEL)); //$NON-NLS-1$
}
workingCopy.setAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_ARGS, stringify(dbgArgs));
String dbgExePath = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_DEBUGGER_EXECUTABLE_PATH, ""); //$NON-NLS-1$
verifyResource(dbgExePath, configuration, progress.newChild(10));
/*
* Prepare the Master SDM controller thread if required by the RM.
*/
IResourceManager rm = getResourceManager(configuration);
if (rm.getConfiguration().needsDebuggerLaunchHelp()) {
/*
* Store information to create routing file later.
*/
prepareRoutingFile(configuration, progress.newChild(10));
/*
* Create SDM master thread
*/
fSdmRunner = new SDMRunner(rm);
/*
* Set SDM command line.
*/
List<String> sdmCommand = new ArrayList<String>();
sdmCommand.add(dbgExePath);
sdmCommand.add("--master"); //$NON-NLS-1$
sdmCommand.addAll(dbgArgs);
fSdmRunner.setCommand(sdmCommand);
fSdmRunner.setWorkDir(getWorkingDirectory(configuration));
}
workingCopy.doSave();
} finally {
if (monitor != null) {
monitor.done();
}
}
}
|
diff --git a/core/src/com/clarkparsia/openrdf/query/util/DescribeVisitor.java b/core/src/com/clarkparsia/openrdf/query/util/DescribeVisitor.java
index 1e085fc..6db1cc5 100644
--- a/core/src/com/clarkparsia/openrdf/query/util/DescribeVisitor.java
+++ b/core/src/com/clarkparsia/openrdf/query/util/DescribeVisitor.java
@@ -1,131 +1,131 @@
/*
* Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.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 com.clarkparsia.openrdf.query.util;
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.algebra.ProjectionElem;
import org.openrdf.query.algebra.SameTerm;
import org.openrdf.query.algebra.ValueConstant;
import org.openrdf.query.algebra.Join;
import org.openrdf.query.algebra.Union;
import org.openrdf.query.algebra.LeftJoin;
import org.openrdf.query.algebra.Filter;
import org.openrdf.query.algebra.SingletonSet;
import org.openrdf.query.algebra.BinaryTupleOperator;
import org.openrdf.query.algebra.StatementPattern;
import org.openrdf.query.algebra.Var;
import org.openrdf.query.algebra.Projection;
import org.openrdf.query.algebra.MultiProjection;
import org.openrdf.query.algebra.Extension;
import org.openrdf.query.algebra.ProjectionElemList;
import org.openrdf.query.algebra.ExtensionElem;
import org.openrdf.query.algebra.Or;
import org.openrdf.query.algebra.And;
import org.openrdf.query.algebra.BinaryValueOperator;
import org.openrdf.query.algebra.UnaryValueOperator;
import org.openrdf.query.algebra.FunctionCall;
import org.openrdf.query.algebra.ValueExpr;
import org.openrdf.query.algebra.Bound;
import org.openrdf.query.algebra.evaluation.impl.ConstantOptimizer;
import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
import org.openrdf.query.parser.ParsedQuery;
import org.openrdf.query.parser.sparql.SPARQLParser;
import org.openrdf.query.impl.MapBindingSet;
import org.openrdf.query.impl.DatasetImpl;
import org.openrdf.query.impl.EmptyBindingSet;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.model.Value;
import org.openrdf.model.Literal;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.impl.BooleanLiteralImpl;
import java.util.Set;
import java.util.HashSet;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
/**
* <p>TupleExprVisitor implementation that will scan a query model and see if it looks like the model for a describe
* query. If so, {@link #isDescribe} will return true after {@link #checkQuery checking} the query. Also,
* {@link #getValues} will return a list of all the concrete values to be described in the query. This will <b>not</b>
* return any variables to be described.</p>
*
* <p>The main aim of this class is to provide some functionality to scan a query model to find out if its a describe,
* and what is being described so you could "compile" the describe query into a query language that does not support
* describe natively, such as SeRQL. Once you know what is being described, you could then simulate the support with
* a construct query.</p>
*
* @author Michael Grove
* @since 0.2.4
* @version 0.3
*/
public final class DescribeVisitor extends QueryModelVisitorBase<Exception> {
/**
* Whether or not the query model represents a describe query
*/
private boolean mIsDescribe = false;
public void reset() {
mIsDescribe = false;
}
/**
* Check to see if this query is a describe query or not
* @param theExpr the query model to check
* @return this visitor
* @throws Exception if there is an error while checking
*/
public boolean checkQuery(TupleExpr theExpr) throws Exception {
reset();
theExpr.visit(this);
return isDescribe();
}
/**
* Check to see if this query is a describe query or not
* @param theQuery the query to check
* @return this visitor
* @throws Exception if there is an error while checking
*/
public boolean checkQuery(ParsedQuery theQuery) throws Exception {
return checkQuery(theQuery.getTupleExpr());
}
/**
* Whether or not the query model represents a describe query
* @return true if it is a describe query, false otherwise
*/
public boolean isDescribe() {
return mIsDescribe;
}
/**
* @inheritDoc
*/
@Override
public void meet(final ProjectionElem theProjectionElem) throws Exception {
- if (theProjectionElem.getSourceName().startsWith("descr") && (theProjectionElem.getTargetName().equals("subject")
- || theProjectionElem.getTargetName().equals("predicate")
- || theProjectionElem.getTargetName().equals("object"))) {
+ if ((theProjectionElem.getSourceName().startsWith("-descr") || theProjectionElem.getSourceName().startsWith("descr_")) && (theProjectionElem.getTargetName().equals("subject")
+ || theProjectionElem.getTargetName().equals("predicate")
+ || theProjectionElem.getTargetName().equals("object"))) {
mIsDescribe = true;
}
}
}
| true | true |
public void meet(final ProjectionElem theProjectionElem) throws Exception {
if (theProjectionElem.getSourceName().startsWith("descr") && (theProjectionElem.getTargetName().equals("subject")
|| theProjectionElem.getTargetName().equals("predicate")
|| theProjectionElem.getTargetName().equals("object"))) {
mIsDescribe = true;
}
}
|
public void meet(final ProjectionElem theProjectionElem) throws Exception {
if ((theProjectionElem.getSourceName().startsWith("-descr") || theProjectionElem.getSourceName().startsWith("descr_")) && (theProjectionElem.getTargetName().equals("subject")
|| theProjectionElem.getTargetName().equals("predicate")
|| theProjectionElem.getTargetName().equals("object"))) {
mIsDescribe = true;
}
}
|
diff --git a/sigfood-android/src/de/sigfood/MealFragment.java b/sigfood-android/src/de/sigfood/MealFragment.java
index 9bca716..1a9c7ce 100644
--- a/sigfood-android/src/de/sigfood/MealFragment.java
+++ b/sigfood-android/src/de/sigfood/MealFragment.java
@@ -1,253 +1,263 @@
package de.sigfood;
// ----------------------------------------
// MealFragment
// Displays details on meals or side dishes
// Handles ratings
// Links to CommentFragment
// ----------------------------------------
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
public class MealFragment extends Fragment {
public static SigfoodActivity act;
public static View v;
public static MensaEssen backMeal;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (v == null) {
act = (SigfoodActivity) getActivity();
v = inflater.inflate(R.layout.meal, null);
} else {
((ViewGroup) v.getParent()).removeView(v);
}
return v;
}
public static Bundle createBundle(String title) {
Bundle bundle = new Bundle();
bundle.putString("title", title);
return bundle;
}
SigfoodApi sigfood;
public static void setMeal(final MensaEssen e) {
backMeal = null;
CommentFragment.setComments(e);
LinearLayout essen = (LinearLayout)v.findViewById(R.id.mealList);
View scroller = (View)v.findViewById(R.id.meal);
scroller.setVisibility(View.VISIBLE);
View note = (View)v.findViewById(R.id.mealNote);
note.setVisibility(View.GONE);
TextView name = (TextView)essen.findViewById(R.id.mealTitle);
name.setText(Html.fromHtml(e.hauptgericht.bezeichnung));
TextView linie = (TextView)essen.findViewById(R.id.mealLine);
if (e.linie.equalsIgnoreCase("0")) linie.setText("Beilage");
else linie.setText("Linie " + e.linie);
- ImageButton img = (ImageButton)essen.findViewById(R.id.mealPicture);
+ final ImageButton img = (ImageButton)essen.findViewById(R.id.mealPicture);
+ Button btn = (Button)essen.findViewById(R.id.mealUpload);
ProgressBar load = (ProgressBar)essen.findViewById(R.id.mealPictureLoading);
img.setVisibility(View.GONE);
+ btn.setVisibility(View.GONE);
load.setVisibility(View.VISIBLE);
if (e.hauptgericht.bilder.size() > 0) {
Random rng = new Random();
int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size()));
URL myFileUrl =null;
try {
myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=480");
} catch (MalformedURLException e1) {
Bitmap bmImg = BitmapFactory.decodeResource(act.getResources(), R.drawable.picdownloadfailed);
img.setImageBitmap(bmImg);
}
PictureThread pt = new PictureThread(myFileUrl,img,load,act);
pt.start();
} else {
img.setVisibility(View.GONE);
+ btn.setVisibility(View.VISIBLE);
load.setVisibility(View.GONE);
}
img.setTag(e);
img.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.takePhoto(v2);
}
+ });
+ btn.setTag(e);
+ btn.setOnClickListener(new Button.OnClickListener() {
+ public void onClick(View v2)
+ {
+ act.takePhoto(img);
+ }
});
final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.mealRating);
final RatingBar barr = (RatingBar)essen.findViewById(R.id.mealRatingChoose);
final Button ratingbutton = (Button)essen.findViewById(R.id.mealRatingButton);
bar1.setMax(50);
bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt*10));
((TextView) essen.findViewById(R.id.mealRatingText)).setText(e.hauptgericht.bewertung.schnitt+", "+e.hauptgericht.bewertung.anzahl+" Bewertungen ("+e.hauptgericht.bewertung.stddev+" Abw.)");
final Date sfspd = e.datumskopie;
Calendar today = Calendar.getInstance();
int hour = today.get(Calendar.HOUR);
int am = today.get(Calendar.AM_PM);
today.set(Calendar.HOUR,0); today.set(Calendar.AM_PM,Calendar.AM); today.set(Calendar.MINUTE,0); today.set(Calendar.SECOND,0); today.set(Calendar.MILLISECOND,0);
Calendar twoago = (Calendar) today.clone();
twoago.roll(Calendar.DATE, -2);
Calendar start = Calendar.getInstance();
start.set(sfspd.getYear()+1900, sfspd.getMonth(), sfspd.getDate(), 0, 0, 0); start.set(Calendar.MILLISECOND,0);
if (start.before(twoago)) {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung nicht mehr möglich");
} else if (((hour>=11 || am==Calendar.PM) && start.equals(today)) || start.before(today)) {
ratingbutton.setEnabled(true);
ratingbutton.setText("Bewerten");
ratingbutton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
if(barr.getVisibility()==View.GONE) {
bar1.setVisibility(View.GONE);
barr.setVisibility(View.VISIBLE);
ratingbutton.setText("Bewertung abgeben");
} else {
bar1.setVisibility(View.VISIBLE);
barr.setVisibility(View.GONE);
ratingbutton.setEnabled(false);
Log.d("Rating",(int)barr.getRating()+"");
if (bewerten(e.hauptgericht, (int)barr.getRating(), sfspd))
ratingbutton.setText("Bewertet mit "+(int)barr.getRating()+" Stern"+(((int)barr.getRating()==1) ? "" : "en"));
}
}
});
} else {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung noch nicht möglich");
}
LinearLayout sidedishes = (LinearLayout)v.findViewById(R.id.mealSidedish);
sidedishes.removeAllViews();
if (e.beilagen.size()>0) {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.VISIBLE);
sidedishes.setVisibility(View.VISIBLE);
for (final Hauptgericht beilage : e.beilagen) {
LinearLayout sidedish = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.mealsidedish, null);
TextView titel = (TextView)sidedish.findViewById(R.id.sidedishTitle);
titel.setText(Html.fromHtml(beilage.bezeichnung));
final RatingBar bar2 = (RatingBar)sidedish.findViewById(R.id.sidedishRating);
bar2.setMax(50);
bar2.setProgress((int) (beilage.bewertung.schnitt * 10));
sidedish.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
MensaEssen bei = new MensaEssen();
bei.linie = "0";
bei.hauptgericht = beilage;
bei.datumskopie = e.datumskopie;
setMeal(bei);
backMeal = e;
}
});
sidedishes.addView(sidedish);
}
} else {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.GONE);
sidedishes.setVisibility(View.GONE);
}
LinearLayout comments = (LinearLayout)essen.findViewById(R.id.mealComment);
comments.removeAllViews();
if (e.hauptgericht.kommentare.size()>0) {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.VISIBLE);
comments.setVisibility(View.VISIBLE);
LinearLayout comment = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.comment, null);
TextView text = (TextView)comment.findViewById(R.id.commentText);
text.setText(Html.fromHtml(e.hauptgericht.kommentare.get(0)));
comments.addView(comment);
} else {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.GONE);
comments.setVisibility(View.GONE);
}
Button commentbtn = (Button)v.findViewById(R.id.mealCommentButton);
commentbtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.getSupportActionBar().setSelectedNavigationItem(2);
}
});
}
static boolean bewerten(Hauptgericht e, int stars, Date tag) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.sigfood.de/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("do", "1"));
nameValuePairs.add(new BasicNameValuePair("datum",
String.format("%tY-%tm-%td", tag, tag, tag)));
nameValuePairs.add(new BasicNameValuePair("gerid", Integer.toString(e.id)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine() == null) {
return false;
} else {
if (response.getStatusLine().getStatusCode() != 200) {
return false;
}
}
} catch (ClientProtocolException e1) {
return false;
} catch (IOException e1) {
return false;
}
return true;
}
}
| false | true |
public static void setMeal(final MensaEssen e) {
backMeal = null;
CommentFragment.setComments(e);
LinearLayout essen = (LinearLayout)v.findViewById(R.id.mealList);
View scroller = (View)v.findViewById(R.id.meal);
scroller.setVisibility(View.VISIBLE);
View note = (View)v.findViewById(R.id.mealNote);
note.setVisibility(View.GONE);
TextView name = (TextView)essen.findViewById(R.id.mealTitle);
name.setText(Html.fromHtml(e.hauptgericht.bezeichnung));
TextView linie = (TextView)essen.findViewById(R.id.mealLine);
if (e.linie.equalsIgnoreCase("0")) linie.setText("Beilage");
else linie.setText("Linie " + e.linie);
ImageButton img = (ImageButton)essen.findViewById(R.id.mealPicture);
ProgressBar load = (ProgressBar)essen.findViewById(R.id.mealPictureLoading);
img.setVisibility(View.GONE);
load.setVisibility(View.VISIBLE);
if (e.hauptgericht.bilder.size() > 0) {
Random rng = new Random();
int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size()));
URL myFileUrl =null;
try {
myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=480");
} catch (MalformedURLException e1) {
Bitmap bmImg = BitmapFactory.decodeResource(act.getResources(), R.drawable.picdownloadfailed);
img.setImageBitmap(bmImg);
}
PictureThread pt = new PictureThread(myFileUrl,img,load,act);
pt.start();
} else {
img.setVisibility(View.GONE);
load.setVisibility(View.GONE);
}
img.setTag(e);
img.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.takePhoto(v2);
}
});
final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.mealRating);
final RatingBar barr = (RatingBar)essen.findViewById(R.id.mealRatingChoose);
final Button ratingbutton = (Button)essen.findViewById(R.id.mealRatingButton);
bar1.setMax(50);
bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt*10));
((TextView) essen.findViewById(R.id.mealRatingText)).setText(e.hauptgericht.bewertung.schnitt+", "+e.hauptgericht.bewertung.anzahl+" Bewertungen ("+e.hauptgericht.bewertung.stddev+" Abw.)");
final Date sfspd = e.datumskopie;
Calendar today = Calendar.getInstance();
int hour = today.get(Calendar.HOUR);
int am = today.get(Calendar.AM_PM);
today.set(Calendar.HOUR,0); today.set(Calendar.AM_PM,Calendar.AM); today.set(Calendar.MINUTE,0); today.set(Calendar.SECOND,0); today.set(Calendar.MILLISECOND,0);
Calendar twoago = (Calendar) today.clone();
twoago.roll(Calendar.DATE, -2);
Calendar start = Calendar.getInstance();
start.set(sfspd.getYear()+1900, sfspd.getMonth(), sfspd.getDate(), 0, 0, 0); start.set(Calendar.MILLISECOND,0);
if (start.before(twoago)) {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung nicht mehr möglich");
} else if (((hour>=11 || am==Calendar.PM) && start.equals(today)) || start.before(today)) {
ratingbutton.setEnabled(true);
ratingbutton.setText("Bewerten");
ratingbutton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
if(barr.getVisibility()==View.GONE) {
bar1.setVisibility(View.GONE);
barr.setVisibility(View.VISIBLE);
ratingbutton.setText("Bewertung abgeben");
} else {
bar1.setVisibility(View.VISIBLE);
barr.setVisibility(View.GONE);
ratingbutton.setEnabled(false);
Log.d("Rating",(int)barr.getRating()+"");
if (bewerten(e.hauptgericht, (int)barr.getRating(), sfspd))
ratingbutton.setText("Bewertet mit "+(int)barr.getRating()+" Stern"+(((int)barr.getRating()==1) ? "" : "en"));
}
}
});
} else {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung noch nicht möglich");
}
LinearLayout sidedishes = (LinearLayout)v.findViewById(R.id.mealSidedish);
sidedishes.removeAllViews();
if (e.beilagen.size()>0) {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.VISIBLE);
sidedishes.setVisibility(View.VISIBLE);
for (final Hauptgericht beilage : e.beilagen) {
LinearLayout sidedish = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.mealsidedish, null);
TextView titel = (TextView)sidedish.findViewById(R.id.sidedishTitle);
titel.setText(Html.fromHtml(beilage.bezeichnung));
final RatingBar bar2 = (RatingBar)sidedish.findViewById(R.id.sidedishRating);
bar2.setMax(50);
bar2.setProgress((int) (beilage.bewertung.schnitt * 10));
sidedish.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
MensaEssen bei = new MensaEssen();
bei.linie = "0";
bei.hauptgericht = beilage;
bei.datumskopie = e.datumskopie;
setMeal(bei);
backMeal = e;
}
});
sidedishes.addView(sidedish);
}
} else {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.GONE);
sidedishes.setVisibility(View.GONE);
}
LinearLayout comments = (LinearLayout)essen.findViewById(R.id.mealComment);
comments.removeAllViews();
if (e.hauptgericht.kommentare.size()>0) {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.VISIBLE);
comments.setVisibility(View.VISIBLE);
LinearLayout comment = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.comment, null);
TextView text = (TextView)comment.findViewById(R.id.commentText);
text.setText(Html.fromHtml(e.hauptgericht.kommentare.get(0)));
comments.addView(comment);
} else {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.GONE);
comments.setVisibility(View.GONE);
}
Button commentbtn = (Button)v.findViewById(R.id.mealCommentButton);
commentbtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.getSupportActionBar().setSelectedNavigationItem(2);
}
});
}
|
public static void setMeal(final MensaEssen e) {
backMeal = null;
CommentFragment.setComments(e);
LinearLayout essen = (LinearLayout)v.findViewById(R.id.mealList);
View scroller = (View)v.findViewById(R.id.meal);
scroller.setVisibility(View.VISIBLE);
View note = (View)v.findViewById(R.id.mealNote);
note.setVisibility(View.GONE);
TextView name = (TextView)essen.findViewById(R.id.mealTitle);
name.setText(Html.fromHtml(e.hauptgericht.bezeichnung));
TextView linie = (TextView)essen.findViewById(R.id.mealLine);
if (e.linie.equalsIgnoreCase("0")) linie.setText("Beilage");
else linie.setText("Linie " + e.linie);
final ImageButton img = (ImageButton)essen.findViewById(R.id.mealPicture);
Button btn = (Button)essen.findViewById(R.id.mealUpload);
ProgressBar load = (ProgressBar)essen.findViewById(R.id.mealPictureLoading);
img.setVisibility(View.GONE);
btn.setVisibility(View.GONE);
load.setVisibility(View.VISIBLE);
if (e.hauptgericht.bilder.size() > 0) {
Random rng = new Random();
int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size()));
URL myFileUrl =null;
try {
myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=480");
} catch (MalformedURLException e1) {
Bitmap bmImg = BitmapFactory.decodeResource(act.getResources(), R.drawable.picdownloadfailed);
img.setImageBitmap(bmImg);
}
PictureThread pt = new PictureThread(myFileUrl,img,load,act);
pt.start();
} else {
img.setVisibility(View.GONE);
btn.setVisibility(View.VISIBLE);
load.setVisibility(View.GONE);
}
img.setTag(e);
img.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.takePhoto(v2);
}
});
btn.setTag(e);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.takePhoto(img);
}
});
final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.mealRating);
final RatingBar barr = (RatingBar)essen.findViewById(R.id.mealRatingChoose);
final Button ratingbutton = (Button)essen.findViewById(R.id.mealRatingButton);
bar1.setMax(50);
bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt*10));
((TextView) essen.findViewById(R.id.mealRatingText)).setText(e.hauptgericht.bewertung.schnitt+", "+e.hauptgericht.bewertung.anzahl+" Bewertungen ("+e.hauptgericht.bewertung.stddev+" Abw.)");
final Date sfspd = e.datumskopie;
Calendar today = Calendar.getInstance();
int hour = today.get(Calendar.HOUR);
int am = today.get(Calendar.AM_PM);
today.set(Calendar.HOUR,0); today.set(Calendar.AM_PM,Calendar.AM); today.set(Calendar.MINUTE,0); today.set(Calendar.SECOND,0); today.set(Calendar.MILLISECOND,0);
Calendar twoago = (Calendar) today.clone();
twoago.roll(Calendar.DATE, -2);
Calendar start = Calendar.getInstance();
start.set(sfspd.getYear()+1900, sfspd.getMonth(), sfspd.getDate(), 0, 0, 0); start.set(Calendar.MILLISECOND,0);
if (start.before(twoago)) {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung nicht mehr möglich");
} else if (((hour>=11 || am==Calendar.PM) && start.equals(today)) || start.before(today)) {
ratingbutton.setEnabled(true);
ratingbutton.setText("Bewerten");
ratingbutton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
if(barr.getVisibility()==View.GONE) {
bar1.setVisibility(View.GONE);
barr.setVisibility(View.VISIBLE);
ratingbutton.setText("Bewertung abgeben");
} else {
bar1.setVisibility(View.VISIBLE);
barr.setVisibility(View.GONE);
ratingbutton.setEnabled(false);
Log.d("Rating",(int)barr.getRating()+"");
if (bewerten(e.hauptgericht, (int)barr.getRating(), sfspd))
ratingbutton.setText("Bewertet mit "+(int)barr.getRating()+" Stern"+(((int)barr.getRating()==1) ? "" : "en"));
}
}
});
} else {
ratingbutton.setEnabled(false);
ratingbutton.setText("Bewertung noch nicht möglich");
}
LinearLayout sidedishes = (LinearLayout)v.findViewById(R.id.mealSidedish);
sidedishes.removeAllViews();
if (e.beilagen.size()>0) {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.VISIBLE);
sidedishes.setVisibility(View.VISIBLE);
for (final Hauptgericht beilage : e.beilagen) {
LinearLayout sidedish = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.mealsidedish, null);
TextView titel = (TextView)sidedish.findViewById(R.id.sidedishTitle);
titel.setText(Html.fromHtml(beilage.bezeichnung));
final RatingBar bar2 = (RatingBar)sidedish.findViewById(R.id.sidedishRating);
bar2.setMax(50);
bar2.setProgress((int) (beilage.bewertung.schnitt * 10));
sidedish.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
MensaEssen bei = new MensaEssen();
bei.linie = "0";
bei.hauptgericht = beilage;
bei.datumskopie = e.datumskopie;
setMeal(bei);
backMeal = e;
}
});
sidedishes.addView(sidedish);
}
} else {
v.findViewById(R.id.mealSidedishLabel).setVisibility(View.GONE);
sidedishes.setVisibility(View.GONE);
}
LinearLayout comments = (LinearLayout)essen.findViewById(R.id.mealComment);
comments.removeAllViews();
if (e.hauptgericht.kommentare.size()>0) {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.VISIBLE);
comments.setVisibility(View.VISIBLE);
LinearLayout comment = (LinearLayout)LayoutInflater.from(act.getBaseContext()).inflate(R.layout.comment, null);
TextView text = (TextView)comment.findViewById(R.id.commentText);
text.setText(Html.fromHtml(e.hauptgericht.kommentare.get(0)));
comments.addView(comment);
} else {
v.findViewById(R.id.mealCommentLabel).setVisibility(View.GONE);
comments.setVisibility(View.GONE);
}
Button commentbtn = (Button)v.findViewById(R.id.mealCommentButton);
commentbtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v2)
{
act.getSupportActionBar().setSelectedNavigationItem(2);
}
});
}
|
diff --git a/enunciate/core/src/java/net/sf/enunciate/apt/EnunciateAnnotationProcessorFactory.java b/enunciate/core/src/java/net/sf/enunciate/apt/EnunciateAnnotationProcessorFactory.java
index b45589e3..2c34b9cf 100755
--- a/enunciate/core/src/java/net/sf/enunciate/apt/EnunciateAnnotationProcessorFactory.java
+++ b/enunciate/core/src/java/net/sf/enunciate/apt/EnunciateAnnotationProcessorFactory.java
@@ -1,77 +1,78 @@
package net.sf.enunciate.apt;
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import net.sf.enunciate.EnunciateException;
import net.sf.enunciate.main.Enunciate;
import net.sf.enunciate.config.EnunciateConfiguration;
import net.sf.jelly.apt.ProcessorFactory;
import net.sf.jelly.apt.freemarker.FreemarkerProcessorFactory;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
/**
* @author Ryan Heaton
*/
public class EnunciateAnnotationProcessorFactory extends ProcessorFactory {
/**
* Option to specify the config file to use.
*/
public static final String CONFIG_OPTION = "-Aconfig";
/**
* Option to specify the namespace of the enunciate transform library.
*/
public static final String FM_LIBRARY_NS_OPTION = "-AEnunciateFreemarkerLibraryNS";
/**
* Option to specify a verbose output.
*/
public static final String VERBOSE_OPTION = "-Averbose";
private static final Collection<String> SUPPORTED_OPTIONS = Collections.unmodifiableCollection(Arrays.asList(CONFIG_OPTION,
FM_LIBRARY_NS_OPTION,
FreemarkerProcessorFactory.FM_LIBRARY_NS_OPTION,
VERBOSE_OPTION));
private static final Collection<String> SUPPORTED_TYPES = Collections.unmodifiableCollection(Arrays.asList("*"));
private final EnunciateAnnotationProcessor processor;
public EnunciateAnnotationProcessorFactory(Enunciate enunciate) throws EnunciateException {
this.processor = new EnunciateAnnotationProcessor(enunciate);
+ this.round = 0; //todo: fix this in APT-Jelly. What it really needs to do is listen to the rounds.
}
//Inherited.
public Collection<String> supportedOptions() {
return SUPPORTED_OPTIONS;
}
//Inherited.
public Collection<String> supportedAnnotationTypes() {
return SUPPORTED_TYPES;
}
@Override
protected AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> annotations) {
return processor;
}
//no-op.
protected AnnotationProcessor newProcessor(URL url) {
return null;
}
/**
* Throws any errors that occurred during processing.
*/
public void throwAnyErrors() throws EnunciateException, IOException {
processor.throwAnyErrors();
}
}
| true | true |
public EnunciateAnnotationProcessorFactory(Enunciate enunciate) throws EnunciateException {
this.processor = new EnunciateAnnotationProcessor(enunciate);
}
|
public EnunciateAnnotationProcessorFactory(Enunciate enunciate) throws EnunciateException {
this.processor = new EnunciateAnnotationProcessor(enunciate);
this.round = 0; //todo: fix this in APT-Jelly. What it really needs to do is listen to the rounds.
}
|
diff --git a/core/src/main/java/hudson/model/Hudson.java b/core/src/main/java/hudson/model/Hudson.java
index 42031ca31..d2bfbc4b5 100644
--- a/core/src/main/java/hudson/model/Hudson.java
+++ b/core/src/main/java/hudson/model/Hudson.java
@@ -1,2545 +1,2550 @@
package hudson.model;
import com.thoughtworks.xstream.XStream;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.StructuredForm;
import hudson.TcpSlaveAgentListener;
import hudson.Util;
import static hudson.Util.fixEmpty;
import hudson.XmlFile;
import hudson.ProxyConfiguration;
import hudson.slaves.RetentionStrategy;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.JobListener;
import hudson.model.listeners.JobListener.JobListenerAdapter;
import hudson.model.listeners.SCMListener;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.CVSSCM;
import hudson.scm.RepositoryBrowser;
import hudson.scm.RepositoryBrowsers;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMS;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.SecurityRealm.SecurityComponents;
import hudson.security.TokenBasedRememberMeServices2;
import hudson.security.AccessControlled;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Builder;
import hudson.tasks.DynamicLabeler;
import hudson.tasks.LabelFinder;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.triggers.Triggers;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.FormFieldValidator;
import hudson.util.HudsonIsLoading;
import hudson.util.MultipartFormDataParser;
import hudson.util.RemotingDiagnostics;
import hudson.util.TextFile;
import hudson.util.XStream2;
import hudson.widgets.Widget;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import static org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.Proxy;
import java.security.SecureRandom;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
public final class Hudson extends View implements ItemGroup<TopLevelItem>, Node, StaplerProxy {
private transient final Queue queue = new Queue();
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
private transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Hudson.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Hudson.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm;
/**
* Message displayed in the top page.
*/
private String systemMessage;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Hudson theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
/**
* Widgets on Hudson.
*/
private transient final List<Widget> widgets = new CopyOnWriteArrayList<Widget>();
private transient volatile DependencyGraph dependencyGraph;
/**
* Set of installed cluster nodes.
*
* We use this field with copy-on-write semantics.
* This field has mutable list (to keep the serialization look clean),
* but it shall never be modified. Only new completely populated slave
* list can be set here.
*/
private volatile List<Slave> slaves;
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* {@link ListView}s.
*/
private List<ListView> views; // can't initialize it eagerly for backward compatibility
private transient MyView myView = new MyView(this);
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
/**
* List of registered {@link JobListener}s.
*/
private transient final CopyOnWriteList<ItemListener> itemListeners = new CopyOnWriteList<ItemListener>();
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* All labels known to Hudson. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
private transient Set<Label> labelSet;
private transient volatile Set<Label> dynamicLabels = null;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
public static Hudson getInstance() {
return theInstance;
}
/**
* Secrete key generated once and used for a long time, beyond
* container start/stop.
*/
private final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
public Hudson(File root, ServletContext context) throws IOException {
this.root = root;
this.servletContext = context;
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(Hudson.getInstance().getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to load proxy configuration", e);
}
// load plugins.
pluginManager = new PluginManager(context);
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
else
tcpSlaveAgentListener = null;
// if we are loading old data that doesn't have this field
if(slaves==null) slaves = new ArrayList<Slave>();
// work around to have MavenModule register itself until we either move it to a plugin
// or make it a part of the core.
Items.LIST.hashCode();
load();
updateComputerList();
getQueue().load();
for (ItemListener l : itemListeners)
l.onLoaded();
// create TokenBasedRememberMeServices, which depends on the availability of the secret key
TokenBasedRememberMeServices2 rms = new TokenBasedRememberMeServices2();
rms.setUserDetailsService(HudsonFilter.USER_DETAILS_SERVICE_PROXY);
rms.setKey(getSecretKey());
rms.setParameter("remember_me"); // this is the form field name in login.jelly
HudsonFilter.REMEMBER_ME_SERVICES_PROXY.setDelegate(rms);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* Obtains the {@link Proxy} instance to talk to other HTTP servers.
*/
public Proxy createProxy() {
if(proxy==null)
return Proxy.NO_PROXY;
else
return proxy.createProxy();
}
/**
* If you are calling this on Hudson something is wrong.
*
* @deprecated
*/
@Deprecated
public String getNodeName() {
return "";
}
public String getNodeDescription() {
return "the master Hudson node";
}
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*/
public String getSecretKey() {
return secretKey;
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCMS.SCMS);
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowsers.LIST);
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, BuildStep.BUILDERS);
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrappers.WRAPPERS);
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, BuildStep.PUBLISHERS);
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor)findDescriptor(shortClassName, Triggers.TRIGGERS);
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, Jobs.PROPERTIES);
return (JobPropertyDescriptor) d;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.LIST);
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
/**
* Adds a new {@link JobListener}.
*
* @deprecated
* Use {@code getJobListners().add(l)} instead.
*/
public void addListener(JobListener l) {
itemListeners.add(new JobListenerAdapter(l));
}
/**
* Deletes an existing {@link JobListener}.
*
* @deprecated
* Use {@code getJobListners().remove(l)} instead.
*/
public boolean removeListener(JobListener l ) {
return itemListeners.remove(new JobListenerAdapter(l));
}
/**
* Gets all the installed {@link ItemListener}s.
*/
public CopyOnWriteList<ItemListener> getJobListeners() {
return itemListeners;
}
/**
* Gets all the installed {@link SCMListener}s.
*/
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the hpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym to {@link #getNodeDescription()}.
*/
public String getSystemMessage() {
return systemMessage;
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener);
}
/**
* Updates {@link #computers} by using {@link #getSlaves()}.
*
* <p>
* This method tries to reuse existing {@link Computer} objects
* so that we won't upset {@link Executor}s running in it.
*/
private void updateComputerList() throws IOException {
synchronized(computers) {// this synchronization is still necessary so that no two update happens concurrently
Map<String,Computer> byName = new HashMap<String,Computer>();
for (Computer c : computers.values()) {
if(c.getNode()==null)
continue; // this computer is gone
byName.put(c.getNode().getNodeName(),c);
}
Set<Computer> old = new HashSet<Computer>(computers.values());
Set<Computer> used = new HashSet<Computer>();
updateComputer(this, byName, used);
for (Slave s : getSlaves())
updateComputer(s, byName, used);
// find out what computers are removed, and kill off all executors.
// when all executors exit, it will be removed from the computers map.
// so don't remove too quickly
old.removeAll(used);
for (Computer c : old) {
c.kill();
}
}
getQueue().scheduleMaintenance();
}
private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used) {
Computer c;
c = byNameMap.get(n.getNodeName());
if (c!=null) {
c.setNode(n); // reuse
} else {
if(n.getNumExecutors()>0)
computers.put(n,c=n.createComputer());
}
used.add(c);
}
/*package*/ void removeComputer(Computer computer) {
for (Entry<Node, Computer> e : computers.entrySet()) {
if (e.getValue() == computer) {
computers.remove(e.getKey());
return;
}
}
throw new IllegalStateException("Trying to remove unknown computer");
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, write code like
* {@code Hudson.getInstance().getActions().add(...)}
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Hudson}.
*
* @see #getAllItems(Class)
*/
public List<TopLevelItem> getItems() {
return new ArrayList<TopLevelItem>(items.values());
}
/**
* Gets just the immediate children of {@link Hudson} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : items.values())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
List<T> r = new ArrayList<T>();
Stack<ItemGroup> q = new Stack<ItemGroup>();
q.push(this);
while(!q.isEmpty()) {
ItemGroup<?> parent = q.pop();
for (Item i : parent.getItems()) {
if(type.isInstance(i))
r.add(type.cast(i));
if(i instanceof ItemGroup)
q.push((ItemGroup)i);
}
}
return r;
}
/**
* Gets the list of all the projects.
*
* <p>
* Since {@link Project} can only show up under {@link Hudson},
* no need to search recursively.
*/
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
/**
* Every job belongs to us.
*
* @deprecated
* why are you calling a method that always return true?
*/
@Deprecated
public boolean contains(TopLevelItem view) {
return true;
}
public synchronized View getView(String name) {
if(views!=null) {
for (ListView v : views) {
if(v.getViewName().equals(name))
return v;
}
}
if (this.getViewName().equals(name)) {
return this;
} else if (myView.getViewName().equals(name)) {
return myView;
} else
return null;
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public synchronized View[] getViews() {
if(views==null)
views = new ArrayList<ListView>();
if(Functions.isAnonymous()) {
View[] r = new View[views.size()+1];
views.toArray(r);
// sort Views and put "all" at the very beginning
r[r.length-1] = r[0];
Arrays.sort(r,1,r.length, View.SORTER);
r[0] = this;
return r;
} else {
// this is an authenticated user, so let's have the "my projects" view
View[] r = new View[views.size()+2];
views.toArray(r);
r[r.length-2] = r[0];
r[r.length-1] = r[1];
Arrays.sort(r,2,r.length, View.SORTER);
r[0] = myView;
r[1] = this;
return r;
}
}
public synchronized void deleteView(ListView view) throws IOException {
if(views!=null) {
views.remove(view);
save();
}
}
public String getViewName() {
return Messages.Hudson_ViewName();
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Hudson.this) return -1;
if(rhs.getNode()==Hudson.this) return 1;
return lhs.getDisplayName().compareTo(rhs.getDisplayName());
}
});
return r;
}
/*package*/ Computer getComputer(Node n) {
return computers.get(n);
}
public Computer getComputer(String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getNode().getNodeName().equals(name))
return c;
}
return null;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
public ComputerSet getComputer() {
return new ComputerSet();
}
public Computer toComputer() {
return getComputer(this);
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if no such label exists.
*/
public Label getLabel(String name) {
if(name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return l;
// non-existent
labels.putIfAbsent(name,new Label(name));
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.getNodes().isEmpty())
r.add(l);
}
return r;
}
public Queue getQueue() {
return queue;
}
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Hudson.
*/
public Slave getSlave(String name) {
for (Slave s : getSlaves()) {
if(s.getNodeName().equals(name))
return s;
}
return null;
}
public List<Slave> getSlaves() {
return Collections.unmodifiableList(slaves);
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* @deprecated
* Why are you calling a method that always returns ""?
* Perhaps you meant {@link #getRootUrl()}.
*/
public String getUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<ListView> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Hudson,
* such as "http://localhost/hudson/".
*
* <p>
* Also note that when serving user requests from HTTP, you should always use
* {@link HttpServletRequest} to determine the full URL, instead of using this
* (this is because one host may have multiple names, and {@link HttpServletRequest}
* accurately represents what the current user used.)
*
* <p>
* This information is rather only meant to be useful for sending out messages
* via non-HTTP channels, like SMTP or IRC, with a link back to Hudson website.
*
* @return
* This method returns null if this parameter is not configured by the user.
* The caller must gracefully deal with this situation.
* The returned URL will always have the trailing '/'.
* @since 1.66
*/
public String getRootUrl() {
// for compatibility. the actual data is stored in Mailer
String url = Mailer.DESCRIPTOR.getUrl();
if(url!=null) return url;
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null) {
StringBuilder buf = new StringBuilder();
buf.append("http://");
buf.append(req.getServerName());
if(req.getServerPort()!=80)
buf.append(':').append(req.getServerPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
return null;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
return new FilePath(new File(item.getRootDir(),"workspace"));
}
public FilePath getRootPath() {
return new FilePath(getRootDir());
}
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION;
}
/**
* Returns the constant that captures the three basic security modes
* in Hudson.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.securityRealm = securityRealm;
SecurityComponents sc = securityRealm.createSecurityComponents();
HudsonFilter.AUTHENTICATION_MANAGER.setDelegate(sc.manager);
HudsonFilter.USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails);
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* Returns true if Hudson is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* @deprecated
* Left only for the compatibility of URLs.
* Should not be invoked for any other purpose.
*/
public TopLevelItem getJob(String name) {
return getItem(name);
}
/**
* @deprecated
* Used only for mapping jobs to URL in a case-insensitive fashion.
*/
public TopLevelItem getJobCaseInsensitive(String name) {
for (Entry<String, TopLevelItem> e : items.entrySet()) {
if(Functions.toEmailSafeString(e.getKey()).equalsIgnoreCase(Functions.toEmailSafeString(name)))
return e.getValue();
}
return null;
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override
public TopLevelItem getItem(String name) {
return items.get(name);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
*/
public <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
parent = (ItemGroup) item;
}
}
public Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return
* This method returns a non-null object for any user name, without validation.
*/
public User getUser(String name) {
return User.get(name);
}
/**
* Creates a new job.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
if(items.containsKey(name))
throw new IllegalArgumentException();
TopLevelItem item;
try {
item = type.newInstance(name);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
item.save();
items.put(name,item);
return item;
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
/*package*/ void deleteJob(TopLevelItem item) throws IOException {
for (ItemListener l : itemListeners)
l.onDeleted(item);
items.remove(item.getName());
if(views!=null) {
for (ListView v : views) {
synchronized(v) {
v.jobNames.remove(item.getName());
}
}
save();
}
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Hudson by the caller.
*/
/*package*/ void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
if(views!=null) {
for (ListView v : views) {
synchronized(v) {
if(v.jobNames.remove(oldName))
v.jobNames.add(newName);
}
}
save();
}
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public Set<Label> getAssignedLabels() {
if (labelSet == null) {
Set<Label> r = new HashSet<Label>();
r.addAll(getDynamicLabels());
r.add(getSelfLabel());
this.labelSet = Collections.unmodifiableSet(r);
}
return labelSet;
}
/**
* Returns the possibly empty set of labels that it has been determined as supported by this node.
*
* @see hudson.tasks.LabelFinder
*/
public Set<Label> getDynamicLabels() {
if (dynamicLabels == null) {
// in the worst cast, two threads end up doing the same computation twice,
// but that won't break the semantics.
// OTOH, not locking prevents dead-lock. See #1390
Set<Label> r = new HashSet<Label>();
Computer comp = getComputer("");
if (comp != null) {
VirtualChannel channel = comp.getChannel();
if (channel != null) {
for (DynamicLabeler labeler : LabelFinder.LABELERS) {
for (String label : labeler.findLabels(channel)) {
r.add(getLabel(label));
}
}
}
}
dynamicLabels = r;
}
return dynamicLabels;
}
public Label getSelfLabel() {
return getLabel("master");
}
public Computer createComputer() {
return new MasterComputer();
}
private synchronized void load() throws IOException {
long startTime = System.currentTimeMillis();
XmlFile cfg = getConfigFile();
if(cfg.exists())
cfg.unmarshal(this);
File projectsDir = new File(root,"jobs");
if(!projectsDir.isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles(new FileFilter() {
public boolean accept(File child) {
return child.isDirectory() && Items.getConfigFile(child).exists();
}
});
items.clear();
if(parallelLoad) {
// load jobs in parallel for better performance
List<Future<TopLevelItem>> loaders = new ArrayList<Future<TopLevelItem>>();
for (final File subdir : subdirs) {
loaders.add(threadPoolForLoad.submit(new Callable<TopLevelItem>() {
public TopLevelItem call() throws Exception {
return (TopLevelItem) Items.load(Hudson.this, subdir);
}
}));
}
for (Future<TopLevelItem> loader : loaders) {
try {
TopLevelItem item = loader.get();
items.put(item.getName(), item);
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to load a project",e.getCause());
} catch (InterruptedException e) {
e.printStackTrace(); // this is probably not the right thing to do
}
}
} else {
for (File subdir : subdirs) {
try {
TopLevelItem item = (TopLevelItem)Items.load(this,subdir);
items.put(item.getName(), item);
} catch (Error e) {
LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
} catch (RuntimeException e) {
LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+subdir,e);
}
}
}
rebuildDependencyGraph();
// recompute label objects
if (null != slaves) { // only if we have slaves
for (Slave slave : slaves)
slave.getAssignedLabels();
}
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null || !useSecurity)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null || !useSecurity)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
if(useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
}
LOGGER.info(String.format("Took %s ms to load",System.currentTimeMillis()-startTime));
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
getConfigFile().write(this);
}
/**
* Called to shut down the system.
*/
public void cleanUp() {
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
c.kill();
c.disconnect();
}
ExternalJob.reloadThread.interrupt();
Trigger.timer.cancel();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create HUDSON_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
}
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
for (Action a : getActions())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
try {
checkPermission(ADMINISTER);
req.setCharacterEncoding("UTF-8");
JSONObject json = StructuredForm.get(req);
// keep using 'useSecurity' field as the main configuration setting
// until we get the new security implementation working
// useSecurity = null;
if (json.has("use_security")) {
useSecurity = true;
JSONObject security = json.getJSONObject("use_security");
setSecurityRealm(SecurityRealm.LIST.newInstanceFromRadioList(security,"realm"));
authorizationStrategy = AuthorizationStrategy.LIST.newInstanceFromRadioList(security,"authorization");
if(authorizationStrategy==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
} else {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
{
String v = req.getParameter("slaveAgentPortType");
if(!isUseSecurity() || v==null || v.equals("random"))
slaveAgentPort = 0;
else
if(v.equals("disable"))
slaveAgentPort = -1;
else {
try {
slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
} catch (NumberFormatException e) {
throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")),"slaveAgentPort");
}
}
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
systemMessage = Util.nullify(req.getParameter("system_message"));
{// update JDK installations
jdks.clear();
String[] names = req.getParameterValues("jdk_name");
String[] homes = req.getParameterValues("jdk_home");
if(names!=null && homes!=null) {
int len = Math.min(names.length,homes.length);
for(int i=0;i<len;i++) {
jdks.add(new JDK(names[i],homes[i]));
}
}
}
boolean result = true;
for( Descriptor<Builder> d : BuildStep.BUILDERS )
result &= d.configure(req);
for( Descriptor<Publisher> d : BuildStep.PUBLISHERS )
result &= d.configure(req);
for( Descriptor<BuildWrapper> d : BuildWrappers.WRAPPERS )
result &= d.configure(req);
for( SCMDescriptor scmd : SCMS.SCMS )
result &= scmd.configure(req);
for( TriggerDescriptor d : Triggers.TRIGGERS )
result &= d.configure(req);
for( JobPropertyDescriptor d : Jobs.PROPERTIES )
result &= d.configure(req);
save();
if(result)
rsp.sendRedirect(req.getContextPath()+'/'); // go to the top page
else
rsp.sendRedirect("configure"); // back to config
} catch (FormException e) {
sendError(e,req,rsp);
}
}
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ADMINISTER);
JSONObject json = StructuredForm.get(req);
numExecutors = Integer.parseInt(req.getParameter("numExecutors"));
if(req.hasParameter("master.mode"))
mode = Mode.valueOf(req.getParameter("master.mode"));
else
mode = Mode.NORMAL;
{
// update slave list
this.slaves = req.bindJSONToList(Slave.class,json.get("slaves"));
updateComputerList();
// label trim off
for (Label l : labels.values()) {
l.reset();
if(l.getNodes().isEmpty())
labels.remove(l);
}
}
save();
rsp.sendRedirect(req.getContextPath()+'/'); // go to the top page
}
/**
* Accepts the new description.
*/
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ADMINISTER);
req.setCharacterEncoding("UTF-8");
systemMessage = req.getParameter("description");
save();
rsp.sendRedirect(".");
}
public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
checkPermission(ADMINISTER);
isQuietingDown = true;
rsp.sendRedirect2(".");
}
public synchronized void doCancelQuietDown(StaplerResponse rsp) throws IOException, ServletException {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
rsp.sendRedirect2(".");
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
public synchronized Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(Job.CREATE);
TopLevelItem result;
String requestContentType = req.getContentType();
if(requestContentType==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"No Content-Type header set");
return null;
}
boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");
if(!isXmlSubmission) {
// containers often implement RFCs incorrectly in that it doesn't interpret query parameter
// decoding with UTF-8. This will ensure we get it right.
// but doing this for config.xml submission could potentiall overwrite valid
// "text/xml;charset=xxx"
req.setCharacterEncoding("UTF-8");
}
String name = req.getParameter("name");
if(name==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
return null;
}
name = name.trim();
String mode = req.getParameter("mode");
try {
checkGoodName(name);
} catch (ParseException e) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(e,req,rsp);
return null;
}
if(getItem(name)!=null) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
return null;
}
if(mode!=null && mode.equals("copyJob")) {
- TopLevelItem src = getItem(req.getParameter("from"));
+ String from = req.getParameter("from");
+ TopLevelItem src = getItem(from);
if(src==null) {
- rsp.sendError(SC_BAD_REQUEST);
+ rsp.setStatus(SC_BAD_REQUEST);
+ if(Util.fixEmpty(from)==null)
+ sendError("Specify which job to copy",req,rsp);
+ else
+ sendError("No such job: "+from,req,rsp);
return null;
}
result = createProject(src.getDescriptor(),name);
// copy config
Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
// reload from the new config
result = (TopLevelItem)Items.load(this,result.getRootDir());
result.onCopiedFrom(src);
items.put(name,result);
} else {
if(isXmlSubmission) {
// config.xml submission
// first copy it as config.xml
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
configXml.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(configXml);
try {
Util.copyStream(req.getInputStream(),fos);
} finally {
fos.close();
}
// load it
result = (TopLevelItem)Items.load(this,configXml.getParentFile());
items.put(name,result);
} catch (IOException e) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(configXml.getParentFile());
throw e;
}
} else {
// create empty job and redirect to the project config screen
if(mode==null) {
rsp.sendError(SC_BAD_REQUEST);
return null;
}
result = createProject(Items.getDescriptor(mode), name);
}
}
for (ItemListener l : itemListeners)
l.onCreated(result);
if(isXmlSubmission) {
// it worked
rsp.setStatus(HttpServletResponse.SC_OK);
} else {
// send the browser to the config page
rsp.sendRedirect2(result.getUrl()+"configure");
}
return result;
}
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(View.CREATE);
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
try {
checkGoodName(name);
} catch (ParseException e) {
sendError(e, req, rsp);
return;
}
ListView v = new ListView(this, name);
if(views==null)
views = new Vector<ListView>();
views.add(v);
save();
// redirect to the config screen
rsp.sendRedirect2("./"+v.getUrl()+"configure");
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws ParseException
* if the given name is not good
*/
public static void checkGoodName(String name) throws ParseException {
if(name==null || name.length()==0)
throw new ParseException(Messages.Hudson_NoName(),0);
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new ParseException(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)),i);
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new ParseException(Messages.Hudson_UnsafeChar(ch),i);
}
// looks good
}
private static String toPrintableName(String name) {
StringBuffer printableName = new StringBuffer();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null)
rsp.sendRedirect2("noPrincipal");
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Called once the user logs in. Just forward to the top page.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException {
HttpSession session = req.getSession(false);
if(session!=null)
session.invalidate();
SecurityContextHolder.clearContext();
// reset remember-me cookie
Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY,"");
cookie.setPath(req.getContextPath().length()>0 ? req.getContextPath() : "/");
rsp.addCookie(cookie);
rsp.sendRedirect2(req.getContextPath()+"/");
}
/**
* RSS feed for log entries.
*/
public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(ADMINISTER);
List<LogRecord> logs = logRecords;
// filter log records based on the log level
String level = req.getParameter("level");
if(level!=null) {
Level threshold = Level.parse(level);
List<LogRecord> filtered = new ArrayList<LogRecord>();
for (LogRecord r : logs) {
if(r.getLevel().intValue() >= threshold.intValue())
filtered.add(r);
}
logs = filtered;
}
RSS.forwardToRss("Hudson log","", logs, new FeedAdapter<LogRecord>() {
public String getEntryTitle(LogRecord entry) {
return entry.getMessage();
}
public String getEntryUrl(LogRecord entry) {
return "log"; // TODO: one URL for one log entry?
}
public String getEntryID(LogRecord entry) {
return String.valueOf(entry.getSequenceNumber());
}
public String getEntryDescription(LogRecord entry) {
return Functions.printLogRecord(entry);
}
public Calendar getEntryTimestamp(LogRecord entry) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(entry.getMillis());
return cal;
}
},req,rsp);
}
/**
* Reloads the configuration.
*/
public synchronized void doReload( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
final ServletContext context = req.getServletContext();
context.setAttribute("app",new HudsonIsLoading());
rsp.sendRedirect2(req.getContextPath()+"/");
new Thread("Hudson config reload thread") {
public void run() {
try {
load();
User.reload();
context.setAttribute("app",Hudson.this);
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to reload Hudson config",e);
}
}
}.start();
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* Serves static resources without the "Last-Modified" header to work around
* a bug in Firefox.
*
* <p>
* See https://bugzilla.mozilla.org/show_bug.cgi?id=89419
*/
public void doNocacheImages( StaplerRequest req, StaplerResponse rsp ) throws IOException {
String path = req.getRestOfPath();
if(path.length()==0)
path = "/";
if(path.indexOf("..")!=-1 || path.length()<1) {
// don't serve anything other than files in the artifacts dir
rsp.sendError(SC_BAD_REQUEST);
return;
}
File f = new File(req.getServletContext().getRealPath("/images"),path.substring(1));
if(!f.exists()) {
rsp.sendError(SC_NOT_FOUND);
return;
}
if(f.isDirectory()) {
// listing not allowed
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
FileInputStream in = new FileInputStream(f);
// serve the file
String contentType = req.getServletContext().getMimeType(f.getPath());
rsp.setContentType(contentType);
rsp.setContentLength((int)f.length());
Util.copyStream(in,rsp.getOutputStream());
in.close();
}
/**
* For debugging. Expose URL to perform GC.
*/
public void doGc(StaplerResponse rsp) throws IOException {
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* Shutdown the system.
* @since 1.161
*/
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication(), req.getRemoteAddr()));
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
System.exit(0);
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = new AnonymousAuthenticationToken("anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
return a;
}
/**
* Configure the logging level.
*/
public void doConfigLogger(StaplerResponse rsp, @QueryParameter("name")String name, @QueryParameter("level")String level) throws IOException {
checkPermission(ADMINISTER);
Level lv;
if(level.equals("inherit"))
lv = null;
else
lv = Level.parse(level.toUpperCase());
Logger.getLogger(name).setLevel(lv);
rsp.sendRedirect2("log");
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
checkPermission(ADMINISTER);
String text = req.getParameter("script");
if(text!=null) {
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
req.getView(this,"_script.jelly").forward(req,rsp);
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
req.getView(getSecurityRealm(),"signup.jelly").forward(req,rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null || !ICON_SIZE.matcher(qs).matches())
throw new ServletException();
Cookie cookie = new Cookie("iconSize", qs);
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* Checks if the path is a valid path.
*/
public void doCheckLocalFSRoot( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// this can be used to check the existence of a file on the server, so needs to be protected
new FormFieldValidator.WorkspaceDirectory(req,rsp,true).process();
}
/**
* Checks if the JAVA_HOME is a valid JAVA_HOME path.
*/
public void doJavaHomeCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// this can be used to check the existence of a file on the server, so needs to be protected
new FormFieldValidator(req,rsp,true) {
public void check() throws IOException, ServletException {
File f = getFileParameter("value");
if(!f.isDirectory()) {
error(Messages.Hudson_NotADirectory(f));
return;
}
File toolsJar = new File(f,"lib/tools.jar");
File mac = new File(f,"lib/dt.jar");
if(!toolsJar.exists() && !mac.exists()) {
error(Messages.Hudson_NotJDKDir(f));
return;
}
ok();
}
}.process();
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public void doDefaultJDKCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
new FormFieldValidator(req,rsp,true) {
public void check() throws IOException, ServletException {
String v = request.getParameter("value");
if(!v.equals("(Default)"))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
ok();
else {
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Hudson.this))
ok();
else
errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
}
}.process();
}
/**
* Checks if the top-level item with the given name exists.
*/
public void doItemExistsCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
new FormFieldValidator(req,rsp,true) {
protected void check() throws IOException, ServletException {
String job = fixEmpty(request.getParameter("value"));
if(job==null) {
ok(); // nothing is entered yet
return;
}
if(getItem(job)==null)
ok();
else
error(Messages.Hudson_JobAlreadyExists(job));
}
}.process();
}
/**
* Checks if the value for a field is set; if not an error or warning text is displayed.
* If the parameter "value" is not set then the parameter "errorText" is displayed
* as an error text. If the parameter "errorText" is not set, then the parameter "warningText" is
* displayed as a warning text.
* <p/>
* If the text is set and the parameter "type" is set, it will validate that the value is of the
* correct type. Supported types are "number, "number-positive" and "number-negative".
* @param req containing the parameter value and the errorText to display if the value isnt set
* @param rsp used by FormFieldValidator
* @throws IOException thrown by FormFieldValidator.check()
* @throws ServletException thrown by FormFieldValidator.check()
*/
public void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, false) {
/**
* Display the error text or warning text.
*/
private void fieldCheckFailed() throws IOException, ServletException {
String v = fixEmpty(request.getParameter("errorText"));
if (v != null) {
error(v);
return;
}
v = fixEmpty(request.getParameter("warningText"));
if (v != null) {
warning(v);
return;
}
error("No error or warning text was set for fieldCheck().");
return;
}
/**
* Checks if the value is of the correct type.
* @param type the type of string
* @param value the actual value to check
* @return true, if the type was valid; false otherwise
*/
private boolean checkType(String type, String value) throws IOException, ServletException {
try {
if (type.equalsIgnoreCase("number")) {
NumberFormat.getInstance().parse(value);
} else if (type.equalsIgnoreCase("number-positive")) {
if (NumberFormat.getInstance().parse(value).floatValue() <= 0) {
error(Messages.Hudson_NotAPositiveNumber());
return false;
}
} else if (type.equalsIgnoreCase("number-negative")) {
if (NumberFormat.getInstance().parse(value).floatValue() >= 0) {
error(Messages.Hudson_NotANegativeNumber());
return false;
}
}
} catch (ParseException e) {
error(Messages.Hudson_NotANumber());
return false;
}
return true;
}
@Override
protected void check() throws IOException, ServletException {
String value = fixEmpty(request.getParameter("value"));
if (value == null) {
fieldCheckFailed();
return;
}
String type = fixEmpty(request.getParameter("type"));
if (type != null) {
if (!checkType(type, value)) {
return;
}
}
ok();
}
}.process();
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(1);
path = path.substring(path.indexOf('/')+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://hudson.gotdns.com/wiki/display/HUDSON/Tomcat#Tomcat-i18n
*
* @param req containing the parameter value
* @param rsp used by FormFieldValidator
* @throws IOException thrown by FormFieldValidator.check()
* @throws ServletException thrown by FormFieldValidator.check()
*/
public void doCheckURIEncoding(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, true) {
@Override
protected void check() throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value)) {
warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return;
}
ok();
}
}.process();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
/**
* Returns all {@code CVSROOT} strings used in the current Hudson installation.
*
* <p>
* Ideally this shouldn't be defined in here
* but EL doesn't provide a convenient way of invoking a static function,
* so I'm putting it here for now.
*/
public Set<String> getAllCvsRoots() {
Set<String> r = new TreeSet<String>();
for( AbstractProject p : getAllItems(AbstractProject.class) ) {
SCM scm = p.getScm();
if (scm instanceof CVSSCM) {
CVSSCM cvsscm = (CVSSCM) scm;
r.add(cvsscm.getCvsRoot());
}
}
return r;
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
dependencyGraph = new DependencyGraph();
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.LIST;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/signup")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
throw e;
}
return this;
}
public static final class MasterComputer extends Computer {
private MasterComputer() {
super(Hudson.getInstance());
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
@Override
public VirtualChannel getChannel() {
return localChannel;
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
public void launch() {
// noop
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*/
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
}
/**
* @deprecated
* Use {@link #checkPermission(Permission)}
*/
public static boolean adminCheck() throws IOException {
return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
}
/**
* @deprecated
* Use {@link #checkPermission(Permission)}
*/
public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
if (isAdmin(req)) return true;
rsp.sendError(StaplerResponse.SC_FORBIDDEN);
return false;
}
/**
* Checks if the current user (for which we are processing the current request)
* has the admin access.
*
* @deprecated
* This method is deprecated when Hudson moved from simple Unix root-like model
* of "admin gets to do everything, and others don't have any privilege" to more
* complex {@link ACL} and {@link Permission} based scheme.
*
* <p>
* For a quick migration, use {@code Hudson.getInstance().getACL().hasPermission(Hudson.ADMINISTER)}
* To check if the user has the 'administer' role in Hudson.
*
* <p>
* But ideally, your plugin should first identify a suitable {@link Permission} (or create one,
* if appropriate), then identify a suitable {@link AccessControlled} object to check its permission
* against.
*/
public static boolean isAdmin() {
return Hudson.getInstance().getACL().hasPermission(ADMINISTER);
}
/**
* @deprecated
* Define a custom {@link Permission} and check against ACL.
* See {@link #isAdmin()} for more instructions.
*/
public static boolean isAdmin(StaplerRequest req) {
return isAdmin();
}
/**
* Live view of recent {@link LogRecord}s produced by Hudson.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM = new XStream2();
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ static final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
0, Runtime.getRuntime().availableProcessors() * 2,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
/**
* Version number of this Hudson.
*/
public static String VERSION;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
*/
public static String RESOURCE_PATH;
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Hudson to pick up
* stale cache when the user upgrades to a different version.
*/
public static String VIEW_RESOURCE_PATH;
public static boolean parallelLoad = Boolean.getBoolean(Hudson.class.getName()+".parallelLoad");
private static final Logger LOGGER = Logger.getLogger(Hudson.class.getName());
private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Hudson.class,Messages._Hudson_Permissions_Title());
public static final Permission ADMINISTER = new Permission(PERMISSIONS,"Administer", Permission.FULL_CONTROL);
public static final Permission READ = new Permission(PERMISSIONS,"Read", Permission.READ);
static {
XSTREAM.alias("hudson",Hudson.class);
XSTREAM.alias("slave",Slave.class);
XSTREAM.alias("jdk",JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
}
}
| false | true |
public synchronized Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(Job.CREATE);
TopLevelItem result;
String requestContentType = req.getContentType();
if(requestContentType==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"No Content-Type header set");
return null;
}
boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");
if(!isXmlSubmission) {
// containers often implement RFCs incorrectly in that it doesn't interpret query parameter
// decoding with UTF-8. This will ensure we get it right.
// but doing this for config.xml submission could potentiall overwrite valid
// "text/xml;charset=xxx"
req.setCharacterEncoding("UTF-8");
}
String name = req.getParameter("name");
if(name==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
return null;
}
name = name.trim();
String mode = req.getParameter("mode");
try {
checkGoodName(name);
} catch (ParseException e) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(e,req,rsp);
return null;
}
if(getItem(name)!=null) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
return null;
}
if(mode!=null && mode.equals("copyJob")) {
TopLevelItem src = getItem(req.getParameter("from"));
if(src==null) {
rsp.sendError(SC_BAD_REQUEST);
return null;
}
result = createProject(src.getDescriptor(),name);
// copy config
Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
// reload from the new config
result = (TopLevelItem)Items.load(this,result.getRootDir());
result.onCopiedFrom(src);
items.put(name,result);
} else {
if(isXmlSubmission) {
// config.xml submission
// first copy it as config.xml
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
configXml.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(configXml);
try {
Util.copyStream(req.getInputStream(),fos);
} finally {
fos.close();
}
// load it
result = (TopLevelItem)Items.load(this,configXml.getParentFile());
items.put(name,result);
} catch (IOException e) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(configXml.getParentFile());
throw e;
}
} else {
// create empty job and redirect to the project config screen
if(mode==null) {
rsp.sendError(SC_BAD_REQUEST);
return null;
}
result = createProject(Items.getDescriptor(mode), name);
}
}
for (ItemListener l : itemListeners)
l.onCreated(result);
if(isXmlSubmission) {
// it worked
rsp.setStatus(HttpServletResponse.SC_OK);
} else {
// send the browser to the config page
rsp.sendRedirect2(result.getUrl()+"configure");
}
return result;
}
|
public synchronized Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(Job.CREATE);
TopLevelItem result;
String requestContentType = req.getContentType();
if(requestContentType==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"No Content-Type header set");
return null;
}
boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");
if(!isXmlSubmission) {
// containers often implement RFCs incorrectly in that it doesn't interpret query parameter
// decoding with UTF-8. This will ensure we get it right.
// but doing this for config.xml submission could potentiall overwrite valid
// "text/xml;charset=xxx"
req.setCharacterEncoding("UTF-8");
}
String name = req.getParameter("name");
if(name==null) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Query parameter 'name' is required");
return null;
}
name = name.trim();
String mode = req.getParameter("mode");
try {
checkGoodName(name);
} catch (ParseException e) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(e,req,rsp);
return null;
}
if(getItem(name)!=null) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(Messages.Hudson_JobAlreadyExists(name),req,rsp);
return null;
}
if(mode!=null && mode.equals("copyJob")) {
String from = req.getParameter("from");
TopLevelItem src = getItem(from);
if(src==null) {
rsp.setStatus(SC_BAD_REQUEST);
if(Util.fixEmpty(from)==null)
sendError("Specify which job to copy",req,rsp);
else
sendError("No such job: "+from,req,rsp);
return null;
}
result = createProject(src.getDescriptor(),name);
// copy config
Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
// reload from the new config
result = (TopLevelItem)Items.load(this,result.getRootDir());
result.onCopiedFrom(src);
items.put(name,result);
} else {
if(isXmlSubmission) {
// config.xml submission
// first copy it as config.xml
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
configXml.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(configXml);
try {
Util.copyStream(req.getInputStream(),fos);
} finally {
fos.close();
}
// load it
result = (TopLevelItem)Items.load(this,configXml.getParentFile());
items.put(name,result);
} catch (IOException e) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(configXml.getParentFile());
throw e;
}
} else {
// create empty job and redirect to the project config screen
if(mode==null) {
rsp.sendError(SC_BAD_REQUEST);
return null;
}
result = createProject(Items.getDescriptor(mode), name);
}
}
for (ItemListener l : itemListeners)
l.onCreated(result);
if(isXmlSubmission) {
// it worked
rsp.setStatus(HttpServletResponse.SC_OK);
} else {
// send the browser to the config page
rsp.sendRedirect2(result.getUrl()+"configure");
}
return result;
}
|
diff --git a/src/org/mozilla/javascript/NodeTransformer.java b/src/org/mozilla/javascript/NodeTransformer.java
index b2e38949..33317c25 100644
--- a/src/org/mozilla/javascript/NodeTransformer.java
+++ b/src/org/mozilla/javascript/NodeTransformer.java
@@ -1,539 +1,540 @@
/* -*- 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
* Igor Bukanov
* Bob Jervis
* Roger Lawrence
* Mike McCabe
*
* 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;
import java.util.Iterator;
import java.util.Set;
import java.util.ArrayList;
/**
* This class transforms a tree to a lower-level representation for codegen.
*
* @see Node
* @author Norris Boyd
*/
public class NodeTransformer
{
public NodeTransformer()
{
}
public final void transform(ScriptOrFnNode tree)
{
transformCompilationUnit(tree);
for (int i = 0; i != tree.getFunctionCount(); ++i) {
FunctionNode fn = tree.getFunctionNode(i);
transform(fn);
}
}
private void transformCompilationUnit(ScriptOrFnNode tree)
{
loops = new ObjArray();
loopEnds = new ObjArray();
// to save against upchecks if no finally blocks are used.
hasFinally = false;
// Flatten all only if we are not using scope objects for block scope
boolean createScopeObjects = tree.getType() != Token.FUNCTION ||
((FunctionNode)tree).requiresActivation();
tree.flattenSymbolTable(!createScopeObjects);
//uncomment to print tree before transformation
//if (Token.printTrees) System.out.println(tree.toStringTree(tree));
transformCompilationUnit_r(tree, tree, tree, createScopeObjects);
}
private void transformCompilationUnit_r(final ScriptOrFnNode tree,
final Node parent,
Node.Scope scope,
boolean createScopeObjects)
{
Node node = null;
siblingLoop:
for (;;) {
Node previous = null;
if (node == null) {
node = parent.getFirstChild();
} else {
previous = node;
node = node.getNext();
}
if (node == null) {
break;
}
int type = node.getType();
if (createScopeObjects &&
(type == Token.BLOCK || type == Token.LOOP) &&
(node instanceof Node.Scope))
{
Node.Scope newScope = (Node.Scope) node;
if (newScope.symbolTable != null) {
// transform to let statement so we get a with statement
// created to contain scoped let variables
Node let = new Node(Token.LET);
+ Node innerLet = new Node(Token.LET);
+ let.addChildToBack(innerLet);
Iterator iter = newScope.symbolTable.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
- let.addChildToBack(new Node(Token.LET,
- Node.newString(Token.NAME, name)));
+ innerLet.addChildToBack(Node.newString(Token.NAME, name));
}
newScope.symbolTable = null; // so we don't transform again
Node oldNode = node;
node = replaceCurrent(parent, previous, node, let);
type = node.getType();
let.addChildToBack(oldNode);
}
}
switch (type) {
case Token.LABEL:
case Token.SWITCH:
case Token.LOOP:
loops.push(node);
loopEnds.push(((Node.Jump)node).target);
break;
case Token.WITH:
{
loops.push(node);
Node leave = node.getNext();
if (leave.getType() != Token.LEAVEWITH) {
Kit.codeBug();
}
loopEnds.push(leave);
break;
}
case Token.TRY:
{
Node.Jump jump = (Node.Jump)node;
Node finallytarget = jump.getFinally();
if (finallytarget != null) {
hasFinally = true;
loops.push(node);
loopEnds.push(finallytarget);
}
break;
}
case Token.TARGET:
case Token.LEAVEWITH:
if (!loopEnds.isEmpty() && loopEnds.peek() == node) {
loopEnds.pop();
loops.pop();
}
break;
case Token.YIELD:
((FunctionNode)tree).addResumptionPoint(node);
break;
case Token.RETURN:
{
boolean isGenerator = tree.getType() == Token.FUNCTION
&& ((FunctionNode)tree).isGenerator();
if (isGenerator) {
node.putIntProp(Node.GENERATOR_END_PROP, 1);
}
/* If we didn't support try/finally, it wouldn't be
* necessary to put LEAVEWITH nodes here... but as
* we do need a series of JSR FINALLY nodes before
* each RETURN, we need to ensure that each finally
* block gets the correct scope... which could mean
* that some LEAVEWITH nodes are necessary.
*/
if (!hasFinally)
break; // skip the whole mess.
Node unwindBlock = null;
for (int i=loops.size()-1; i >= 0; i--) {
Node n = (Node) loops.get(i);
int elemtype = n.getType();
if (elemtype == Token.TRY || elemtype == Token.WITH) {
Node unwind;
if (elemtype == Token.TRY) {
Node.Jump jsrnode = new Node.Jump(Token.JSR);
Node jsrtarget = ((Node.Jump)n).getFinally();
jsrnode.target = jsrtarget;
unwind = jsrnode;
} else {
unwind = new Node(Token.LEAVEWITH);
}
if (unwindBlock == null) {
unwindBlock = new Node(Token.BLOCK,
node.getLineno());
}
unwindBlock.addChildToBack(unwind);
}
}
if (unwindBlock != null) {
Node returnNode = node;
Node returnExpr = returnNode.getFirstChild();
node = replaceCurrent(parent, previous, node, unwindBlock);
if (returnExpr == null || isGenerator) {
unwindBlock.addChildToBack(returnNode);
} else {
Node store = new Node(Token.EXPR_RESULT, returnExpr);
unwindBlock.addChildToFront(store);
returnNode = new Node(Token.RETURN_RESULT);
unwindBlock.addChildToBack(returnNode);
// transform return expression
transformCompilationUnit_r(tree, store, scope,
createScopeObjects);
}
// skip transformCompilationUnit_r to avoid infinite loop
continue siblingLoop;
}
break;
}
case Token.BREAK:
case Token.CONTINUE:
{
Node.Jump jump = (Node.Jump)node;
Node.Jump jumpStatement = jump.getJumpStatement();
if (jumpStatement == null) Kit.codeBug();
for (int i = loops.size(); ;) {
if (i == 0) {
// Parser/IRFactory ensure that break/continue
// always has a jump statement associated with it
// which should be found
throw Kit.codeBug();
}
--i;
Node n = (Node) loops.get(i);
if (n == jumpStatement) {
break;
}
int elemtype = n.getType();
if (elemtype == Token.WITH) {
Node leave = new Node(Token.LEAVEWITH);
previous = addBeforeCurrent(parent, previous, node,
leave);
} else if (elemtype == Token.TRY) {
Node.Jump tryNode = (Node.Jump)n;
Node.Jump jsrFinally = new Node.Jump(Token.JSR);
jsrFinally.target = tryNode.getFinally();
previous = addBeforeCurrent(parent, previous, node,
jsrFinally);
}
}
if (type == Token.BREAK) {
jump.target = jumpStatement.target;
} else {
jump.target = jumpStatement.getContinue();
}
jump.setType(Token.GOTO);
break;
}
case Token.CALL:
visitCall(node, tree);
break;
case Token.NEW:
visitNew(node, tree);
break;
case Token.LETEXPR:
case Token.LET: {
Node child = node.getFirstChild();
if (child.getType() == Token.LET) {
// We have a let statement or expression rather than a
// let declaration
boolean createWith = tree.getType() != Token.FUNCTION
|| ((FunctionNode)tree).requiresActivation();
node = visitLet(createWith, parent, previous, node);
break;
} else {
// fall through to process let declaration...
}
}
/* fall through */
case Token.CONST:
case Token.VAR:
{
Node result = new Node(Token.BLOCK);
for (Node cursor = node.getFirstChild(); cursor != null;) {
// Move cursor to next before createAssignment gets chance
// to change n.next
Node n = cursor;
cursor = cursor.getNext();
if (n.getType() == Token.NAME) {
if (!n.hasChildren())
continue;
Node init = n.getFirstChild();
n.removeChild(init);
n.setType(Token.BINDNAME);
n = new Node(type == Token.CONST ?
Token.SETCONST :
Token.SETNAME,
n, init);
} else {
// May be a destructuring assignment already transformed
// to a LETEXPR
if (n.getType() != Token.LETEXPR)
throw Kit.codeBug();
}
Node pop = new Node(Token.EXPR_VOID, n, node.getLineno());
result.addChildToBack(pop);
}
node = replaceCurrent(parent, previous, node, result);
break;
}
case Token.TYPEOFNAME: {
Node.Scope defining = scope.getDefiningScope(node.getString());
if (defining != null) {
node.setScope(defining);
}
}
break;
case Token.TYPEOF:
case Token.IFNE: {
/* We want to suppress warnings for undefined property o.p
* for the following constructs: typeof o.p, if (o.p),
* if (!o.p), if (o.p == undefined), if (undefined == o.p)
*/
Node child = node.getFirstChild();
if (type == Token.IFNE) {
while (child.getType() == Token.NOT) {
child = child.getFirstChild();
}
if (child.getType() == Token.EQ ||
child.getType() == Token.NE)
{
Node first = child.getFirstChild();
Node last = child.getLastChild();
if (first.getType() == Token.NAME &&
first.getString().equals("undefined"))
child = last;
else if (last.getType() == Token.NAME &&
last.getString().equals("undefined"))
child = first;
}
}
if (child.getType() == Token.GETPROP)
child.setType(Token.GETPROPNOWARN);
break;
}
case Token.NAME:
case Token.SETNAME:
case Token.SETCONST:
case Token.DELPROP:
{
// Turn name to var for faster access if possible
if (createScopeObjects) {
break;
}
Node nameSource;
if (type == Token.NAME) {
nameSource = node;
} else {
nameSource = node.getFirstChild();
if (nameSource.getType() != Token.BINDNAME) {
if (type == Token.DELPROP) {
break;
}
throw Kit.codeBug();
}
}
if (nameSource.getScope() != null) {
break; // already have a scope set
}
String name = nameSource.getString();
Node.Scope defining = scope.getDefiningScope(name);
if (defining != null) {
nameSource.setScope(defining);
if (type == Token.NAME) {
node.setType(Token.GETVAR);
} else if (type == Token.SETNAME) {
node.setType(Token.SETVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.SETCONST) {
node.setType(Token.SETCONSTVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.DELPROP) {
// Local variables are by definition permanent
Node n = new Node(Token.FALSE);
node = replaceCurrent(parent, previous, node, n);
} else {
throw Kit.codeBug();
}
}
break;
}
}
transformCompilationUnit_r(tree, node,
node instanceof Node.Scope ? (Node.Scope)node : scope,
createScopeObjects);
}
}
protected void visitNew(Node node, ScriptOrFnNode tree) {
}
protected void visitCall(Node node, ScriptOrFnNode tree) {
}
protected Node visitLet(boolean createWith, Node parent, Node previous,
Node scopeNode)
{
Node vars = scopeNode.getFirstChild();
Node body = vars.getNext();
scopeNode.removeChild(vars);
scopeNode.removeChild(body);
boolean isExpression = scopeNode.getType() == Token.LETEXPR;
Node result;
Node newVars;
if (createWith) {
result = new Node(isExpression ? Token.WITHEXPR : Token.BLOCK);
result = replaceCurrent(parent, previous, scopeNode, result);
ArrayList list = new ArrayList();
Node objectLiteral = new Node(Token.OBJECTLIT);
for (Node v=vars.getFirstChild(); v != null; v = v.getNext()) {
if (v.getType() == Token.LETEXPR) {
// destructuring in let expr, e.g. let ([x, y] = [3, 4]) {}
Node c = v.getFirstChild();
if (c.getType() != Token.LET) throw Kit.codeBug();
// Add initialization code to front of body
body = new Node(Token.BLOCK,
new Node(Token.EXPR_VOID, c.getNext()),
body);
// Update "list" and "objectLiteral" for the variables
// defined in the destructuring assignment
Set names = ((Node.Scope)scopeNode).getSymbolTable().keySet();
list.addAll(names);
for (int i=0; i < names.size(); i++)
objectLiteral.addChildToBack(
new Node(Token.VOID, Node.newNumber(0.0)));
v = c.getFirstChild(); // should be a NAME, checked below
}
if (v.getType() != Token.NAME) throw Kit.codeBug();
list.add(ScriptRuntime.getIndexObject(v.getString()));
Node init = v.getFirstChild();
if (init == null) {
init = new Node(Token.VOID, Node.newNumber(0.0));
}
objectLiteral.addChildToBack(init);
}
objectLiteral.putProp(Node.OBJECT_IDS_PROP, list.toArray());
newVars = new Node(Token.ENTERWITH, objectLiteral);
result.addChildToBack(newVars);
result.addChildToBack(new Node(Token.WITH, body));
result.addChildToBack(new Node(Token.LEAVEWITH));
} else {
result = new Node(isExpression ? Token.COMMA : Token.BLOCK);
result = replaceCurrent(parent, previous, scopeNode, result);
newVars = new Node(Token.COMMA);
for (Node v=vars.getFirstChild(); v != null; v = v.getNext()) {
if (v.getType() != Token.NAME) throw Kit.codeBug();
Node stringNode = Node.newString(v.getString());
stringNode.setScope((Node.Scope)scopeNode);
Node init = v.getFirstChild();
if (init == null) {
init = new Node(Token.VOID, Node.newNumber(0.0));
}
newVars.addChildToBack(new Node(Token.SETVAR, stringNode, init));
}
if (isExpression) {
result.addChildToBack(newVars);
scopeNode.setType(Token.COMMA);
result.addChildToBack(scopeNode);
scopeNode.addChildToBack(body);
} else {
result.addChildToBack(new Node(Token.EXPR_VOID, newVars));
scopeNode.setType(Token.BLOCK);
result.addChildToBack(scopeNode);
scopeNode.addChildrenToBack(body);
}
}
return result;
}
private static Node addBeforeCurrent(Node parent, Node previous,
Node current, Node toAdd)
{
if (previous == null) {
if (!(current == parent.getFirstChild())) Kit.codeBug();
parent.addChildToFront(toAdd);
} else {
if (!(current == previous.getNext())) Kit.codeBug();
parent.addChildAfter(toAdd, previous);
}
return toAdd;
}
private static Node replaceCurrent(Node parent, Node previous,
Node current, Node replacement)
{
if (previous == null) {
if (!(current == parent.getFirstChild())) Kit.codeBug();
parent.replaceChild(current, replacement);
} else if (previous.next == current) {
// Check cachedPrev.next == current is necessary due to possible
// tree mutations
parent.replaceChildAfter(previous, replacement);
} else {
parent.replaceChild(current, replacement);
}
return replacement;
}
private ObjArray loops;
private ObjArray loopEnds;
private boolean hasFinally;
}
| false | true |
private void transformCompilationUnit_r(final ScriptOrFnNode tree,
final Node parent,
Node.Scope scope,
boolean createScopeObjects)
{
Node node = null;
siblingLoop:
for (;;) {
Node previous = null;
if (node == null) {
node = parent.getFirstChild();
} else {
previous = node;
node = node.getNext();
}
if (node == null) {
break;
}
int type = node.getType();
if (createScopeObjects &&
(type == Token.BLOCK || type == Token.LOOP) &&
(node instanceof Node.Scope))
{
Node.Scope newScope = (Node.Scope) node;
if (newScope.symbolTable != null) {
// transform to let statement so we get a with statement
// created to contain scoped let variables
Node let = new Node(Token.LET);
Iterator iter = newScope.symbolTable.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
let.addChildToBack(new Node(Token.LET,
Node.newString(Token.NAME, name)));
}
newScope.symbolTable = null; // so we don't transform again
Node oldNode = node;
node = replaceCurrent(parent, previous, node, let);
type = node.getType();
let.addChildToBack(oldNode);
}
}
switch (type) {
case Token.LABEL:
case Token.SWITCH:
case Token.LOOP:
loops.push(node);
loopEnds.push(((Node.Jump)node).target);
break;
case Token.WITH:
{
loops.push(node);
Node leave = node.getNext();
if (leave.getType() != Token.LEAVEWITH) {
Kit.codeBug();
}
loopEnds.push(leave);
break;
}
case Token.TRY:
{
Node.Jump jump = (Node.Jump)node;
Node finallytarget = jump.getFinally();
if (finallytarget != null) {
hasFinally = true;
loops.push(node);
loopEnds.push(finallytarget);
}
break;
}
case Token.TARGET:
case Token.LEAVEWITH:
if (!loopEnds.isEmpty() && loopEnds.peek() == node) {
loopEnds.pop();
loops.pop();
}
break;
case Token.YIELD:
((FunctionNode)tree).addResumptionPoint(node);
break;
case Token.RETURN:
{
boolean isGenerator = tree.getType() == Token.FUNCTION
&& ((FunctionNode)tree).isGenerator();
if (isGenerator) {
node.putIntProp(Node.GENERATOR_END_PROP, 1);
}
/* If we didn't support try/finally, it wouldn't be
* necessary to put LEAVEWITH nodes here... but as
* we do need a series of JSR FINALLY nodes before
* each RETURN, we need to ensure that each finally
* block gets the correct scope... which could mean
* that some LEAVEWITH nodes are necessary.
*/
if (!hasFinally)
break; // skip the whole mess.
Node unwindBlock = null;
for (int i=loops.size()-1; i >= 0; i--) {
Node n = (Node) loops.get(i);
int elemtype = n.getType();
if (elemtype == Token.TRY || elemtype == Token.WITH) {
Node unwind;
if (elemtype == Token.TRY) {
Node.Jump jsrnode = new Node.Jump(Token.JSR);
Node jsrtarget = ((Node.Jump)n).getFinally();
jsrnode.target = jsrtarget;
unwind = jsrnode;
} else {
unwind = new Node(Token.LEAVEWITH);
}
if (unwindBlock == null) {
unwindBlock = new Node(Token.BLOCK,
node.getLineno());
}
unwindBlock.addChildToBack(unwind);
}
}
if (unwindBlock != null) {
Node returnNode = node;
Node returnExpr = returnNode.getFirstChild();
node = replaceCurrent(parent, previous, node, unwindBlock);
if (returnExpr == null || isGenerator) {
unwindBlock.addChildToBack(returnNode);
} else {
Node store = new Node(Token.EXPR_RESULT, returnExpr);
unwindBlock.addChildToFront(store);
returnNode = new Node(Token.RETURN_RESULT);
unwindBlock.addChildToBack(returnNode);
// transform return expression
transformCompilationUnit_r(tree, store, scope,
createScopeObjects);
}
// skip transformCompilationUnit_r to avoid infinite loop
continue siblingLoop;
}
break;
}
case Token.BREAK:
case Token.CONTINUE:
{
Node.Jump jump = (Node.Jump)node;
Node.Jump jumpStatement = jump.getJumpStatement();
if (jumpStatement == null) Kit.codeBug();
for (int i = loops.size(); ;) {
if (i == 0) {
// Parser/IRFactory ensure that break/continue
// always has a jump statement associated with it
// which should be found
throw Kit.codeBug();
}
--i;
Node n = (Node) loops.get(i);
if (n == jumpStatement) {
break;
}
int elemtype = n.getType();
if (elemtype == Token.WITH) {
Node leave = new Node(Token.LEAVEWITH);
previous = addBeforeCurrent(parent, previous, node,
leave);
} else if (elemtype == Token.TRY) {
Node.Jump tryNode = (Node.Jump)n;
Node.Jump jsrFinally = new Node.Jump(Token.JSR);
jsrFinally.target = tryNode.getFinally();
previous = addBeforeCurrent(parent, previous, node,
jsrFinally);
}
}
if (type == Token.BREAK) {
jump.target = jumpStatement.target;
} else {
jump.target = jumpStatement.getContinue();
}
jump.setType(Token.GOTO);
break;
}
case Token.CALL:
visitCall(node, tree);
break;
case Token.NEW:
visitNew(node, tree);
break;
case Token.LETEXPR:
case Token.LET: {
Node child = node.getFirstChild();
if (child.getType() == Token.LET) {
// We have a let statement or expression rather than a
// let declaration
boolean createWith = tree.getType() != Token.FUNCTION
|| ((FunctionNode)tree).requiresActivation();
node = visitLet(createWith, parent, previous, node);
break;
} else {
// fall through to process let declaration...
}
}
/* fall through */
case Token.CONST:
case Token.VAR:
{
Node result = new Node(Token.BLOCK);
for (Node cursor = node.getFirstChild(); cursor != null;) {
// Move cursor to next before createAssignment gets chance
// to change n.next
Node n = cursor;
cursor = cursor.getNext();
if (n.getType() == Token.NAME) {
if (!n.hasChildren())
continue;
Node init = n.getFirstChild();
n.removeChild(init);
n.setType(Token.BINDNAME);
n = new Node(type == Token.CONST ?
Token.SETCONST :
Token.SETNAME,
n, init);
} else {
// May be a destructuring assignment already transformed
// to a LETEXPR
if (n.getType() != Token.LETEXPR)
throw Kit.codeBug();
}
Node pop = new Node(Token.EXPR_VOID, n, node.getLineno());
result.addChildToBack(pop);
}
node = replaceCurrent(parent, previous, node, result);
break;
}
case Token.TYPEOFNAME: {
Node.Scope defining = scope.getDefiningScope(node.getString());
if (defining != null) {
node.setScope(defining);
}
}
break;
case Token.TYPEOF:
case Token.IFNE: {
/* We want to suppress warnings for undefined property o.p
* for the following constructs: typeof o.p, if (o.p),
* if (!o.p), if (o.p == undefined), if (undefined == o.p)
*/
Node child = node.getFirstChild();
if (type == Token.IFNE) {
while (child.getType() == Token.NOT) {
child = child.getFirstChild();
}
if (child.getType() == Token.EQ ||
child.getType() == Token.NE)
{
Node first = child.getFirstChild();
Node last = child.getLastChild();
if (first.getType() == Token.NAME &&
first.getString().equals("undefined"))
child = last;
else if (last.getType() == Token.NAME &&
last.getString().equals("undefined"))
child = first;
}
}
if (child.getType() == Token.GETPROP)
child.setType(Token.GETPROPNOWARN);
break;
}
case Token.NAME:
case Token.SETNAME:
case Token.SETCONST:
case Token.DELPROP:
{
// Turn name to var for faster access if possible
if (createScopeObjects) {
break;
}
Node nameSource;
if (type == Token.NAME) {
nameSource = node;
} else {
nameSource = node.getFirstChild();
if (nameSource.getType() != Token.BINDNAME) {
if (type == Token.DELPROP) {
break;
}
throw Kit.codeBug();
}
}
if (nameSource.getScope() != null) {
break; // already have a scope set
}
String name = nameSource.getString();
Node.Scope defining = scope.getDefiningScope(name);
if (defining != null) {
nameSource.setScope(defining);
if (type == Token.NAME) {
node.setType(Token.GETVAR);
} else if (type == Token.SETNAME) {
node.setType(Token.SETVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.SETCONST) {
node.setType(Token.SETCONSTVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.DELPROP) {
// Local variables are by definition permanent
Node n = new Node(Token.FALSE);
node = replaceCurrent(parent, previous, node, n);
} else {
throw Kit.codeBug();
}
}
break;
}
}
transformCompilationUnit_r(tree, node,
node instanceof Node.Scope ? (Node.Scope)node : scope,
createScopeObjects);
}
}
|
private void transformCompilationUnit_r(final ScriptOrFnNode tree,
final Node parent,
Node.Scope scope,
boolean createScopeObjects)
{
Node node = null;
siblingLoop:
for (;;) {
Node previous = null;
if (node == null) {
node = parent.getFirstChild();
} else {
previous = node;
node = node.getNext();
}
if (node == null) {
break;
}
int type = node.getType();
if (createScopeObjects &&
(type == Token.BLOCK || type == Token.LOOP) &&
(node instanceof Node.Scope))
{
Node.Scope newScope = (Node.Scope) node;
if (newScope.symbolTable != null) {
// transform to let statement so we get a with statement
// created to contain scoped let variables
Node let = new Node(Token.LET);
Node innerLet = new Node(Token.LET);
let.addChildToBack(innerLet);
Iterator iter = newScope.symbolTable.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
innerLet.addChildToBack(Node.newString(Token.NAME, name));
}
newScope.symbolTable = null; // so we don't transform again
Node oldNode = node;
node = replaceCurrent(parent, previous, node, let);
type = node.getType();
let.addChildToBack(oldNode);
}
}
switch (type) {
case Token.LABEL:
case Token.SWITCH:
case Token.LOOP:
loops.push(node);
loopEnds.push(((Node.Jump)node).target);
break;
case Token.WITH:
{
loops.push(node);
Node leave = node.getNext();
if (leave.getType() != Token.LEAVEWITH) {
Kit.codeBug();
}
loopEnds.push(leave);
break;
}
case Token.TRY:
{
Node.Jump jump = (Node.Jump)node;
Node finallytarget = jump.getFinally();
if (finallytarget != null) {
hasFinally = true;
loops.push(node);
loopEnds.push(finallytarget);
}
break;
}
case Token.TARGET:
case Token.LEAVEWITH:
if (!loopEnds.isEmpty() && loopEnds.peek() == node) {
loopEnds.pop();
loops.pop();
}
break;
case Token.YIELD:
((FunctionNode)tree).addResumptionPoint(node);
break;
case Token.RETURN:
{
boolean isGenerator = tree.getType() == Token.FUNCTION
&& ((FunctionNode)tree).isGenerator();
if (isGenerator) {
node.putIntProp(Node.GENERATOR_END_PROP, 1);
}
/* If we didn't support try/finally, it wouldn't be
* necessary to put LEAVEWITH nodes here... but as
* we do need a series of JSR FINALLY nodes before
* each RETURN, we need to ensure that each finally
* block gets the correct scope... which could mean
* that some LEAVEWITH nodes are necessary.
*/
if (!hasFinally)
break; // skip the whole mess.
Node unwindBlock = null;
for (int i=loops.size()-1; i >= 0; i--) {
Node n = (Node) loops.get(i);
int elemtype = n.getType();
if (elemtype == Token.TRY || elemtype == Token.WITH) {
Node unwind;
if (elemtype == Token.TRY) {
Node.Jump jsrnode = new Node.Jump(Token.JSR);
Node jsrtarget = ((Node.Jump)n).getFinally();
jsrnode.target = jsrtarget;
unwind = jsrnode;
} else {
unwind = new Node(Token.LEAVEWITH);
}
if (unwindBlock == null) {
unwindBlock = new Node(Token.BLOCK,
node.getLineno());
}
unwindBlock.addChildToBack(unwind);
}
}
if (unwindBlock != null) {
Node returnNode = node;
Node returnExpr = returnNode.getFirstChild();
node = replaceCurrent(parent, previous, node, unwindBlock);
if (returnExpr == null || isGenerator) {
unwindBlock.addChildToBack(returnNode);
} else {
Node store = new Node(Token.EXPR_RESULT, returnExpr);
unwindBlock.addChildToFront(store);
returnNode = new Node(Token.RETURN_RESULT);
unwindBlock.addChildToBack(returnNode);
// transform return expression
transformCompilationUnit_r(tree, store, scope,
createScopeObjects);
}
// skip transformCompilationUnit_r to avoid infinite loop
continue siblingLoop;
}
break;
}
case Token.BREAK:
case Token.CONTINUE:
{
Node.Jump jump = (Node.Jump)node;
Node.Jump jumpStatement = jump.getJumpStatement();
if (jumpStatement == null) Kit.codeBug();
for (int i = loops.size(); ;) {
if (i == 0) {
// Parser/IRFactory ensure that break/continue
// always has a jump statement associated with it
// which should be found
throw Kit.codeBug();
}
--i;
Node n = (Node) loops.get(i);
if (n == jumpStatement) {
break;
}
int elemtype = n.getType();
if (elemtype == Token.WITH) {
Node leave = new Node(Token.LEAVEWITH);
previous = addBeforeCurrent(parent, previous, node,
leave);
} else if (elemtype == Token.TRY) {
Node.Jump tryNode = (Node.Jump)n;
Node.Jump jsrFinally = new Node.Jump(Token.JSR);
jsrFinally.target = tryNode.getFinally();
previous = addBeforeCurrent(parent, previous, node,
jsrFinally);
}
}
if (type == Token.BREAK) {
jump.target = jumpStatement.target;
} else {
jump.target = jumpStatement.getContinue();
}
jump.setType(Token.GOTO);
break;
}
case Token.CALL:
visitCall(node, tree);
break;
case Token.NEW:
visitNew(node, tree);
break;
case Token.LETEXPR:
case Token.LET: {
Node child = node.getFirstChild();
if (child.getType() == Token.LET) {
// We have a let statement or expression rather than a
// let declaration
boolean createWith = tree.getType() != Token.FUNCTION
|| ((FunctionNode)tree).requiresActivation();
node = visitLet(createWith, parent, previous, node);
break;
} else {
// fall through to process let declaration...
}
}
/* fall through */
case Token.CONST:
case Token.VAR:
{
Node result = new Node(Token.BLOCK);
for (Node cursor = node.getFirstChild(); cursor != null;) {
// Move cursor to next before createAssignment gets chance
// to change n.next
Node n = cursor;
cursor = cursor.getNext();
if (n.getType() == Token.NAME) {
if (!n.hasChildren())
continue;
Node init = n.getFirstChild();
n.removeChild(init);
n.setType(Token.BINDNAME);
n = new Node(type == Token.CONST ?
Token.SETCONST :
Token.SETNAME,
n, init);
} else {
// May be a destructuring assignment already transformed
// to a LETEXPR
if (n.getType() != Token.LETEXPR)
throw Kit.codeBug();
}
Node pop = new Node(Token.EXPR_VOID, n, node.getLineno());
result.addChildToBack(pop);
}
node = replaceCurrent(parent, previous, node, result);
break;
}
case Token.TYPEOFNAME: {
Node.Scope defining = scope.getDefiningScope(node.getString());
if (defining != null) {
node.setScope(defining);
}
}
break;
case Token.TYPEOF:
case Token.IFNE: {
/* We want to suppress warnings for undefined property o.p
* for the following constructs: typeof o.p, if (o.p),
* if (!o.p), if (o.p == undefined), if (undefined == o.p)
*/
Node child = node.getFirstChild();
if (type == Token.IFNE) {
while (child.getType() == Token.NOT) {
child = child.getFirstChild();
}
if (child.getType() == Token.EQ ||
child.getType() == Token.NE)
{
Node first = child.getFirstChild();
Node last = child.getLastChild();
if (first.getType() == Token.NAME &&
first.getString().equals("undefined"))
child = last;
else if (last.getType() == Token.NAME &&
last.getString().equals("undefined"))
child = first;
}
}
if (child.getType() == Token.GETPROP)
child.setType(Token.GETPROPNOWARN);
break;
}
case Token.NAME:
case Token.SETNAME:
case Token.SETCONST:
case Token.DELPROP:
{
// Turn name to var for faster access if possible
if (createScopeObjects) {
break;
}
Node nameSource;
if (type == Token.NAME) {
nameSource = node;
} else {
nameSource = node.getFirstChild();
if (nameSource.getType() != Token.BINDNAME) {
if (type == Token.DELPROP) {
break;
}
throw Kit.codeBug();
}
}
if (nameSource.getScope() != null) {
break; // already have a scope set
}
String name = nameSource.getString();
Node.Scope defining = scope.getDefiningScope(name);
if (defining != null) {
nameSource.setScope(defining);
if (type == Token.NAME) {
node.setType(Token.GETVAR);
} else if (type == Token.SETNAME) {
node.setType(Token.SETVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.SETCONST) {
node.setType(Token.SETCONSTVAR);
nameSource.setType(Token.STRING);
} else if (type == Token.DELPROP) {
// Local variables are by definition permanent
Node n = new Node(Token.FALSE);
node = replaceCurrent(parent, previous, node, n);
} else {
throw Kit.codeBug();
}
}
break;
}
}
transformCompilationUnit_r(tree, node,
node instanceof Node.Scope ? (Node.Scope)node : scope,
createScopeObjects);
}
}
|
diff --git a/WhereAreYou/src/main/java/com/snot/whereareyou/HistoryListFragment.java b/WhereAreYou/src/main/java/com/snot/whereareyou/HistoryListFragment.java
index 4ef6316..8baa75b 100644
--- a/WhereAreYou/src/main/java/com/snot/whereareyou/HistoryListFragment.java
+++ b/WhereAreYou/src/main/java/com/snot/whereareyou/HistoryListFragment.java
@@ -1,111 +1,110 @@
package com.snot.whereareyou;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.snot.whereareyou.database.History;
import com.snot.whereareyou.database.Provider;
import java.util.Date;
// TODO:
// swipe to dismiss
// delete entire hist
public class HistoryListFragment extends ListFragment {
public HistoryListFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getActivity();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2,
null,
new String[] { History.COL_PHONE_NUMBER, History.COL_TIMESTAMP },
new int[] { android.R.id.text1, android.R.id.text2 },
0) {
@Override
public View getView(int position, View view, ViewGroup parent)
{
View row = super.getView(position, view, parent);
TextView text1 = (TextView)row.findViewById(android.R.id.text1);
TextView text2 = (TextView)row.findViewById(android.R.id.text2);
Cursor c = getCursor();
c.moveToPosition(position);
String phoneNumber = c.getString(c.getColumnIndex(History.COL_PHONE_NUMBER));
long timeStamp = c.getLong(c.getColumnIndex(History.COL_TIMESTAMP));
String name = MainActivity.getContactName(context, phoneNumber);
text1.setText(name);
Date date = new java.util.Date((long)timeStamp*1000);
text2.setText(date.toString());
return row;
}
};
setListAdapter(adapter);
// Load the content
getLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
- // TODO: order by ts
String sortOrder = History.COL_TIMESTAMP + " DESC";
return new CursorLoader(getActivity(), Provider.URI_HISTORYS, History.FIELDS, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(null);
}
});
}
@Override
public void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
// get cursor
Cursor c = ((SimpleCursorAdapter)list.getAdapter()).getCursor();
// move to the desired position
c.moveToPosition(position);
// pass it to our history object
History history = new History(c);
// create geo uri
Uri uri = Uri.parse("geo:0,0?q=" + history.latitude + "," + history.longitude + "&z=10");
// create intent
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// launch intent
startActivity(intent);
}
// @Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// super.onCreateOptionsMenu(menu, inflater);
// inflater.inflate(R.menu.exercise_list, menu);
// }
}
| true | true |
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getActivity();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2,
null,
new String[] { History.COL_PHONE_NUMBER, History.COL_TIMESTAMP },
new int[] { android.R.id.text1, android.R.id.text2 },
0) {
@Override
public View getView(int position, View view, ViewGroup parent)
{
View row = super.getView(position, view, parent);
TextView text1 = (TextView)row.findViewById(android.R.id.text1);
TextView text2 = (TextView)row.findViewById(android.R.id.text2);
Cursor c = getCursor();
c.moveToPosition(position);
String phoneNumber = c.getString(c.getColumnIndex(History.COL_PHONE_NUMBER));
long timeStamp = c.getLong(c.getColumnIndex(History.COL_TIMESTAMP));
String name = MainActivity.getContactName(context, phoneNumber);
text1.setText(name);
Date date = new java.util.Date((long)timeStamp*1000);
text2.setText(date.toString());
return row;
}
};
setListAdapter(adapter);
// Load the content
getLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO: order by ts
String sortOrder = History.COL_TIMESTAMP + " DESC";
return new CursorLoader(getActivity(), Provider.URI_HISTORYS, History.FIELDS, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(null);
}
});
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getActivity();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2,
null,
new String[] { History.COL_PHONE_NUMBER, History.COL_TIMESTAMP },
new int[] { android.R.id.text1, android.R.id.text2 },
0) {
@Override
public View getView(int position, View view, ViewGroup parent)
{
View row = super.getView(position, view, parent);
TextView text1 = (TextView)row.findViewById(android.R.id.text1);
TextView text2 = (TextView)row.findViewById(android.R.id.text2);
Cursor c = getCursor();
c.moveToPosition(position);
String phoneNumber = c.getString(c.getColumnIndex(History.COL_PHONE_NUMBER));
long timeStamp = c.getLong(c.getColumnIndex(History.COL_TIMESTAMP));
String name = MainActivity.getContactName(context, phoneNumber);
text1.setText(name);
Date date = new java.util.Date((long)timeStamp*1000);
text2.setText(date.toString());
return row;
}
};
setListAdapter(adapter);
// Load the content
getLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sortOrder = History.COL_TIMESTAMP + " DESC";
return new CursorLoader(getActivity(), Provider.URI_HISTORYS, History.FIELDS, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
((SimpleCursorAdapter) getListAdapter()).swapCursor(null);
}
});
}
|
diff --git a/cube-common/src/main/java/ch/admin/vbs/cube/common/container/impl/DmcryptContainerFactory.java b/cube-common/src/main/java/ch/admin/vbs/cube/common/container/impl/DmcryptContainerFactory.java
index 3a2f31f..0404a5a 100644
--- a/cube-common/src/main/java/ch/admin/vbs/cube/common/container/impl/DmcryptContainerFactory.java
+++ b/cube-common/src/main/java/ch/admin/vbs/cube/common/container/impl/DmcryptContainerFactory.java
@@ -1,161 +1,169 @@
/**
* Copyright (C) 2011 / cube-team <https://cube.forge.osor.eu>
*
* 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 ch.admin.vbs.cube.common.container.impl;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.admin.vbs.cube.common.CubeCommonProperties;
import ch.admin.vbs.cube.common.container.Container;
import ch.admin.vbs.cube.common.container.ContainerException;
import ch.admin.vbs.cube.common.container.IContainerFactory;
import ch.admin.vbs.cube.common.container.SizeFormatUtil;
import ch.admin.vbs.cube.common.keyring.EncryptionKey;
import ch.admin.vbs.cube.common.shell.ScriptUtil;
import ch.admin.vbs.cube.common.shell.ShellUtil;
import ch.admin.vbs.cube.common.shell.ShellUtilException;
/**
* This class implements IContainerFactory. It use DM-Crypt tools (Linux) to
* create, mount and unmount encrypted containers. This class use several Perl
* scripts to perform the necessary system operations. The use of scripts ensure
* performance (command line execution is slow in Java) and flexibility.
*
* All cube scripts are located in a central directory (default
* /opt/cube/client/scripts) and some need 'sudo' rights (see documentation).
*/
public class DmcryptContainerFactory implements IContainerFactory {
/** Logger */
private static final Logger LOG = LoggerFactory.getLogger(DmcryptContainerFactory.class);
private ScriptUtil su = new ScriptUtil();
/** Cleanup remaining open containers. */
public static void cleanup() {
try {
File varDir = new File(CubeCommonProperties.getProperty("cube.scripts.dir") + "/../var/");
if (!varDir.exists()) {
LOG.debug("Cleanup skipped. Directory [{}] does not exist", varDir.getAbsolutePath());
return;
}
LOG.debug("Cleanup remaining containers.");
for (File lock : varDir.listFiles()) {
// remove unused locks
if (lock.getName().endsWith(".last")) {
} else {
LOG.debug("Try to unmount container [{}]", lock.getName());
Properties p = new Properties();
try {
FileInputStream is = new FileInputStream(lock);
p.load(is);
is.close();
//
Container c = new Container();
c.setContainerFile(new File(p.getProperty("file")));
c.setMountpoint(new File(p.getProperty("mountpoint")));
c.setId("n/a");
DmcryptContainerFactory f = new DmcryptContainerFactory();
f.unmountContainer(c);
} catch (Exception e) {
LOG.error("Failed to unlock [" + lock.getAbsolutePath() + "]", e);
+ } finally {
+ if (lock.exists()) {
+ try {
+ lock.delete();
+ } catch (Exception e) {
+ LOG.error("Failed to unlock [" + lock.getAbsolutePath() + "]", e);
+ }
+ }
}
}
}
} catch (Exception e) {
LOG.error("Failed to cleanup", e);
}
}
@Override
public void createContainer(Container container, EncryptionKey key) throws ContainerException {
try {
LOG.debug("Create container [{}] (could take some time)", SizeFormatUtil.format(container.getSize()));
ShellUtil shell = su.execute("sudo", "./dmcrypt-create-container.pl", "-f", container.getContainerFile().getAbsolutePath(), "-k", key.getFile()
.getAbsolutePath(), "-s", "" + container.getSize());
if (shell.getExitValue() != 0) {
// Handle sudo errors with a custom log message in order to help
// the administrator to find that its sudo configuration smells.
if (shell.getStandardError().indexOf("sudo: no tty present and no askpass program specified") >= 0) {
LOG.error("SUDO is not correctly configured: It ask a password (interactive) in order to execute the script. Edit your sudoer file (-> visudo).");
}
throw new ShellUtilException("Script returned an error [" + shell.getExitValue() + "]");
}
} catch (Exception e) {
throw new ContainerException("Failed to execute script", e);
}
}
@Override
public void deleteContainer(Container container) throws ContainerException {
try {
LOG.debug("Delete container..");
ShellUtil s = su.execute("sudo", "./dmcrypt-delete-container.pl", "-f", container.getContainerFile().getAbsolutePath(), "-m", container
.getMountpoint().getAbsolutePath());
if (s.getExitValue() != 0) {
LOG.error("stdout:\n" + s.getStandardOutput().toString());
LOG.error("stderr:\n" + s.getStandardError().toString());
throw new RuntimeException("script returned a non-zero code [" + s.getExitValue() + "]");
}
} catch (ShellUtilException e) {
throw new ContainerException("Could not delete container [" + container + "]", e);
}
}
@Override
public void mountContainer(Container container, EncryptionKey key) throws ContainerException {
try {
ShellUtil s = su.execute("sudo", "./dmcrypt-mount-container.pl", "-f", container.getContainerFile().getAbsolutePath(), "-k", key.getFile()
.getAbsolutePath(), "-m", container.getMountpoint().getAbsolutePath());
if (s.getExitValue() == 0) {
LOG.debug("Container successfully mounted");
} else {
// try to unmount / remount the container
LOG.debug("Failed to mount the container at the first attempt. Try to unmount/remount it");
try {
unmountContainer(container);
} catch (Exception e) {
}
s = su.execute("sudo", "./dmcrypt-mount-container.pl", "-f", container.getContainerFile().getAbsolutePath(), "-k", key.getFile()
.getAbsolutePath(), "-m", container.getMountpoint().getAbsolutePath());
}
if (s.getExitValue() != 0) {
LOG.error("standard output:\n" + s.getStandardOutput());
LOG.error("standard error:\n" + s.getStandardError());
throw new RuntimeException("Mounting container failed [" + s.getExitValue() + "]");
}
} catch (Exception e) {
throw new ContainerException("Could not mount container [" + container + "]", e);
}
}
@Override
public void unmountContainer(Container container) throws ContainerException {
try {
LOG.debug("Unmount container..");
ShellUtil s = su.execute("sudo", "./dmcrypt-unmount-container.pl", "-f", container.getContainerFile().getAbsolutePath(), "-m", container
.getMountpoint().getAbsolutePath());
if (s.getExitValue() != 0) {
throw new RuntimeException("script returned a non-zero code [" + s.getExitValue() + "]");
}
} catch (Exception e) {
throw new ContainerException("Could not unmount container [" + container + "]", e);
}
}
}
| true | true |
public static void cleanup() {
try {
File varDir = new File(CubeCommonProperties.getProperty("cube.scripts.dir") + "/../var/");
if (!varDir.exists()) {
LOG.debug("Cleanup skipped. Directory [{}] does not exist", varDir.getAbsolutePath());
return;
}
LOG.debug("Cleanup remaining containers.");
for (File lock : varDir.listFiles()) {
// remove unused locks
if (lock.getName().endsWith(".last")) {
} else {
LOG.debug("Try to unmount container [{}]", lock.getName());
Properties p = new Properties();
try {
FileInputStream is = new FileInputStream(lock);
p.load(is);
is.close();
//
Container c = new Container();
c.setContainerFile(new File(p.getProperty("file")));
c.setMountpoint(new File(p.getProperty("mountpoint")));
c.setId("n/a");
DmcryptContainerFactory f = new DmcryptContainerFactory();
f.unmountContainer(c);
} catch (Exception e) {
LOG.error("Failed to unlock [" + lock.getAbsolutePath() + "]", e);
}
}
}
} catch (Exception e) {
LOG.error("Failed to cleanup", e);
}
}
|
public static void cleanup() {
try {
File varDir = new File(CubeCommonProperties.getProperty("cube.scripts.dir") + "/../var/");
if (!varDir.exists()) {
LOG.debug("Cleanup skipped. Directory [{}] does not exist", varDir.getAbsolutePath());
return;
}
LOG.debug("Cleanup remaining containers.");
for (File lock : varDir.listFiles()) {
// remove unused locks
if (lock.getName().endsWith(".last")) {
} else {
LOG.debug("Try to unmount container [{}]", lock.getName());
Properties p = new Properties();
try {
FileInputStream is = new FileInputStream(lock);
p.load(is);
is.close();
//
Container c = new Container();
c.setContainerFile(new File(p.getProperty("file")));
c.setMountpoint(new File(p.getProperty("mountpoint")));
c.setId("n/a");
DmcryptContainerFactory f = new DmcryptContainerFactory();
f.unmountContainer(c);
} catch (Exception e) {
LOG.error("Failed to unlock [" + lock.getAbsolutePath() + "]", e);
} finally {
if (lock.exists()) {
try {
lock.delete();
} catch (Exception e) {
LOG.error("Failed to unlock [" + lock.getAbsolutePath() + "]", e);
}
}
}
}
}
} catch (Exception e) {
LOG.error("Failed to cleanup", e);
}
}
|
diff --git a/Commander.java b/Commander.java
index 90457ca..5ba030c 100644
--- a/Commander.java
+++ b/Commander.java
@@ -1,193 +1,192 @@
/**
* Commander.java
*
* This class is designed to be to command interpreter
* and pareser. The keyword is initially parsed and
* the appropriate method is called.
*
* @author Nick DeRossi
* Group: Nick DeRossi, Tyler Janowski, Nick Grauel
*/
import java.util.*;
import java.io.*;
public class Commander
{
// instance variable
private Scanner s = null;
private People pers;
private Providers ps;
private Tours ts;
/**
* Constructor for the command processor
* Paremeter is a Scanner object
*/
public Commander( Scanner sc )
{
s = sc;
pers = new People();
ps = new Providers();
ts = new Tours();
}
/**
* Method to handle the actual keyword
* identification and parsing.
*/
public void action()
{
String input = null;
while( s.hasNext() )
{
input = s.next();
if( input.equals( "person" ) )
definePerson();
else if( input.equals( "provider" ) )
defineProvider();
else if( input.equals( "tour" ) )
defineTour();
else if( input.equals( "#" ) )
System.out.println( "#" + s.nextLine() );
else
s.nextLine();
}
System.out.println( "\nPeople:\n----------------" );
System.out.println( pers.toString() );
System.out.println( "Providers:\n---------------" );
System.out.println( ps.toString() );
System.out.println( "Tours:\n---------------" );
System.out.println( ts.toString() );
}
/**
* Method to parse and define the
* person object.
*/
public void definePerson()
{
Person p = null;
String type = s.next();
String name = s.next();
int age = s.nextInt();
String gender = s.next();
int fitLevel = s.nextInt();
if( type.equals( "solo" ) )
p = new Solo( name, age, gender, fitLevel );
else if( type.equals( "single" ) )
p = new Single( name, age, gender, fitLevel );
else if( type.equals( "double" ) )
{
String name2 = s.next();
int age2 = s.nextInt();
String gender2 = s.next();
int f2 = s.nextInt();
Person tmp = new Single( name, age, gender, fitLevel );
p = new Double( tmp, new Single( name2, age2, gender2, f2 ) );
}
else
System.out.println( "Invalid person type!" );
pers.insertPerson( p );
s.nextLine();
}
/**
* method to define a provider object
* according to the file input
*/
public void defineProvider()
{
String serv = s.next();
String name = s.next();
String location = s.next();
int cap = s.nextInt();
int opTime = s.nextInt();
int clTime = s.nextInt();
int secs = opTime%100;
opTime = opTime/100;
int hours = opTime%100;
GregorianCalendar op = new GregorianCalendar( 2011, 11, 10, hours, secs );
secs = clTime%100;
clTime = clTime/100;
hours = clTime%100;
GregorianCalendar cl = new GregorianCalendar( 2011, 11, 10, hours, secs );
Provider p = new Provider( name, serv, location, op, cl, cap );
ps.addProvider( p );
}
/**
* Method to handle the parsing and
* declaration of a Tour object
*/
public void defineTour()
{
Tour t = null;
Event e = null;
String comp = s.next();
String id = s.next();
String startLoc = s.next();
String endLoc = s.next();
int days = s.nextInt();
int fit = s.nextInt();
int cap = s.nextInt();
int sT = 0;
int eT = 0;
int hours = 0;
int secs = 0;
s.nextLine();
- s.nextLine();
t = new Tour( comp, id, startLoc, endLoc, cap, days, fit );
for( int i = 0; i<days; i++ )
{
- while( s.next().equals( "event" ) )
+ while( s.hasNext() && s.next().equals( "event" ) )
{
String tmp = s.next();
if( tmp.equals( "travel" ) )
{
String mode = s.next();
startLoc = s.next();
endLoc = s.next();
sT = s.nextInt();
eT = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new TravelEvent( mode, startLoc, endLoc, s, end, i+1 );
}
else
{
String act = s.next();
sT = s.nextInt();
eT = s.nextInt();
fit = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
sT = sT/100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new ActivityEvent( act, s, end, fit, i+1 );
}
t.addEvent( e );
s.nextLine();
}
s.nextLine();
}
ts.add( t );
}
}
| false | true |
public void defineTour()
{
Tour t = null;
Event e = null;
String comp = s.next();
String id = s.next();
String startLoc = s.next();
String endLoc = s.next();
int days = s.nextInt();
int fit = s.nextInt();
int cap = s.nextInt();
int sT = 0;
int eT = 0;
int hours = 0;
int secs = 0;
s.nextLine();
s.nextLine();
t = new Tour( comp, id, startLoc, endLoc, cap, days, fit );
for( int i = 0; i<days; i++ )
{
while( s.next().equals( "event" ) )
{
String tmp = s.next();
if( tmp.equals( "travel" ) )
{
String mode = s.next();
startLoc = s.next();
endLoc = s.next();
sT = s.nextInt();
eT = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new TravelEvent( mode, startLoc, endLoc, s, end, i+1 );
}
else
{
String act = s.next();
sT = s.nextInt();
eT = s.nextInt();
fit = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
sT = sT/100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new ActivityEvent( act, s, end, fit, i+1 );
}
t.addEvent( e );
s.nextLine();
}
s.nextLine();
}
ts.add( t );
}
|
public void defineTour()
{
Tour t = null;
Event e = null;
String comp = s.next();
String id = s.next();
String startLoc = s.next();
String endLoc = s.next();
int days = s.nextInt();
int fit = s.nextInt();
int cap = s.nextInt();
int sT = 0;
int eT = 0;
int hours = 0;
int secs = 0;
s.nextLine();
t = new Tour( comp, id, startLoc, endLoc, cap, days, fit );
for( int i = 0; i<days; i++ )
{
while( s.hasNext() && s.next().equals( "event" ) )
{
String tmp = s.next();
if( tmp.equals( "travel" ) )
{
String mode = s.next();
startLoc = s.next();
endLoc = s.next();
sT = s.nextInt();
eT = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new TravelEvent( mode, startLoc, endLoc, s, end, i+1 );
}
else
{
String act = s.next();
sT = s.nextInt();
eT = s.nextInt();
fit = s.nextInt();
secs = sT%100;
sT = sT/100;
hours = sT%100;
sT = sT/100;
GregorianCalendar s = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
secs = eT%100;
eT = eT/100;
hours = eT%100;
GregorianCalendar end = new GregorianCalendar( 2011, 11, 10+i, hours, secs );
e = new ActivityEvent( act, s, end, fit, i+1 );
}
t.addEvent( e );
s.nextLine();
}
s.nextLine();
}
ts.add( t );
}
|
diff --git a/jgsf/src/main/java/com/jenjinstudios/net/Server.java b/jgsf/src/main/java/com/jenjinstudios/net/Server.java
index a34a1d3c..4b1d4cc7 100755
--- a/jgsf/src/main/java/com/jenjinstudios/net/Server.java
+++ b/jgsf/src/main/java/com/jenjinstudios/net/Server.java
@@ -1,213 +1,213 @@
package com.jenjinstudios.net;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The base Server class for implementation of the JGSA. It contains extensible execution functionality designed to be
* used by Executable Messages from ClientHandlers.
* @author Caleb Brinkman
*/
@SuppressWarnings("SameParameterValue")
public class Server<T extends ClientHandler> extends Thread
{
/** The default number of max clients. */
public static final int DEFAULT_MAX_CLIENTS = 100;
/** The logger used by this class. */
static final Logger LOGGER = Logger.getLogger(Server.class.getName());
/** The number of milliseconds before a blocking method should time out. */
public static long TIMEOUT_MILLIS = 30000;
/** The updates per second. */
public final int UPS;
/** The period of the update in milliseconds. */
public final int PERIOD;
/** The list of {@code ClientListener}s working for this server. */
private final ClientListener<T> clientListener;
/** The list of {@code ClientHandler}s working for this server. */
private final ArrayList<T> clientHandlers;
/** The map of clients stored by username. */
private final TreeMap<String, T> clientsByUsername;
/** Indicates whether this server is initialized. */
private volatile boolean initialized;
/** The current number of connected clients. */
private int numClients;
/**
* Construct a new Server without a SQLHandler.
* @param ups The cycles per second at which this server will run.
* @param port The port number on which this server will listen.
* @param handlerClass The class of ClientHandler used by this Server.
* @throws java.io.IOException If there is an IO Error initializing the server.
* @throws NoSuchMethodException If there is no appropriate constructor for the specified ClientHandler constructor.
*/
public Server(int ups, int port, Class<? extends T> handlerClass) throws IOException, NoSuchMethodException {
this(ups, port, handlerClass, DEFAULT_MAX_CLIENTS);
}
/**
* Construct a new Server without a SQLHandler.
* @param ups The cycles per second at which this server will run.
* @param port The port number on which this server will listen.
* @param handlerClass The class of ClientHandler used by this Server.
* @param maxClients The maximum number of clients.
* @throws java.io.IOException If there is an IO Error initializing the server.
* @throws NoSuchMethodException If there is no appropriate constructor for the specified ClientHandler constructor.
*/
@SuppressWarnings("unchecked")
public Server(int ups, int port, Class<? extends T> handlerClass, int maxClients) throws IOException, NoSuchMethodException {
super("Server");
LOGGER.log(Level.FINE, "Initializing Server.");
UPS = ups;
PERIOD = 1000 / ups;
clientsByUsername = new TreeMap<>();
clientListener = (ClientListener<T>) new ClientListener<>(this, port, handlerClass);
clientHandlers = new ArrayList<>();
for (int i = 0; i < maxClients; i++)
clientHandlers.add(null);
numClients = 0;
}
/**
* Schedule a client to be removed during the next update.
* @param handler The client handler to be removed.
*/
void removeClient(ClientHandler handler) {
synchronized (clientHandlers)
{
String username = handler.getUsername();
if (username != null) { clientsByUsername.remove(username); }
clientHandlers.set(handler.getHandlerId(), null);
numClients--;
}
}
/**
* Add new clients that have connected to the client listeners.
* @return true if new clients were added.
*/
public boolean getNewClients() {
boolean clientsAdded;
LinkedList<T> nc = clientListener.getNewClients();
clientsAdded = !nc.isEmpty();
for (T h : nc)
{
int nullIndex = clientHandlers.indexOf(null);
clientHandlers.set(nullIndex, h);
h.setID(nullIndex);
h.start();
numClients++;
}
return clientsAdded;
}
/** Broadcast all outgoing messages to clients. */
public void broadcast() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.sendAllMessages(); }
}
}
}
/** Update all clients before they sendAllMessages. */
public void update() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.update(); }
}
}
}
/** Refresh all clients after they sendAllMessages. */
public void refresh() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.refresh(); }
}
}
}
/** Run the server. */
@Override
public void run() {
clientListener.listen();
initialized = true;
}
/**
* Start the server, and do not return until it is fully initialized.
* @return If the blocking start was successful.
*/
public final boolean blockingStart() {
long startTime = System.currentTimeMillis();
long timepast = System.currentTimeMillis() - startTime;
start();
while (!initialized && (timepast < TIMEOUT_MILLIS))
{
- try // TODO make sure error is handled gracefully
+ try
{
Thread.sleep(10);
timepast = System.currentTimeMillis() - startTime;
} catch (InterruptedException e)
{
- LOGGER.log(Level.WARNING, "Issue with server blockingStart", e);
+ LOGGER.log(Level.WARNING, "Server blocking start was interrupted.", e);
}
}
return initialized;
}
/**
* Shutdown the server, forcing all client links to close.
* @throws IOException if there is an error shutting down a client.
*/
public void shutdown() throws IOException {
synchronized (clientHandlers)
{
for (ClientHandler h : clientHandlers)
{
if (h != null) { h.shutdown(); }
}
}
clientListener.stopListening();
}
/**
* Return whether this server is initialized.
* @return true if the server has been initialized.
*/
public boolean isInitialized() { return initialized; }
/**
* Get the ClientHandler with the given username.
* @param username The username of the client to look up.
* @return The client with the username specified; null if there is no client with this username.
*/
public T getClientHandlerByUsername(String username) { return clientsByUsername.get(username); }
/**
* Called by ClientHandler when the client sets a username.
* @param username The username assigned to the ClientHandler.
* @param handler The ClientHandler that has had a username set.
*/
@SuppressWarnings("unchecked")
void clientUsernameSet(String username, ClientHandler handler) { clientsByUsername.put(username, (T) handler); }
/**
* Get the current number of connected clients.
* @return The current number of connected clients.
*/
public int getNumClients() {
return numClients;
}
}
| false | true |
public final boolean blockingStart() {
long startTime = System.currentTimeMillis();
long timepast = System.currentTimeMillis() - startTime;
start();
while (!initialized && (timepast < TIMEOUT_MILLIS))
{
try // TODO make sure error is handled gracefully
{
Thread.sleep(10);
timepast = System.currentTimeMillis() - startTime;
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Issue with server blockingStart", e);
}
}
return initialized;
}
|
public final boolean blockingStart() {
long startTime = System.currentTimeMillis();
long timepast = System.currentTimeMillis() - startTime;
start();
while (!initialized && (timepast < TIMEOUT_MILLIS))
{
try
{
Thread.sleep(10);
timepast = System.currentTimeMillis() - startTime;
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Server blocking start was interrupted.", e);
}
}
return initialized;
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java
index 726ea310..82c96362 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java
@@ -1,1208 +1,1209 @@
/*
* Copyright (C) 2011-2012 asksven
*
* 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.asksven.betterbatterystats;
/**
* @author sven
*
*/
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.asksven.android.common.AppRater;
import com.asksven.android.common.CommonLogSettings;
import com.asksven.android.common.ReadmeActivity;
import com.asksven.android.common.RootShell;
import com.asksven.android.common.utils.DataStorage;
import com.asksven.android.common.utils.DateUtils;
import com.asksven.android.common.utils.SysUtils;
import com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException;
import com.asksven.android.common.privateapiproxies.BatteryStatsProxy;
import com.asksven.betterbatterystats.R;
import com.asksven.betterbatterystats.adapters.ReferencesAdapter;
import com.asksven.betterbatterystats.adapters.StatsAdapter;
import com.asksven.betterbatterystats.data.GoogleAnalytics;
import com.asksven.betterbatterystats.data.Reading;
import com.asksven.betterbatterystats.data.Reference;
import com.asksven.betterbatterystats.data.ReferenceDBHelper;
import com.asksven.betterbatterystats.data.ReferenceStore;
import com.asksven.betterbatterystats.data.StatsProvider;
import com.asksven.betterbatterystats.services.EventWatcherService;
import com.asksven.betterbatterystats.services.WriteCurrentReferenceService;
import com.asksven.betterbatterystats.services.WriteCustomReferenceService;
import com.asksven.betterbatterystats.services.WriteScreenOffReferenceService;
import com.asksven.betterbatterystats.services.WriteUnpluggedReferenceService;
import com.asksven.betterbatterystats.services.WriteBootReferenceService;
public class StatsActivity extends ListActivity implements AdapterView.OnItemSelectedListener, OnSharedPreferenceChangeListener
{
public static String STAT = "STAT";
public static String STAT_TYPE_FROM = "STAT_TYPE_FROM";
public static String STAT_TYPE_TO = "STAT_TYPE_TO";
public static String FROM_NOTIFICATION = "FROM_NOTIFICATION";
/**
* The logging TAG
*/
private static final String TAG = "StatsActivity";
/**
* The logfile TAG
*/
private static final String LOGFILE = "BetterBatteryStats_Dump.log";
/**
* a progess dialog to be used for long running tasks
*/
ProgressDialog m_progressDialog;
/**
* The ArrayAdpater for rendering the ListView
*/
private StatsAdapter m_listViewAdapter;
private ReferencesAdapter m_spinnerFromAdapter;
private ReferencesAdapter m_spinnerToAdapter;
/**
* The Type of Stat to be displayed (default is "Since charged")
*/
// private int m_iStatType = 0;
private String m_refFromName = "";
private String m_refToName = Reference.CURRENT_REF_FILENAME;
/**
* The Stat to be displayed (default is "Process")
*/
private int m_iStat = 0;
/**
* the selected sorting
*/
private int m_iSorting = 0;
private BroadcastReceiver m_referenceSavedReceiver = null;
/**
* @see android.app.Activity#onCreate(Bundle@SuppressWarnings("rawtypes")
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "OnCreated called");
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// set debugging
if (sharedPrefs.getBoolean("debug_logging", false))
{
LogSettings.DEBUG=true;
CommonLogSettings.DEBUG=true;
}
else
{
LogSettings.DEBUG=false;
CommonLogSettings.DEBUG=false;
}
///////////////////////////////////////////////
// check if we have a new release
///////////////////////////////////////////////
// if yes do some migration (if required) and show release notes
String strLastRelease = sharedPrefs.getString("last_release", "0");
String strCurrentRelease = "";
try
{
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
strCurrentRelease = Integer.toString(pinfo.versionCode);
}
catch (Exception e)
{
// nop strCurrentRelease is set to ""
}
// if root is available use it
boolean hasRoot = sharedPrefs.getBoolean("root_features", false);
+ boolean ignoreSystemApp = sharedPrefs.getBoolean("ignore_system_app", false);
if (!hasRoot && (RootShell.getInstance().rooted()))
{
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putBoolean("root_features", true);
updater.commit();
hasRoot = sharedPrefs.getBoolean("root_features", false);
}
// show install as system app screen if root available but perms missing
- if (hasRoot && !SysUtils.hasBatteryStatsPermission(this))
+ if (!ignoreSystemApp && hasRoot && !SysUtils.hasBatteryStatsPermission(this))
{
Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_PREFERENCES);
this.startActivity(intentSystemApp);
}
// first start
if (strLastRelease.equals("0"))
{
// show the initial run screen
FirstLaunch.app_launched(this);
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
}
else if (!strLastRelease.equals(strCurrentRelease))
{
// save the current release to properties so that the dialog won't be shown till next version
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show();
ReferenceStore.deleteAllRefs(this);
Intent i = new Intent(this, WriteBootReferenceService.class);
this.startService(i);
i = new Intent(this, WriteUnpluggedReferenceService.class);
this.startService(i);
}
else
{
// can't do this at the same time as the popup dialog would be masked by the readme
///////////////////////////////////////////////
// check if we have shown the opt-out from analytics
///////////////////////////////////////////////
boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false);
boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true);
if (bAnalyticsEnabled && !bWarningShown)
{
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\"");
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1)
{
// opt out info was displayed
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("analytics_opt_out", true);
editor.commit();
}
});
// show it
alertbox.show();
}
else
{
// show "rate" dialog
// for testing: AppRater.showRateDialog(this, null);
AppRater.app_launched(this);
}
}
///////////////////////////////////////////////
// retrieve default selections for spinners
// if none were passed
///////////////////////////////////////////////
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
if (!ReferenceStore.hasReferenceByName(m_refFromName, this))
{
if (sharedPrefs.getBoolean("fallback_to_since_boot", false))
{
m_refFromName = Reference.BOOT_REF_FILENAME;
Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show();
}
}
try
{
// recover any saved state
if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty()))
{
m_iStat = (Integer) savedInstanceState.getSerializable("stat");
m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
}
}
catch (Exception e)
{
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
Log.e(TAG, "Exception: " + e.getMessage());
DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
DataStorage.LogToFile(LOGFILE, e.getMessage());
DataStorage.LogToFile(LOGFILE, e.getStackTrace());
Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show();
}
// Handle the case the Activity was called from an intent with paramaters
Bundle extras = getIntent().getExtras();
if (extras != null)
{
// Override if some values were passed to the intent
m_iStat = extras.getInt(StatsActivity.STAT);
m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
// Clear the notifications that was clicked to call the activity
if (bCalledFromNotification)
{
NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
nM.cancel(EventWatcherService.NOTFICATION_ID);
}
}
// Display the reference of the stat
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
if (tvSince != null)
{
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
}
// Spinner for selecting the stat
Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(
this, R.array.stats, android.R.layout.simple_spinner_item);
spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStat.setAdapter(spinnerStatAdapter);
// setSelection MUST be called after setAdapter
spinnerStat.setSelection(m_iStat);
spinnerStat.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the Stat type
///////////////////////////////////////////////
Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStatType.setAdapter(m_spinnerFromAdapter);
try
{
this.setListViewAdapter();
}
catch (BatteryInfoUnavailableException e)
{
// Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
//Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"An unhandled error occured. Please check your logcat",
Toast.LENGTH_LONG).show();
}
// setSelection MUST be called after setAdapter
spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
spinnerStatType.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the end sample
///////////////////////////////////////////////
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
if ((m_refToName != null) && !m_refToName.equals("") )
{
int pos = m_spinnerToAdapter.getPosition(m_refToName);
spinnerStatSampleEnd.setSelection(pos);
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
spinnerStatSampleEnd.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// sorting
///////////////////////////////////////////////
String strOrderBy = sharedPrefs.getString("default_orderby", "0");
try
{
m_iSorting = Integer.valueOf(strOrderBy);
}
catch(Exception e)
{
// handle error here
m_iSorting = 0;
}
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
// Set up a listener whenever a key changes
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
// log reference store
ReferenceStore.logReferences(this);
}
/* Request updates at startup */
@Override
protected void onResume()
{
Log.i(TAG, "OnResume called");
super.onResume();
// register the broadcast receiver
IntentFilter intentFilter = new IntentFilter(ReferenceStore.REF_UPDATED);
m_referenceSavedReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
//extract our message from intent
String refName = intent.getStringExtra(Reference.EXTRA_REF_NAME);
//log our message value
Log.i(TAG, "Received broadcast, reference was updated:" + refName);
// reload the spinners to make sure all refs are in the right sequence when current gets refreshed
// if (refName.equals(Reference.CURRENT_REF_FILENAME))
// {
refreshSpinners();
// }
}
};
//registering our receiver
this.registerReceiver(m_referenceSavedReceiver, intentFilter);
// the service is always started as it handles the widget updates too
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean serviceShouldBeRunning = sharedPrefs.getBoolean("ref_for_screen_off", false);
// we need to run the service also if we are on kitkat without root
boolean rootEnabled = sharedPrefs.getBoolean("root_features", false);
// if on kitkat make sure that we always collect screen on time: if no root then count the time
if ( !rootEnabled && !SysUtils.hasBatteryStatsPermission(this) )
{
serviceShouldBeRunning = true;
}
if (serviceShouldBeRunning)
{
if (!EventWatcherService.isServiceRunning(this))
{
Intent i = new Intent(this, EventWatcherService.class);
this.startService(i);
}
}
// make sure to create a valid "current" stat if none exists
// or if prefs re set to auto refresh
boolean bAutoRefresh = sharedPrefs.getBoolean("auto_refresh", true);
if ((bAutoRefresh) || (!ReferenceStore.hasReferenceByName(Reference.CURRENT_REF_FILENAME, this)))
{
Intent serviceIntent = new Intent(this, WriteCurrentReferenceService.class);
this.startService(serviceIntent);
doRefresh(true);
}
else
{
refreshSpinners();
doRefresh(false);
}
// check if active monitoring is on: if yes make sure the alarm is scheduled
if (sharedPrefs.getBoolean("active_mon_enabled", false))
{
if (!StatsProvider.isActiveMonAlarmScheduled(this))
{
StatsProvider.scheduleActiveMonAlarm(this);
}
}
}
/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause()
{
super.onPause();
// unregister boradcast receiver for saved references
this.unregisterReceiver(this.m_referenceSavedReceiver);
// make sure to dispose any running dialog
if (m_progressDialog != null)
{
m_progressDialog.dismiss();
m_progressDialog = null;
}
// this.unregisterReceiver(m_batteryHandler);
}
/**
* Save state, the application is going to get moved out of memory
* @see http://stackoverflow.com/questions/151777/how-do-i-save-an-android-applications-state
*/
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putSerializable("stattypeFrom", m_refFromName);
savedInstanceState.putSerializable("stattypeTo", m_refToName);
savedInstanceState.putSerializable("stat", m_iStat);
//StatsProvider.getInstance(this).writeToBundle(savedInstanceState);
}
/**
* Add menu items
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
boolean bSortingEnabled = true;
MenuItem sortCount = menu.findItem(R.id.by_count_desc);
MenuItem sortTime = menu.findItem(R.id.by_time_desc);
if (m_iSorting == 0)
{
// sorting is by time
sortTime.setEnabled(false);
sortCount.setEnabled(true);
}
else
{
// sorting is by count
sortTime.setEnabled(true);
sortCount.setEnabled(false);
}
if (m_iStat == 2) // @see arrays.xml, dependency to string-array name="stats"
{
// disable menu group
bSortingEnabled = true;
}
else
{
// enable menu group
bSortingEnabled = true;
}
menu.setGroupEnabled(R.id.sorting_group, bSortingEnabled);
return true;
}
/**
* Define menu action
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.preferences:
Intent intentPrefs = new Intent(this, PreferencesActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_PREFERENCES);
this.startActivity(intentPrefs);
break;
case R.id.graph:
Intent intentGraph = new Intent(this, BatteryGraphActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_BATTERY_GRAPH);
this.startActivity(intentGraph);
break;
case R.id.rawstats:
Intent intentRaw = new Intent(this, RawStatsActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_RAW);
this.startActivity(intentRaw);
break;
case R.id.refresh:
// Refresh
// ReferenceStore.rebuildCache(this);
doRefresh(true);
break;
case R.id.custom_ref:
// Set custom reference
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTION_SET_CUSTOM_REF);
// start service to persist reference
Intent serviceIntent = new Intent(this, WriteCustomReferenceService.class);
this.startService(serviceIntent);
break;
case R.id.credits:
Intent intentCredits = new Intent(this, CreditsActivity.class);
this.startActivity(intentCredits);
break;
case R.id.by_time_desc:
// Enable "count" option
m_iSorting = 0;
doRefresh(false);
break;
case R.id.by_count_desc:
// Enable "count" option
m_iSorting = 1;
doRefresh(false);
break;
// case R.id.test:
// Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
// this.startService(serviceIntent);
// break;
case R.id.about:
// About
Intent intentAbout = new Intent(this, AboutActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_ABOUT);
this.startActivity(intentAbout);
break;
case R.id.getting_started:
// Help
Intent intentHelp = new Intent(this, HelpActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_HELP);
intentHelp.putExtra("filename", "help.html");
this.startActivity(intentHelp);
break;
case R.id.howto:
// How To
Intent intentHowTo = new Intent(this, HelpActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_HOWTO);
intentHowTo.putExtra("filename", "howto.html");
this.startActivity(intentHowTo);
break;
case R.id.releasenotes:
// Release notes
Intent intentReleaseNotes = new Intent(this, ReadmeActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_README);
intentReleaseNotes.putExtra("filename", "readme.html");
this.startActivity(intentReleaseNotes);
break;
case R.id.share:
// Share
getShareDialog().show();
break;
}
return false;
}
/**
* Take the change of selection from the spinners into account and refresh the ListView
* with the right data
*/
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
// this method is fired even if nothing has changed so we nee to find that out
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean bChanged = false;
// id is in the order of the spinners, 0 is stat, 1 is stat_type
if (parent == (Spinner) findViewById(R.id.spinnerStatType))
{
// detect if something changed
String newStat = (String) ( (ReferencesAdapter) parent.getAdapter()).getItemName(position);
if ((m_refFromName != null) && ( !m_refFromName.equals(newStat) ))
{
Log.i(TAG, "Spinner from changed from " + m_refFromName + " to " + newStat);
m_refFromName = newStat;
bChanged = true;
// we need to update the second spinner
m_spinnerToAdapter.filterToSpinner(newStat, this);
m_spinnerToAdapter.notifyDataSetChanged();
// select the right element
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
if (spinnerStatSampleEnd.isShown())
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(m_refToName));
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
return;
}
}
else if (parent == (Spinner) findViewById(R.id.spinnerStatSampleEnd))
{
String newStat = (String) ( (ReferencesAdapter) parent.getAdapter()).getItemName(position);
if ((m_refFromName != null) && ( !m_refToName.equals(newStat) ))
{
Log.i(TAG, "Spinner to changed from " + m_refToName + " to " + newStat);
m_refToName = newStat;
bChanged = true;
}
else
{
return;
}
}
else if (parent == (Spinner) findViewById(R.id.spinnerStat))
{
int iNewStat = position;
if ( m_iStat != iNewStat )
{
m_iStat = iNewStat;
bChanged = true;
}
else
{
return;
}
// inform the user when he tries to use functions requiring root and he doesn't have root enabled
boolean rootEnabled = sharedPrefs.getBoolean("root_features", false);
if (!rootEnabled)
{
if ((m_iStat == 4) || (m_iStat == 3))
{
Toast.makeText(this,
"This function requires root access. Check \"Advanced\" preferences",
Toast.LENGTH_LONG).show();
}
}
}
else
{
Log.e(TAG, "ProcessStatsActivity.onItemSelected error. ID could not be resolved");
Toast.makeText(this, "Error: could not resolve what changed", Toast.LENGTH_SHORT).show();
}
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
// long sinceMs = getSince();
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a ");
Log.i(TAG, "Since: n/a ");
}
// @todo fix this: this method is called twice
//m_listViewAdapter.notifyDataSetChanged();
if (bChanged)
{
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
//new LoadStatData().execute(this);
// as the source changed fetch the data
doRefresh(false);
}
}
public void onNothingSelected(AdapterView<?> parent)
{
// Log.i(TAG, "OnNothingSelected called");
// do nothing
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
{
if (key.equals("show_to_ref"))
{
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
boolean bShowSpinner = prefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
}
}
}
private void refreshSpinners()
{
// reload the spinners to make sure all refs are in the right sequence
m_spinnerFromAdapter.refreshFromSpinner(this);
m_spinnerToAdapter.filterToSpinner(m_refFromName, this);
// after we reloaded the spinners we need to reset the selections
Spinner spinnerStatTypeFrom = (Spinner) findViewById(R.id.spinnerStatType);
Spinner spinnerStatTypeTo = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
Log.i(TAG, "refreshSpinners: reset spinner selections: from='" + m_refFromName + "', to='" + m_refToName + "'");
Log.i(TAG, "refreshSpinners Spinner values: SpinnerFrom=" + m_spinnerFromAdapter.getNames() + " SpinnerTo=" + m_spinnerToAdapter.getNames());
Log.i(TAG, "refreshSpinners: request selections: from='" + m_spinnerFromAdapter.getPosition(m_refFromName) + "', to='" + m_spinnerToAdapter.getPosition(m_refToName) + "'");
// restore positions
spinnerStatTypeFrom.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName), true);
if (spinnerStatTypeTo.isShown())
{
spinnerStatTypeTo.setSelection(m_spinnerToAdapter.getPosition(m_refToName), true);
}
else
{
spinnerStatTypeTo.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME), true);
}
Log.i(TAG, "refreshSpinners result positions: from='" + spinnerStatTypeFrom.getSelectedItemPosition() + "', to='" + spinnerStatTypeTo.getSelectedItemPosition() + "'");
if ((spinnerStatTypeTo.isShown())
&& ((spinnerStatTypeFrom.getSelectedItemPosition() == -1)||(spinnerStatTypeTo.getSelectedItemPosition() == -1)))
{
Toast.makeText(StatsActivity.this,
"Selected 'from' or 'to' reference could not be loaded. Please refresh",
Toast.LENGTH_LONG).show();
}
}
/**
* In order to refresh the ListView we need to re-create the Adapter
* (should be the case but notifyDataSetChanged doesn't work so
* we recreate and set a new one)
*/
private void setListViewAdapter() throws Exception
{
// make sure we only instanciate when the reference does not exist
if (m_listViewAdapter == null)
{
m_listViewAdapter = new StatsAdapter(this,
StatsProvider.getInstance(this).getStatList(m_iStat, m_refFromName, m_iSorting, m_refToName));
setListAdapter(m_listViewAdapter);
}
}
private void doRefresh(boolean updateCurrent)
{
if (SysUtils.hasBatteryStatsPermission(this)) BatteryStatsProxy.getInstance(this).invalidate();
refreshSpinners();
new LoadStatData().execute(updateCurrent);
}
// @see http://code.google.com/p/makemachine/source/browse/trunk/android/examples/async_task/src/makemachine/android/examples/async/AsyncTaskExample.java
// for more details
private class LoadStatData extends AsyncTask<Boolean, Integer, StatsAdapter>
{
private Exception m_exception = null;
@Override
protected StatsAdapter doInBackground(Boolean... refresh)
{
// do we need to refresh current
if (refresh[0])
{
// make sure to create a valid "current" stat
StatsProvider.getInstance(StatsActivity.this).setCurrentReference(m_iSorting);
}
//super.doInBackground(params);
m_listViewAdapter = null;
try
{
Log.i(TAG, "LoadStatData: refreshing display for stats " + m_refFromName + " to " + m_refToName);
m_listViewAdapter = new StatsAdapter(
StatsActivity.this,
StatsProvider.getInstance(StatsActivity.this).getStatList(m_iStat, m_refFromName, m_iSorting, m_refToName));
}
catch (BatteryInfoUnavailableException e)
{
//Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
m_exception = e;
}
catch (Exception e)
{
//Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
m_exception = e;
}
//StatsActivity.this.setListAdapter(m_listViewAdapter);
// getStatList();
return m_listViewAdapter;
}
// @Override
protected void onPostExecute(StatsAdapter o)
{
// super.onPostExecute(o);
// update hourglass
try
{
if (m_progressDialog != null)
{
m_progressDialog.dismiss(); //hide();
m_progressDialog = null;
}
}
catch (Exception e)
{
// nop
}
finally
{
m_progressDialog = null;
}
if (m_exception != null)
{
if (m_exception instanceof BatteryInfoUnavailableException)
{
Toast.makeText(StatsActivity.this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(StatsActivity.this,
"An unknown error occured while retrieving stats.",
Toast.LENGTH_LONG).show();
}
}
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
long sinceMs = StatsProvider.getInstance(StatsActivity.this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(StatsActivity.this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
StatsActivity.this.setListAdapter(o);
}
// @Override
protected void onPreExecute()
{
// update hourglass
// @todo this code is only there because onItemSelected is called twice
if (m_progressDialog == null)
{
try
{
m_progressDialog = new ProgressDialog(StatsActivity.this);
m_progressDialog.setMessage("Computing...");
m_progressDialog.setIndeterminate(true);
m_progressDialog.setCancelable(false);
m_progressDialog.show();
}
catch (Exception e)
{
m_progressDialog = null;
}
}
}
}
public Dialog getShareDialog()
{
final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean saveAsText = sharedPrefs.getBoolean("save_as_text", true);
boolean saveAsJson = sharedPrefs.getBoolean("save_as_json", false);
boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false);
boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false);
if (saveAsText)
{
selectedSaveActions.add(0);
}
if (saveAsJson)
{
selectedSaveActions.add(1);
}
if (saveLogcat)
{
selectedSaveActions.add(2);
}
if (saveDmesg)
{
selectedSaveActions.add(3);
}
// Set the dialog title
builder.setTitle(R.string.title_share_dialog)
.setMultiChoiceItems(R.array.saveAsLabels, new boolean[]{saveAsText, saveAsJson, saveLogcat, saveDmesg}, new DialogInterface.OnMultiChoiceClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked)
{
if (isChecked)
{
// If the user checked the item, add it to the
// selected items
selectedSaveActions.add(which);
} else if (selectedSaveActions.contains(which))
{
// Else, if the item is already in the array,
// remove it
selectedSaveActions.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
GoogleAnalytics.getInstance(StatsActivity.this).trackPage(GoogleAnalytics.ACTION_DUMP);
ArrayList<Uri> attachements = new ArrayList<Uri>();
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);
// save as text is selected
if (selectedSaveActions.contains(0))
{
attachements.add(reading.writeToFileText(StatsActivity.this));
}
// save as JSON if selected
if (selectedSaveActions.contains(1))
{
attachements.add(reading.writeToFileJson(StatsActivity.this));
}
// save logcat if selected
if (selectedSaveActions.contains(2))
{
attachements.add(StatsProvider.getInstance(StatsActivity.this).writeLogcatToFile());
}
// save dmesg if selected
if (selectedSaveActions.contains(3))
{
attachements.add(StatsProvider.getInstance(StatsActivity.this).writeDmesgToFile());
}
if (!attachements.isEmpty())
{
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements);
shareIntent.setType("text/*");
startActivity(Intent.createChooser(shareIntent, "Share info to.."));
}
}
})
.setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
GoogleAnalytics.getInstance(StatsActivity.this).trackPage(GoogleAnalytics.ACTION_DUMP);
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this);
Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo);
// save as text is selected
// save as text is selected
if (selectedSaveActions.contains(0))
{
reading.writeToFileText(StatsActivity.this);
}
// save as JSON if selected
if (selectedSaveActions.contains(1))
{
reading.writeToFileJson(StatsActivity.this);
}
// save logcat if selected
if (selectedSaveActions.contains(2))
{
StatsProvider.getInstance(StatsActivity.this).writeLogcatToFile();
}
// save dmesg if selected
if (selectedSaveActions.contains(3))
{
StatsProvider.getInstance(StatsActivity.this).writeDmesgToFile();
}
}
}).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
// do nothing
}
});
return builder.create();
}
}
| false | true |
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "OnCreated called");
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// set debugging
if (sharedPrefs.getBoolean("debug_logging", false))
{
LogSettings.DEBUG=true;
CommonLogSettings.DEBUG=true;
}
else
{
LogSettings.DEBUG=false;
CommonLogSettings.DEBUG=false;
}
///////////////////////////////////////////////
// check if we have a new release
///////////////////////////////////////////////
// if yes do some migration (if required) and show release notes
String strLastRelease = sharedPrefs.getString("last_release", "0");
String strCurrentRelease = "";
try
{
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
strCurrentRelease = Integer.toString(pinfo.versionCode);
}
catch (Exception e)
{
// nop strCurrentRelease is set to ""
}
// if root is available use it
boolean hasRoot = sharedPrefs.getBoolean("root_features", false);
if (!hasRoot && (RootShell.getInstance().rooted()))
{
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putBoolean("root_features", true);
updater.commit();
hasRoot = sharedPrefs.getBoolean("root_features", false);
}
// show install as system app screen if root available but perms missing
if (hasRoot && !SysUtils.hasBatteryStatsPermission(this))
{
Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_PREFERENCES);
this.startActivity(intentSystemApp);
}
// first start
if (strLastRelease.equals("0"))
{
// show the initial run screen
FirstLaunch.app_launched(this);
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
}
else if (!strLastRelease.equals(strCurrentRelease))
{
// save the current release to properties so that the dialog won't be shown till next version
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show();
ReferenceStore.deleteAllRefs(this);
Intent i = new Intent(this, WriteBootReferenceService.class);
this.startService(i);
i = new Intent(this, WriteUnpluggedReferenceService.class);
this.startService(i);
}
else
{
// can't do this at the same time as the popup dialog would be masked by the readme
///////////////////////////////////////////////
// check if we have shown the opt-out from analytics
///////////////////////////////////////////////
boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false);
boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true);
if (bAnalyticsEnabled && !bWarningShown)
{
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\"");
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1)
{
// opt out info was displayed
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("analytics_opt_out", true);
editor.commit();
}
});
// show it
alertbox.show();
}
else
{
// show "rate" dialog
// for testing: AppRater.showRateDialog(this, null);
AppRater.app_launched(this);
}
}
///////////////////////////////////////////////
// retrieve default selections for spinners
// if none were passed
///////////////////////////////////////////////
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
if (!ReferenceStore.hasReferenceByName(m_refFromName, this))
{
if (sharedPrefs.getBoolean("fallback_to_since_boot", false))
{
m_refFromName = Reference.BOOT_REF_FILENAME;
Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show();
}
}
try
{
// recover any saved state
if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty()))
{
m_iStat = (Integer) savedInstanceState.getSerializable("stat");
m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
}
}
catch (Exception e)
{
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
Log.e(TAG, "Exception: " + e.getMessage());
DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
DataStorage.LogToFile(LOGFILE, e.getMessage());
DataStorage.LogToFile(LOGFILE, e.getStackTrace());
Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show();
}
// Handle the case the Activity was called from an intent with paramaters
Bundle extras = getIntent().getExtras();
if (extras != null)
{
// Override if some values were passed to the intent
m_iStat = extras.getInt(StatsActivity.STAT);
m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
// Clear the notifications that was clicked to call the activity
if (bCalledFromNotification)
{
NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
nM.cancel(EventWatcherService.NOTFICATION_ID);
}
}
// Display the reference of the stat
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
if (tvSince != null)
{
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
}
// Spinner for selecting the stat
Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(
this, R.array.stats, android.R.layout.simple_spinner_item);
spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStat.setAdapter(spinnerStatAdapter);
// setSelection MUST be called after setAdapter
spinnerStat.setSelection(m_iStat);
spinnerStat.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the Stat type
///////////////////////////////////////////////
Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStatType.setAdapter(m_spinnerFromAdapter);
try
{
this.setListViewAdapter();
}
catch (BatteryInfoUnavailableException e)
{
// Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
//Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"An unhandled error occured. Please check your logcat",
Toast.LENGTH_LONG).show();
}
// setSelection MUST be called after setAdapter
spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
spinnerStatType.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the end sample
///////////////////////////////////////////////
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
if ((m_refToName != null) && !m_refToName.equals("") )
{
int pos = m_spinnerToAdapter.getPosition(m_refToName);
spinnerStatSampleEnd.setSelection(pos);
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
spinnerStatSampleEnd.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// sorting
///////////////////////////////////////////////
String strOrderBy = sharedPrefs.getString("default_orderby", "0");
try
{
m_iSorting = Integer.valueOf(strOrderBy);
}
catch(Exception e)
{
// handle error here
m_iSorting = 0;
}
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
// Set up a listener whenever a key changes
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
// log reference store
ReferenceStore.logReferences(this);
}
|
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "OnCreated called");
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// set debugging
if (sharedPrefs.getBoolean("debug_logging", false))
{
LogSettings.DEBUG=true;
CommonLogSettings.DEBUG=true;
}
else
{
LogSettings.DEBUG=false;
CommonLogSettings.DEBUG=false;
}
///////////////////////////////////////////////
// check if we have a new release
///////////////////////////////////////////////
// if yes do some migration (if required) and show release notes
String strLastRelease = sharedPrefs.getString("last_release", "0");
String strCurrentRelease = "";
try
{
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
strCurrentRelease = Integer.toString(pinfo.versionCode);
}
catch (Exception e)
{
// nop strCurrentRelease is set to ""
}
// if root is available use it
boolean hasRoot = sharedPrefs.getBoolean("root_features", false);
boolean ignoreSystemApp = sharedPrefs.getBoolean("ignore_system_app", false);
if (!hasRoot && (RootShell.getInstance().rooted()))
{
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putBoolean("root_features", true);
updater.commit();
hasRoot = sharedPrefs.getBoolean("root_features", false);
}
// show install as system app screen if root available but perms missing
if (!ignoreSystemApp && hasRoot && !SysUtils.hasBatteryStatsPermission(this))
{
Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_PREFERENCES);
this.startActivity(intentSystemApp);
}
// first start
if (strLastRelease.equals("0"))
{
// show the initial run screen
FirstLaunch.app_launched(this);
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
}
else if (!strLastRelease.equals(strCurrentRelease))
{
// save the current release to properties so that the dialog won't be shown till next version
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show();
ReferenceStore.deleteAllRefs(this);
Intent i = new Intent(this, WriteBootReferenceService.class);
this.startService(i);
i = new Intent(this, WriteUnpluggedReferenceService.class);
this.startService(i);
}
else
{
// can't do this at the same time as the popup dialog would be masked by the readme
///////////////////////////////////////////////
// check if we have shown the opt-out from analytics
///////////////////////////////////////////////
boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false);
boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true);
if (bAnalyticsEnabled && !bWarningShown)
{
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\"");
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1)
{
// opt out info was displayed
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("analytics_opt_out", true);
editor.commit();
}
});
// show it
alertbox.show();
}
else
{
// show "rate" dialog
// for testing: AppRater.showRateDialog(this, null);
AppRater.app_launched(this);
}
}
///////////////////////////////////////////////
// retrieve default selections for spinners
// if none were passed
///////////////////////////////////////////////
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
if (!ReferenceStore.hasReferenceByName(m_refFromName, this))
{
if (sharedPrefs.getBoolean("fallback_to_since_boot", false))
{
m_refFromName = Reference.BOOT_REF_FILENAME;
Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show();
}
}
try
{
// recover any saved state
if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty()))
{
m_iStat = (Integer) savedInstanceState.getSerializable("stat");
m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
}
}
catch (Exception e)
{
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
Log.e(TAG, "Exception: " + e.getMessage());
DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
DataStorage.LogToFile(LOGFILE, e.getMessage());
DataStorage.LogToFile(LOGFILE, e.getStackTrace());
Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show();
}
// Handle the case the Activity was called from an intent with paramaters
Bundle extras = getIntent().getExtras();
if (extras != null)
{
// Override if some values were passed to the intent
m_iStat = extras.getInt(StatsActivity.STAT);
m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
// Clear the notifications that was clicked to call the activity
if (bCalledFromNotification)
{
NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
nM.cancel(EventWatcherService.NOTFICATION_ID);
}
}
// Display the reference of the stat
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
if (tvSince != null)
{
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
}
// Spinner for selecting the stat
Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(
this, R.array.stats, android.R.layout.simple_spinner_item);
spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStat.setAdapter(spinnerStatAdapter);
// setSelection MUST be called after setAdapter
spinnerStat.setSelection(m_iStat);
spinnerStat.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the Stat type
///////////////////////////////////////////////
Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStatType.setAdapter(m_spinnerFromAdapter);
try
{
this.setListViewAdapter();
}
catch (BatteryInfoUnavailableException e)
{
// Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
//Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"An unhandled error occured. Please check your logcat",
Toast.LENGTH_LONG).show();
}
// setSelection MUST be called after setAdapter
spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
spinnerStatType.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// Spinner for Selecting the end sample
///////////////////////////////////////////////
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
if ((m_refToName != null) && !m_refToName.equals("") )
{
int pos = m_spinnerToAdapter.getPosition(m_refToName);
spinnerStatSampleEnd.setSelection(pos);
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
// setSelection must be called after setAdapter
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
spinnerStatSampleEnd.setOnItemSelectedListener(this);
///////////////////////////////////////////////
// sorting
///////////////////////////////////////////////
String strOrderBy = sharedPrefs.getString("default_orderby", "0");
try
{
m_iSorting = Integer.valueOf(strOrderBy);
}
catch(Exception e)
{
// handle error here
m_iSorting = 0;
}
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
// Set up a listener whenever a key changes
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
// log reference store
ReferenceStore.logReferences(this);
}
|
diff --git a/core/src/main/java/org/apache/mina/common/support/AbstractIoFilterChain.java b/core/src/main/java/org/apache/mina/common/support/AbstractIoFilterChain.java
index df96b678..9c49b485 100644
--- a/core/src/main/java/org/apache/mina/common/support/AbstractIoFilterChain.java
+++ b/core/src/main/java/org/apache/mina/common/support/AbstractIoFilterChain.java
@@ -1,861 +1,861 @@
/*
* 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.mina.common.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoFilterChain;
import org.apache.mina.common.IoFilterLifeCycleException;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.WriteRequest;
import org.apache.mina.common.IoFilter.NextFilter;
import org.apache.mina.util.SessionLog;
/**
* An abstract implementation of {@link IoFilterChain} that provides
* common operations for developers to implement their own transport layer.
* <p>
* The only method a developer should implement is
* {@link #doWrite(IoSession, IoFilter.WriteRequest)}. This method is invoked
* when filter chain is evaluated for
* {@link IoFilter#filterWrite(NextFilter, IoSession, IoFilter.WriteRequest)} and
* finally to be written out.
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*/
public abstract class AbstractIoFilterChain implements IoFilterChain
{
/**
* A session attribute that stores a {@link ConnectFuture} related with
* the {@link IoSession}. {@link AbstractIoFilterChain} clears this
* attribute and notifies the future when {@link #fireSessionOpened(IoSession)}
* or {@link #fireExceptionCaught(IoSession, Throwable)} is invoked
*/
public static final String CONNECT_FUTURE =
AbstractIoFilterChain.class.getName() + ".connectFuture";
private final IoSession session;
private final Map<String, Entry> name2entry = new HashMap<String, Entry>();
private final EntryImpl head;
private final EntryImpl tail;
protected AbstractIoFilterChain( IoSession session )
{
if( session == null )
{
throw new NullPointerException( "session" );
}
this.session = session;
head = new EntryImpl( null, null, "head", new HeadFilter() );
tail = new EntryImpl( head, null, "tail", new TailFilter() );
head.nextEntry = tail;
}
public IoSession getSession()
{
return session;
}
public Entry getEntry( String name )
{
Entry e = name2entry.get( name );
if ( e == null )
{
return null;
}
return e;
}
public IoFilter get( String name )
{
Entry e = getEntry( name );
if( e == null )
{
return null;
}
return e.getFilter();
}
public NextFilter getNextFilter( String name )
{
Entry e = getEntry( name );
if( e == null )
{
return null;
}
return e.getNextFilter();
}
public synchronized void addFirst( String name,
IoFilter filter )
{
checkAddable( name );
register( head, name, filter );
}
public synchronized void addLast( String name,
IoFilter filter )
{
checkAddable( name );
register( tail.prevEntry, name, filter );
}
public synchronized void addBefore( String baseName,
String name,
IoFilter filter )
{
EntryImpl baseEntry = checkOldName( baseName );
checkAddable( name );
register( baseEntry.prevEntry, name, filter );
}
public synchronized void addAfter( String baseName,
String name,
IoFilter filter )
{
EntryImpl baseEntry = checkOldName( baseName );
checkAddable( name );
register( baseEntry, name, filter );
}
public synchronized IoFilter remove( String name )
{
EntryImpl entry = checkOldName( name );
deregister( entry );
return entry.getFilter();
}
public synchronized void clear() throws Exception
{
Iterator<String> it = new ArrayList<String>( name2entry.keySet() ).iterator();
while ( it.hasNext() )
{
this.remove( it.next() );
}
}
private void register( EntryImpl prevEntry, String name, IoFilter filter )
{
EntryImpl newEntry = new EntryImpl( prevEntry, prevEntry.nextEntry, name, filter );
try
{
filter.onPreAdd( this, name, newEntry.getNextFilter() );
}
catch( Exception e )
{
throw new IoFilterLifeCycleException( "onPreAdd(): " + name + ':' + filter + " in " + getSession(), e );
}
prevEntry.nextEntry.prevEntry = newEntry;
prevEntry.nextEntry = newEntry;
name2entry.put( name, newEntry );
try
{
filter.onPostAdd( this, name, newEntry.getNextFilter() );
}
catch( Exception e )
{
deregister0( newEntry );
throw new IoFilterLifeCycleException( "onPostAdd(): " + name + ':' + filter + " in " + getSession(), e );
}
}
private void deregister( EntryImpl entry )
{
IoFilter filter = entry.getFilter();
try
{
filter.onPreRemove( this, entry.getName(), entry.getNextFilter() );
}
catch( Exception e )
{
throw new IoFilterLifeCycleException( "onPreRemove(): " + entry.getName() + ':' + filter
+ " in " + getSession(), e );
}
deregister0( entry );
try
{
filter.onPostRemove( this, entry.getName(), entry.getNextFilter() );
}
catch( Exception e )
{
throw new IoFilterLifeCycleException( "onPostRemove(): " + entry.getName() + ':' + filter
+ " in " + getSession(), e );
}
}
private void deregister0( EntryImpl entry )
{
EntryImpl prevEntry = entry.prevEntry;
EntryImpl nextEntry = entry.nextEntry;
prevEntry.nextEntry = nextEntry;
nextEntry.prevEntry = prevEntry;
name2entry.remove( entry.name );
}
/**
* Throws an exception when the specified filter name is not registered in this chain.
*
* @return An filter entry with the specified name.
*/
private EntryImpl checkOldName( String baseName )
{
EntryImpl e = ( EntryImpl ) name2entry.get( baseName );
if ( e == null )
{
throw new IllegalArgumentException( "Unknown filter name:" +
baseName );
}
return e;
}
/**
* Checks the specified filter name is already taken and throws an exception if already taken.
*/
private void checkAddable( String name )
{
if ( name2entry.containsKey( name ) )
{
throw new IllegalArgumentException( "Other filter is using the same name '" + name + "'" );
}
}
public void fireSessionCreated( IoSession session )
{
Entry head = this.head;
callNextSessionCreated(head, session);
}
private void callNextSessionCreated( Entry entry, IoSession session )
{
try
{
entry.getFilter().sessionCreated( entry.getNextFilter(), session );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireSessionOpened( IoSession session )
{
Entry head = this.head;
callNextSessionOpened(head, session);
}
private void callNextSessionOpened( Entry entry,
IoSession session)
{
try
{
entry.getFilter().sessionOpened( entry.getNextFilter(), session );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireSessionClosed( IoSession session )
{
// Update future.
try
{
session.getCloseFuture().setClosed();
}
catch( Throwable t )
{
fireExceptionCaught( session, t );
}
// And start the chain.
Entry head = this.head;
callNextSessionClosed(head, session);
}
private void callNextSessionClosed( Entry entry,
IoSession session )
{
try
{
entry.getFilter().sessionClosed( entry.getNextFilter(), session );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireSessionIdle( IoSession session, IdleStatus status )
{
Entry head = this.head;
callNextSessionIdle(head, session, status);
}
private void callNextSessionIdle( Entry entry,
IoSession session,
IdleStatus status )
{
try
{
entry.getFilter().sessionIdle( entry.getNextFilter(), session, status );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireMessageReceived( IoSession session, Object message )
{
Entry head = this.head;
callNextMessageReceived(head, session, message );
}
private void callNextMessageReceived( Entry entry,
IoSession session,
Object message )
{
try
{
entry.getFilter().messageReceived( entry.getNextFilter(), session, message );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireMessageSent( IoSession session, WriteRequest request )
{
try
{
request.getFuture().setWritten( true );
}
catch( Throwable t )
{
fireExceptionCaught( session, t );
}
Entry head = this.head;
callNextMessageSent( head, session, request );
}
private void callNextMessageSent( Entry entry,
IoSession session,
WriteRequest writeRequest )
{
try
{
entry.getFilter().messageSent( entry.getNextFilter(), session, writeRequest );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireExceptionCaught( IoSession session, Throwable cause )
{
// Notify the related ConnectFuture
// if the session is created from SocketConnector.
ConnectFuture future = ( ConnectFuture ) session.removeAttribute( CONNECT_FUTURE );
if( future == null )
{
Entry head = this.head;
callNextExceptionCaught( head, session, cause );
}
else
{
// Please note that this place is not the only place that
// calls ConnectFuture.setException().
future.setException( cause );
}
}
private void callNextExceptionCaught( Entry entry,
IoSession session,
Throwable cause )
{
try
{
entry.getFilter().exceptionCaught( entry.getNextFilter(), session, cause );
}
catch( Throwable e )
{
SessionLog.warn(
session,
"Unexpected exception from exceptionCaught handler.", e );
}
}
public void fireFilterWrite( IoSession session, WriteRequest writeRequest )
{
Entry tail = this.tail;
callPreviousFilterWrite( tail, session, writeRequest );
}
private void callPreviousFilterWrite( Entry entry,
IoSession session,
WriteRequest writeRequest )
{
try
{
entry.getFilter().filterWrite( entry.getNextFilter(), session, writeRequest );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public void fireFilterClose( IoSession session )
{
Entry tail = this.tail;
callPreviousFilterClose( tail, session );
}
private void callPreviousFilterClose( Entry entry,
IoSession session )
{
try
{
entry.getFilter().filterClose( entry.getNextFilter(), session );
}
catch( Throwable e )
{
fireExceptionCaught( session, e );
}
}
public List<Entry> getAll()
{
List<Entry> list = new ArrayList<Entry>();
EntryImpl e = head.nextEntry;
while( e != tail )
{
list.add( e );
e = e.nextEntry;
}
return list;
}
public List<Entry> getAllReversed()
{
List<Entry> list = new ArrayList<Entry>();
EntryImpl e = tail.prevEntry;
while( e != head )
{
list.add( e );
e = e.prevEntry;
}
return list;
}
public boolean contains( String name )
{
return getEntry( name ) != null;
}
public boolean contains( IoFilter filter )
{
EntryImpl e = head.nextEntry;
while( e != tail )
{
if( e.getFilter() == filter )
{
return true;
}
e = e.nextEntry;
}
return false;
}
public boolean contains( Class<? extends IoFilter> filterType )
{
EntryImpl e = head.nextEntry;
while( e != tail )
{
if( filterType.isAssignableFrom( e.getFilter().getClass() ) )
{
return true;
}
e = e.nextEntry;
}
return false;
}
@Override
public String toString()
{
StringBuffer buf = new StringBuffer();
buf.append( "{ " );
boolean empty = true;
EntryImpl e = head.nextEntry;
while( e != tail )
{
if( !empty )
{
buf.append( ", " );
}
else
{
empty = false;
}
buf.append( '(' );
buf.append( e.getName() );
buf.append( ':' );
buf.append( e.getFilter() );
buf.append( ')' );
e = e.nextEntry;
}
if( empty )
{
buf.append( "empty" );
}
buf.append( " }" );
return buf.toString();
}
@Override
protected void finalize() throws Throwable
{
try
{
this.clear();
}
finally
{
super.finalize();
}
}
protected abstract void doWrite( IoSession session, WriteRequest writeRequest ) throws Exception;
protected abstract void doClose( IoSession session ) throws Exception;
private class HeadFilter extends IoFilterAdapter
{
@Override
public void sessionCreated( NextFilter nextFilter, IoSession session )
{
nextFilter.sessionCreated( session );
}
@Override
public void sessionOpened( NextFilter nextFilter, IoSession session )
{
nextFilter.sessionOpened( session );
}
@Override
public void sessionClosed( NextFilter nextFilter, IoSession session )
{
nextFilter.sessionClosed( session );
}
@Override
public void sessionIdle( NextFilter nextFilter, IoSession session,
IdleStatus status )
{
nextFilter.sessionIdle( session, status );
}
@Override
public void exceptionCaught( NextFilter nextFilter,
IoSession session, Throwable cause )
{
nextFilter.exceptionCaught( session, cause );
}
@Override
public void messageReceived( NextFilter nextFilter, IoSession session,
Object message )
{
nextFilter.messageReceived( session, message );
}
@Override
public void messageSent( NextFilter nextFilter, IoSession session,
WriteRequest writeRequest )
{
nextFilter.messageSent( session, writeRequest );
}
@Override
public void filterWrite( NextFilter nextFilter, IoSession session,
WriteRequest writeRequest ) throws Exception
{
if( session.getTransportType().getEnvelopeType().isAssignableFrom( writeRequest.getMessage().getClass() ) )
{
doWrite( session, writeRequest );
}
else
{
throw new IllegalStateException(
"Write requests must be transformed to " +
session.getTransportType().getEnvelopeType() +
": " + writeRequest );
}
}
@Override
public void filterClose( NextFilter nextFilter, IoSession session ) throws Exception
{
doClose( session );
}
}
private static class TailFilter extends IoFilterAdapter
{
@Override
public void sessionCreated( NextFilter nextFilter, IoSession session ) throws Exception
{
session.getHandler().sessionCreated( session );
}
@Override
public void sessionOpened( NextFilter nextFilter, IoSession session ) throws Exception
{
try
{
session.getHandler().sessionOpened( session );
}
finally
{
// Notify the related ConnectFuture
// if the session is created from SocketConnector.
ConnectFuture future = ( ConnectFuture ) session.removeAttribute( CONNECT_FUTURE );
if( future != null )
{
future.setSession( session );
}
}
}
@Override
public void sessionClosed( NextFilter nextFilter, IoSession session ) throws Exception
{
try
{
session.getHandler().sessionClosed( session );
}
finally
{
// Remove all filters.
session.getFilterChain().clear();
}
}
@Override
public void sessionIdle( NextFilter nextFilter, IoSession session,
IdleStatus status ) throws Exception
{
session.getHandler().sessionIdle( session, status );
}
@Override
public void exceptionCaught( NextFilter nextFilter,
IoSession session, Throwable cause ) throws Exception
{
session.getHandler().exceptionCaught( session, cause );
}
@Override
public void messageReceived( NextFilter nextFilter, IoSession session,
Object message ) throws Exception
{
session.getHandler().messageReceived( session, message );
}
@Override
public void messageSent( NextFilter nextFilter, IoSession session,
WriteRequest writeRequest ) throws Exception
{
session.getHandler().messageSent( session, writeRequest.getMessage() );
}
@Override
public void filterWrite( NextFilter nextFilter,
IoSession session, WriteRequest writeRequest ) throws Exception
{
nextFilter.filterWrite( session, writeRequest );
}
@Override
public void filterClose( NextFilter nextFilter, IoSession session ) throws Exception
{
nextFilter.filterClose( session );
}
}
private class EntryImpl implements Entry
{
private EntryImpl prevEntry;
private EntryImpl nextEntry;
private final String name;
private final IoFilter filter;
private final NextFilter nextFilter;
private EntryImpl( EntryImpl prevEntry, EntryImpl nextEntry,
String name, IoFilter filter )
{
if( filter == null )
{
throw new NullPointerException( "filter" );
}
if( name == null )
{
throw new NullPointerException( "name" );
}
this.prevEntry = prevEntry;
this.nextEntry = nextEntry;
this.name = name;
this.filter = filter;
this.nextFilter = new NextFilter()
{
public void sessionCreated( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionCreated( nextEntry, session );
}
public void sessionOpened( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionOpened( nextEntry, session );
}
public void sessionClosed( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionClosed( nextEntry, session );
}
public void sessionIdle( IoSession session, IdleStatus status )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionIdle( nextEntry, session, status );
}
public void exceptionCaught( IoSession session,
Throwable cause )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextExceptionCaught( nextEntry, session, cause );
}
public void messageReceived( IoSession session, Object message )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageReceived( nextEntry, session, message );
}
public void messageSent( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageSent( nextEntry, session, writeRequest );
}
public void filterWrite( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.prevEntry;
if( nextEntry != head && writeRequest.getMessage() instanceof ByteBuffer )
{
// A special message is a buffer with zero length.
// A special message will bypass all next filters.
// TODO: Provide a nicer way to take care of special messages.
ByteBuffer message = ( ByteBuffer ) writeRequest.getMessage();
if( message.remaining() == 0 )
{
- callPreviousFilterWrite( head.nextEntry, session, writeRequest );
+ callPreviousFilterWrite( head, session, writeRequest );
return;
}
}
callPreviousFilterWrite( nextEntry, session, writeRequest );
}
public void filterClose( IoSession session )
{
Entry nextEntry = EntryImpl.this.prevEntry;
callPreviousFilterClose( nextEntry, session );
}
};
}
public String getName()
{
return name;
}
public IoFilter getFilter()
{
return filter;
}
public NextFilter getNextFilter()
{
return nextFilter;
}
@Override
public String toString()
{
return "(" + getName() + ':' + filter + ')';
}
}
}
| true | true |
private EntryImpl( EntryImpl prevEntry, EntryImpl nextEntry,
String name, IoFilter filter )
{
if( filter == null )
{
throw new NullPointerException( "filter" );
}
if( name == null )
{
throw new NullPointerException( "name" );
}
this.prevEntry = prevEntry;
this.nextEntry = nextEntry;
this.name = name;
this.filter = filter;
this.nextFilter = new NextFilter()
{
public void sessionCreated( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionCreated( nextEntry, session );
}
public void sessionOpened( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionOpened( nextEntry, session );
}
public void sessionClosed( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionClosed( nextEntry, session );
}
public void sessionIdle( IoSession session, IdleStatus status )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionIdle( nextEntry, session, status );
}
public void exceptionCaught( IoSession session,
Throwable cause )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextExceptionCaught( nextEntry, session, cause );
}
public void messageReceived( IoSession session, Object message )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageReceived( nextEntry, session, message );
}
public void messageSent( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageSent( nextEntry, session, writeRequest );
}
public void filterWrite( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.prevEntry;
if( nextEntry != head && writeRequest.getMessage() instanceof ByteBuffer )
{
// A special message is a buffer with zero length.
// A special message will bypass all next filters.
// TODO: Provide a nicer way to take care of special messages.
ByteBuffer message = ( ByteBuffer ) writeRequest.getMessage();
if( message.remaining() == 0 )
{
callPreviousFilterWrite( head.nextEntry, session, writeRequest );
return;
}
}
callPreviousFilterWrite( nextEntry, session, writeRequest );
}
public void filterClose( IoSession session )
{
Entry nextEntry = EntryImpl.this.prevEntry;
callPreviousFilterClose( nextEntry, session );
}
};
}
|
private EntryImpl( EntryImpl prevEntry, EntryImpl nextEntry,
String name, IoFilter filter )
{
if( filter == null )
{
throw new NullPointerException( "filter" );
}
if( name == null )
{
throw new NullPointerException( "name" );
}
this.prevEntry = prevEntry;
this.nextEntry = nextEntry;
this.name = name;
this.filter = filter;
this.nextFilter = new NextFilter()
{
public void sessionCreated( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionCreated( nextEntry, session );
}
public void sessionOpened( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionOpened( nextEntry, session );
}
public void sessionClosed( IoSession session )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionClosed( nextEntry, session );
}
public void sessionIdle( IoSession session, IdleStatus status )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextSessionIdle( nextEntry, session, status );
}
public void exceptionCaught( IoSession session,
Throwable cause )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextExceptionCaught( nextEntry, session, cause );
}
public void messageReceived( IoSession session, Object message )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageReceived( nextEntry, session, message );
}
public void messageSent( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.nextEntry;
callNextMessageSent( nextEntry, session, writeRequest );
}
public void filterWrite( IoSession session, WriteRequest writeRequest )
{
Entry nextEntry = EntryImpl.this.prevEntry;
if( nextEntry != head && writeRequest.getMessage() instanceof ByteBuffer )
{
// A special message is a buffer with zero length.
// A special message will bypass all next filters.
// TODO: Provide a nicer way to take care of special messages.
ByteBuffer message = ( ByteBuffer ) writeRequest.getMessage();
if( message.remaining() == 0 )
{
callPreviousFilterWrite( head, session, writeRequest );
return;
}
}
callPreviousFilterWrite( nextEntry, session, writeRequest );
}
public void filterClose( IoSession session )
{
Entry nextEntry = EntryImpl.this.prevEntry;
callPreviousFilterClose( nextEntry, session );
}
};
}
|
diff --git a/src/haven/Homing.java b/src/haven/Homing.java
index 23fc4886..5c66ceff 100644
--- a/src/haven/Homing.java
+++ b/src/haven/Homing.java
@@ -1,66 +1,69 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, 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 for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
public class Homing extends Moving {
long tgt;
Coord tc;
int v;
double dist;
public Homing(Gob gob, long tgt, Coord tc, int v) {
super(gob);
this.tgt = tgt;
this.tc = tc;
this.v = v;
}
public Coord3f getc() {
Coord tc = this.tc;
Gob tgt = gob.glob.oc.getgob(this.tgt);
if(tgt != null)
tc = tgt.rc;
Coord d = tc.add(gob.rc.inv());
double e = gob.rc.dist(tc);
- float rx = (float)((d.x / e) * dist) + gob.rc.x;
- float ry = (float)((d.y / e) * dist) + gob.rc.y;
+ float rx = gob.rc.x, ry = gob.rc.y;
+ if(e > 0.00001) {
+ rx += (float)((d.x / e) * dist);
+ ry += (float)((d.y / e) * dist);
+ }
return(new Coord3f(rx, ry, gob.glob.map.getcz(rx, ry)));
}
public double getv() {
return((v / 100.0) / 0.06);
}
public void move(Coord c) {
dist = 0;
}
public void ctick(int dt) {
double da = ((double)dt / 1000) / 0.06;
dist += (da * 0.9) * ((double)v / 100);
}
}
| true | true |
public Coord3f getc() {
Coord tc = this.tc;
Gob tgt = gob.glob.oc.getgob(this.tgt);
if(tgt != null)
tc = tgt.rc;
Coord d = tc.add(gob.rc.inv());
double e = gob.rc.dist(tc);
float rx = (float)((d.x / e) * dist) + gob.rc.x;
float ry = (float)((d.y / e) * dist) + gob.rc.y;
return(new Coord3f(rx, ry, gob.glob.map.getcz(rx, ry)));
}
|
public Coord3f getc() {
Coord tc = this.tc;
Gob tgt = gob.glob.oc.getgob(this.tgt);
if(tgt != null)
tc = tgt.rc;
Coord d = tc.add(gob.rc.inv());
double e = gob.rc.dist(tc);
float rx = gob.rc.x, ry = gob.rc.y;
if(e > 0.00001) {
rx += (float)((d.x / e) * dist);
ry += (float)((d.y / e) * dist);
}
return(new Coord3f(rx, ry, gob.glob.map.getcz(rx, ry)));
}
|
diff --git a/android/src/name/drahflow/utilator/TimeDistribution.java b/android/src/name/drahflow/utilator/TimeDistribution.java
index f081179..8c292c5 100644
--- a/android/src/name/drahflow/utilator/TimeDistribution.java
+++ b/android/src/name/drahflow/utilator/TimeDistribution.java
@@ -1,126 +1,126 @@
package name.drahflow.utilator;
import java.util.*;
public abstract class TimeDistribution {
private static GregorianCalendar cal = new GregorianCalendar();
abstract public int evaluate(long t, FakeCalendar cal);
abstract public boolean isConstant(Date s, Date e);
public static TimeDistribution compile(int def, List<String> distribution) {
return compile(def, distribution, new TreeMap<String, Date>());
}
public static TimeDistribution compile(int def, List<String> distribution, Map<String, Date> cache) {
if(distribution == null || distribution.isEmpty()) {
return new TimeDistributionConstant(def);
}
Collections.sort(distribution);
List<TimeDistributionComplex.Entry> entries = new ArrayList<TimeDistributionComplex.Entry>();
Integer value = 0;
for(String entry: distribution) {
int colon = entry.indexOf(':');
String[] data = new String[] { entry.substring(1, colon), entry.substring(colon + 1) };
if(data[0].equals("constant")) {
if(value != null) {
value += Integer.parseInt(data[1]);
} else {
entries.add(new TimeDistributionComplex.EntryConstant(Integer.parseInt(data[1])));
}
} else if(data[0].equals("mulrange")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
int semicolon1 = data[1].indexOf(';');
int semicolon2 = data[1].indexOf(';', semicolon1 + 1);
String[] parts = new String[] {
data[1].substring(0, semicolon1),
data[1].substring(semicolon1 + 1, semicolon2),
data[1].substring(semicolon2 + 1)
};
final Date start = Util.parseDate(parts[0], cache);
final Date end = Util.parseDate(parts[1], cache);
int multiplier = Integer.parseInt(parts[2]);
entries.add(new TimeDistributionComplex.EntryMulrange(start.getTime(), end.getTime(), multiplier));
} else if(data[0].equals("mulhours")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
List<TimeDistributionComplex.EntryMulhours.Range> ranges = new ArrayList<TimeDistributionComplex.EntryMulhours.Range>();
for(String hour: parts[0].split(",")) {
TimeDistributionComplex.EntryMulhours.Range range = new TimeDistributionComplex.EntryMulhours.Range();
String[] parts2 = hour.split("\\+");
String[] parts3 = parts2[0].split(":");
range.start = Integer.parseInt(parts3[0]) * 60 + Integer.parseInt(parts3[1]);
range.end = range.start + Integer.parseInt(parts2[1]);
ranges.add(range);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMulhours(ranges, multiplier));
} else if(data[0].equals("muldays")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
Set<Long> dates = new HashSet<Long>();
for(String day: parts[0].split(",")) {
cal.setTime(Util.parseDate(day, cache));
final long date = cal.get(Calendar.YEAR) * 400 + cal.get(Calendar.MONTH) * 32 + cal.get(Calendar.DAY_OF_MONTH);
dates.add(date);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMuldays(dates, multiplier));
} else {
throw new IllegalArgumentException("Unknown time distribution spec: " + entry);
}
}
if(value != null) {
return new TimeDistributionConstant(value);
} else {
// optimize overlapping mulranges
for(int i = 2; i < entries.size(); ++i) {
if(entries.get(i - 1) instanceof TimeDistributionComplex.EntryMulrange && entries.get(i) instanceof TimeDistributionComplex.EntryMulrange) {
final TimeDistributionComplex.EntryMulrange earlier = (TimeDistributionComplex.EntryMulrange)entries.get(i - 1);
final TimeDistributionComplex.EntryMulrange later = (TimeDistributionComplex.EntryMulrange)entries.get(i);
if(earlier.multiplier == 0 && later.multiplier == 0) {
- if(earlier.start < later.start && earlier.end >= later.start) {
+ if(earlier.start < later.start && later.start <= earlier.end) {
earlier.start = earlier.start;
- earlier.end = later.end;
+ earlier.end = earlier.end < later.end? later.end: earlier.end;
entries.remove(i);
--i;
- } else if(earlier.start > later.start && later.end >= earlier.start) { // it is actually backwards
+ } else if(later.start < earlier.start && earlier.start <= later.end) { // it is actually backwards
earlier.start = later.start;
- earlier.end = earlier.end;
+ earlier.end = earlier.end < later.end? later.end: earlier.end;
entries.remove(i);
--i;
}
}
}
}
return new TimeDistributionComplex(entries.toArray(new TimeDistributionComplex.Entry[entries.size()]));
}
}
}
| false | true |
public static TimeDistribution compile(int def, List<String> distribution, Map<String, Date> cache) {
if(distribution == null || distribution.isEmpty()) {
return new TimeDistributionConstant(def);
}
Collections.sort(distribution);
List<TimeDistributionComplex.Entry> entries = new ArrayList<TimeDistributionComplex.Entry>();
Integer value = 0;
for(String entry: distribution) {
int colon = entry.indexOf(':');
String[] data = new String[] { entry.substring(1, colon), entry.substring(colon + 1) };
if(data[0].equals("constant")) {
if(value != null) {
value += Integer.parseInt(data[1]);
} else {
entries.add(new TimeDistributionComplex.EntryConstant(Integer.parseInt(data[1])));
}
} else if(data[0].equals("mulrange")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
int semicolon1 = data[1].indexOf(';');
int semicolon2 = data[1].indexOf(';', semicolon1 + 1);
String[] parts = new String[] {
data[1].substring(0, semicolon1),
data[1].substring(semicolon1 + 1, semicolon2),
data[1].substring(semicolon2 + 1)
};
final Date start = Util.parseDate(parts[0], cache);
final Date end = Util.parseDate(parts[1], cache);
int multiplier = Integer.parseInt(parts[2]);
entries.add(new TimeDistributionComplex.EntryMulrange(start.getTime(), end.getTime(), multiplier));
} else if(data[0].equals("mulhours")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
List<TimeDistributionComplex.EntryMulhours.Range> ranges = new ArrayList<TimeDistributionComplex.EntryMulhours.Range>();
for(String hour: parts[0].split(",")) {
TimeDistributionComplex.EntryMulhours.Range range = new TimeDistributionComplex.EntryMulhours.Range();
String[] parts2 = hour.split("\\+");
String[] parts3 = parts2[0].split(":");
range.start = Integer.parseInt(parts3[0]) * 60 + Integer.parseInt(parts3[1]);
range.end = range.start + Integer.parseInt(parts2[1]);
ranges.add(range);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMulhours(ranges, multiplier));
} else if(data[0].equals("muldays")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
Set<Long> dates = new HashSet<Long>();
for(String day: parts[0].split(",")) {
cal.setTime(Util.parseDate(day, cache));
final long date = cal.get(Calendar.YEAR) * 400 + cal.get(Calendar.MONTH) * 32 + cal.get(Calendar.DAY_OF_MONTH);
dates.add(date);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMuldays(dates, multiplier));
} else {
throw new IllegalArgumentException("Unknown time distribution spec: " + entry);
}
}
if(value != null) {
return new TimeDistributionConstant(value);
} else {
// optimize overlapping mulranges
for(int i = 2; i < entries.size(); ++i) {
if(entries.get(i - 1) instanceof TimeDistributionComplex.EntryMulrange && entries.get(i) instanceof TimeDistributionComplex.EntryMulrange) {
final TimeDistributionComplex.EntryMulrange earlier = (TimeDistributionComplex.EntryMulrange)entries.get(i - 1);
final TimeDistributionComplex.EntryMulrange later = (TimeDistributionComplex.EntryMulrange)entries.get(i);
if(earlier.multiplier == 0 && later.multiplier == 0) {
if(earlier.start < later.start && earlier.end >= later.start) {
earlier.start = earlier.start;
earlier.end = later.end;
entries.remove(i);
--i;
} else if(earlier.start > later.start && later.end >= earlier.start) { // it is actually backwards
earlier.start = later.start;
earlier.end = earlier.end;
entries.remove(i);
--i;
}
}
}
}
return new TimeDistributionComplex(entries.toArray(new TimeDistributionComplex.Entry[entries.size()]));
}
}
|
public static TimeDistribution compile(int def, List<String> distribution, Map<String, Date> cache) {
if(distribution == null || distribution.isEmpty()) {
return new TimeDistributionConstant(def);
}
Collections.sort(distribution);
List<TimeDistributionComplex.Entry> entries = new ArrayList<TimeDistributionComplex.Entry>();
Integer value = 0;
for(String entry: distribution) {
int colon = entry.indexOf(':');
String[] data = new String[] { entry.substring(1, colon), entry.substring(colon + 1) };
if(data[0].equals("constant")) {
if(value != null) {
value += Integer.parseInt(data[1]);
} else {
entries.add(new TimeDistributionComplex.EntryConstant(Integer.parseInt(data[1])));
}
} else if(data[0].equals("mulrange")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
int semicolon1 = data[1].indexOf(';');
int semicolon2 = data[1].indexOf(';', semicolon1 + 1);
String[] parts = new String[] {
data[1].substring(0, semicolon1),
data[1].substring(semicolon1 + 1, semicolon2),
data[1].substring(semicolon2 + 1)
};
final Date start = Util.parseDate(parts[0], cache);
final Date end = Util.parseDate(parts[1], cache);
int multiplier = Integer.parseInt(parts[2]);
entries.add(new TimeDistributionComplex.EntryMulrange(start.getTime(), end.getTime(), multiplier));
} else if(data[0].equals("mulhours")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
List<TimeDistributionComplex.EntryMulhours.Range> ranges = new ArrayList<TimeDistributionComplex.EntryMulhours.Range>();
for(String hour: parts[0].split(",")) {
TimeDistributionComplex.EntryMulhours.Range range = new TimeDistributionComplex.EntryMulhours.Range();
String[] parts2 = hour.split("\\+");
String[] parts3 = parts2[0].split(":");
range.start = Integer.parseInt(parts3[0]) * 60 + Integer.parseInt(parts3[1]);
range.end = range.start + Integer.parseInt(parts2[1]);
ranges.add(range);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMulhours(ranges, multiplier));
} else if(data[0].equals("muldays")) {
if(value != null) {
entries.add(new TimeDistributionComplex.EntryConstant(value));
value = null;
}
String[] parts = data[1].split(";");
Set<Long> dates = new HashSet<Long>();
for(String day: parts[0].split(",")) {
cal.setTime(Util.parseDate(day, cache));
final long date = cal.get(Calendar.YEAR) * 400 + cal.get(Calendar.MONTH) * 32 + cal.get(Calendar.DAY_OF_MONTH);
dates.add(date);
}
int multiplier = Integer.parseInt(parts[1]);
entries.add(new TimeDistributionComplex.EntryMuldays(dates, multiplier));
} else {
throw new IllegalArgumentException("Unknown time distribution spec: " + entry);
}
}
if(value != null) {
return new TimeDistributionConstant(value);
} else {
// optimize overlapping mulranges
for(int i = 2; i < entries.size(); ++i) {
if(entries.get(i - 1) instanceof TimeDistributionComplex.EntryMulrange && entries.get(i) instanceof TimeDistributionComplex.EntryMulrange) {
final TimeDistributionComplex.EntryMulrange earlier = (TimeDistributionComplex.EntryMulrange)entries.get(i - 1);
final TimeDistributionComplex.EntryMulrange later = (TimeDistributionComplex.EntryMulrange)entries.get(i);
if(earlier.multiplier == 0 && later.multiplier == 0) {
if(earlier.start < later.start && later.start <= earlier.end) {
earlier.start = earlier.start;
earlier.end = earlier.end < later.end? later.end: earlier.end;
entries.remove(i);
--i;
} else if(later.start < earlier.start && earlier.start <= later.end) { // it is actually backwards
earlier.start = later.start;
earlier.end = earlier.end < later.end? later.end: earlier.end;
entries.remove(i);
--i;
}
}
}
}
return new TimeDistributionComplex(entries.toArray(new TimeDistributionComplex.Entry[entries.size()]));
}
}
|
diff --git a/src/main/java/org/jenkinsci/plugins/xunit/types/QTestlibType.java b/src/main/java/org/jenkinsci/plugins/xunit/types/QTestlibType.java
index e0cc386..cb7a951 100644
--- a/src/main/java/org/jenkinsci/plugins/xunit/types/QTestlibType.java
+++ b/src/main/java/org/jenkinsci/plugins/xunit/types/QTestlibType.java
@@ -1,43 +1,43 @@
package org.jenkinsci.plugins.xunit.types;
import com.thalesgroup.dtkit.metrics.hudson.api.descriptor.TestTypeDescriptor;
import com.thalesgroup.dtkit.metrics.hudson.api.type.TestType;
import com.thalesgroup.dtkit.metrics.model.InputMetric;
import com.thalesgroup.dtkit.metrics.model.InputMetricException;
import com.thalesgroup.dtkit.metrics.model.InputMetricFactory;
import hudson.Extension;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* @author Gregory Boissinot
*/
public class QTestLibType extends TestType {
@DataBoundConstructor
public QTestLibType(String pattern, boolean failIfNotNew, boolean deleteOutputFiles, boolean stopProcessingIfError) {
super(pattern, failIfNotNew, deleteOutputFiles, stopProcessingIfError);
}
@Extension
public static class QTestLibTypeDescriptor extends TestTypeDescriptor<QTestLibType> {
public QTestLibTypeDescriptor() {
super(QTestLibType.class, null);
}
@Override
public String getId() {
return this.getClass().getName();
}
@Override
public InputMetric getInputMetric() {
try {
- return InputMetricFactory.getInstance(CheckInputMetric.class);
+ return InputMetricFactory.getInstance(QTestLibInputMetric.class);
} catch (InputMetricException e) {
- throw new RuntimeException("Can't create the inputMetric object for the class " + CheckInputMetric.class);
+ throw new RuntimeException("Can't create the inputMetric object for the class " + QTestLibInputMetric.class);
}
}
}
}
| false | true |
public InputMetric getInputMetric() {
try {
return InputMetricFactory.getInstance(CheckInputMetric.class);
} catch (InputMetricException e) {
throw new RuntimeException("Can't create the inputMetric object for the class " + CheckInputMetric.class);
}
}
|
public InputMetric getInputMetric() {
try {
return InputMetricFactory.getInstance(QTestLibInputMetric.class);
} catch (InputMetricException e) {
throw new RuntimeException("Can't create the inputMetric object for the class " + QTestLibInputMetric.class);
}
}
|
diff --git a/blocksworld/Algorithm.java b/blocksworld/Algorithm.java
index 2f39d9b..9bb47a1 100644
--- a/blocksworld/Algorithm.java
+++ b/blocksworld/Algorithm.java
@@ -1,80 +1,80 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package blocksworld;
import java.util.ArrayList;
import operators.Operator;
import predicates.Predicate;
/**
*
* @author gaspercat
*/
public class Algorithm {
private ArrayList<State> states;
private ArrayList<Object> stack;
public Algorithm(){
this.states = new ArrayList<State>();
this.stack = new ArrayList<Object>();
}
public void run(State initial, State goal){
State state = initial;
ArrayList<Operator> plan = new ArrayList<Operator>();
stack.add(goal);
stack.add(goal.getPredicates());
while(stack.size() > 0){
Object c = stack.remove(stack.size()-1);
// If c is an operator
if(c instanceof Operator){
plan.add((Operator)c);
state = new State(state, (Operator)c);
// If c is a condition not fully instanced
}else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){
instanceCondition(state, (Predicate)c);
stack.add(c);
// If c is a condition fully instanced
}else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){
Predicate pred = (Predicate)c;
if(!state.hasPredicate(pred)){
// TODO
}
// If c is a list of conditions
}else if(c instanceof Preconditions){
ArrayList<Predicate> unmet = state.getUnmetConditions((Preconditions)c);
if(unmet.size() > 0){
stack.add(c);
- stack.add(unmet);
+ stack.addAll(unmet);
}
}
}
}
private void instanceCondition(State state, Predicate pred){
// Get related operator
Operator op = null;
for(int i=stack.size()-1;;i--){
if(stack.get(i) instanceof Operator){
op = (Operator)stack.get(i);
break;
}
}
// Define value at operator
op.instanceValues(pred, state);
}
private void clear(){
this.states.clear();
this.stack.clear();
}
}
| true | true |
public void run(State initial, State goal){
State state = initial;
ArrayList<Operator> plan = new ArrayList<Operator>();
stack.add(goal);
stack.add(goal.getPredicates());
while(stack.size() > 0){
Object c = stack.remove(stack.size()-1);
// If c is an operator
if(c instanceof Operator){
plan.add((Operator)c);
state = new State(state, (Operator)c);
// If c is a condition not fully instanced
}else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){
instanceCondition(state, (Predicate)c);
stack.add(c);
// If c is a condition fully instanced
}else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){
Predicate pred = (Predicate)c;
if(!state.hasPredicate(pred)){
// TODO
}
// If c is a list of conditions
}else if(c instanceof Preconditions){
ArrayList<Predicate> unmet = state.getUnmetConditions((Preconditions)c);
if(unmet.size() > 0){
stack.add(c);
stack.add(unmet);
}
}
}
}
|
public void run(State initial, State goal){
State state = initial;
ArrayList<Operator> plan = new ArrayList<Operator>();
stack.add(goal);
stack.add(goal.getPredicates());
while(stack.size() > 0){
Object c = stack.remove(stack.size()-1);
// If c is an operator
if(c instanceof Operator){
plan.add((Operator)c);
state = new State(state, (Operator)c);
// If c is a condition not fully instanced
}else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){
instanceCondition(state, (Predicate)c);
stack.add(c);
// If c is a condition fully instanced
}else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){
Predicate pred = (Predicate)c;
if(!state.hasPredicate(pred)){
// TODO
}
// If c is a list of conditions
}else if(c instanceof Preconditions){
ArrayList<Predicate> unmet = state.getUnmetConditions((Preconditions)c);
if(unmet.size() > 0){
stack.add(c);
stack.addAll(unmet);
}
}
}
}
|
diff --git a/src/com/htb/cnk/data/MyOrder.java b/src/com/htb/cnk/data/MyOrder.java
index 0929ad6..752a5eb 100644
--- a/src/com/htb/cnk/data/MyOrder.java
+++ b/src/com/htb/cnk/data/MyOrder.java
@@ -1,481 +1,481 @@
package com.htb.cnk.data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import com.htb.cnk.lib.Http;
import com.htb.constant.Server;
public class MyOrder {
private int MODE_PAD = 0;
private int MODE_PHONE = 1;
public class OrderedDish {
Dish dish;
int padQuantity;
int phoneQuantity;
int orderDishId;
int tableId;
public OrderedDish(Dish dish, int quantity, int tableId, int type) {
this.dish = dish;
this.tableId = tableId;
if (type == MODE_PAD) {
this.padQuantity = quantity;
this.phoneQuantity = 0;
} else if (type == MODE_PHONE) {
this.phoneQuantity = quantity;
this.padQuantity = 0;
}
}
public OrderedDish(Dish dish, int quantity, int id, int tableId,
int type) {
this.dish = dish;
this.orderDishId = id;
this.tableId = tableId;
if (type == MODE_PAD) {
this.padQuantity = quantity;
this.phoneQuantity = 0;
} else if (type == MODE_PHONE) {
this.phoneQuantity = quantity;
this.padQuantity = 0;
}
}
public String getName() {
return dish.getName();
}
public int getQuantity() {
return padQuantity + phoneQuantity;
}
public double getPrice() {
return dish.getPrice();
}
public int getDishId() {
return this.orderDishId;
}
public int getId() {
return dish.getId();
}
public int getTableId() {
return this.tableId;
}
}
private CnkDbHelper mCnkDbHelper;
protected SQLiteDatabase mDb;
protected static List<OrderedDish> mOrder = new ArrayList<OrderedDish>();
public MyOrder(Context context) {
mCnkDbHelper = new CnkDbHelper(context, CnkDbHelper.DATABASE_NAME,
null, 1);
mDb = mCnkDbHelper.getReadableDatabase();
}
public int addOrder(Dish dish, int quantity, int tableId, int type) {
for (OrderedDish item : mOrder) {
if (item.dish.getId() == dish.getId()) {
if (type == MODE_PAD) {
item.padQuantity += quantity;
} else if (type == MODE_PHONE) {
item.phoneQuantity += quantity;
}
return 0;
}
}
mOrder.add(new OrderedDish(dish, quantity, tableId, type));
return 0;
}
public int add(Dish dish, int quantity, int tableId, int type) {
for (OrderedDish item : mOrder) {
if (item.dish.getId() == dish.getId()) {
item.padQuantity += quantity;
return 0;
}
}
mOrder.add(new OrderedDish(dish, quantity, tableId, type));
return 0;
}
public int addItem(Dish dish, int quantity, int id, int tableId) {
for (OrderedDish item : mOrder) {
if (item.dish.getId() == dish.getId()) {
item.padQuantity += quantity;
return 0;
}
}
mOrder.add(new OrderedDish(dish, quantity, id, tableId));
return 0;
}
public int add(int position, int quantity) {
mOrder.get(position).padQuantity += quantity;
return 0;
}
public int minus(Dish dish, int quantity) {
for (OrderedDish item : mOrder) {
if (item.dish.getId() == dish.getId()) {
if (item.padQuantity > 0) {
item.padQuantity -= quantity;
} else if (item.padQuantity == 0 && item.phoneQuantity > 0) {
item.phoneQuantity -= quantity;
} else {
mOrder.remove(item);
}
return 0;
}
}
return 0;
}
public int minus(int position, int quantity) {
if ((mOrder.get(position).padQuantity + mOrder.get(position).phoneQuantity) > quantity) {
if (mOrder.get(position).padQuantity > quantity) {
mOrder.get(position).padQuantity -= quantity;
} else {
quantity -= mOrder.get(position).padQuantity;
mOrder.get(position).padQuantity = 0;
mOrder.get(position).phoneQuantity -= quantity;
return mOrder.get(position).phoneQuantity;
}
} else {
mOrder.remove(position);
}
return 0;
}
public int count() {
return mOrder.size();
}
public int totalQuantity() {
int count = 0;
for (OrderedDish item : mOrder) {
count += (item.padQuantity + item.phoneQuantity);
}
return count;
}
public int getDishId(int position) {
if (position < mOrder.size()) {
return mOrder.get(position).dish.getId();
}
return -1;
}
public double getTotalPrice() {
double totalPrice = 0;
for (OrderedDish item : mOrder) {
totalPrice += (item.padQuantity + item.phoneQuantity)
* item.dish.getPrice();
}
return totalPrice;
}
public int getTableId() {
return mOrder.get(0).getTableId();
}
public OrderedDish getOrderedDish(int position) {
return mOrder.get(position);
}
public void removeItem(int did) {
mOrder.remove(did);
}
public void clear() {
mOrder.clear();
}
public void phoneClear(){
for (int i = 0; i < mOrder.size(); i++) {
OrderedDish item = (OrderedDish) mOrder.get(i);
if (item.padQuantity == 0) {
mOrder.remove(item);
i--;
} else {
item.phoneQuantity = 0;
}
}
}
public void talbeClear() {
if (count() > 0 && getTableId() != Info.getTableId()) {
mOrder.clear();
Log.d("talbeClear", "clear");
}
}
public int getOrderedCount(int did) {
for (OrderedDish dish : mOrder) {
if (dish.getId() == did) {
return (dish.padQuantity + dish.phoneQuantity);
}
}
return 0;
}
public String submit() {
JSONObject order = new JSONObject();
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(date);
if (mOrder.size() <= 0) {
return null;
}
try {
order.put("tableId", Info.getTableId());
order.put("tableName", Info.getTableName());
order.put("timestamp", time);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray dishes = new JSONArray();
try {
for (int i = 0; i < mOrder.size(); i++) {
JSONObject dish = new JSONObject();
dish.put("id", mOrder.get(i).dish.getId());
dish.put("name", mOrder.get(i).dish.getName());
dish.put("price", mOrder.get(i).dish.getPrice());
dish.put(
"quan",
(mOrder.get(i).padQuantity + mOrder.get(i).phoneQuantity));
dishes.put(dish);
}
order.put("order", dishes);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON", order.toString());
String response = Http.post(Server.SUBMIT_ORDER, order.toString());
if (response == null) {
Log.d("Respond", "ok");
} else {
Log.d("Respond", response);
}
return response;
}
public int getTableFromDB(int tableId) {
String response = Http.get(Server.GET_MYORDER, "TID=" + tableId);
Log.d("resp", response);
try {
JSONArray tableList = new JSONArray(response);
int length = tableList.length();
clear();
for (int i = 0; i < length; i++) {
JSONObject item = tableList.getJSONObject(i);
int quantity = item.getInt("quantity");
int dishId = item.getInt("dish_id");
double dishPrice = item.getInt("price");
Log.d("tableFromDB", "quantity" + quantity + "dishId" + dishId
+ "dishPrice" + dishPrice);
String name = getDishName(dishId);
Dish mDish = new Dish(dishId, name, dishPrice, null);
addOrder(mDish, quantity, tableId, MODE_PAD);
}
return 0;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public int getTablePhoneFromDB(int tableId) {
talbeClear();
String response = Http.get(Server.GET_GETPHONEORDER, "TID=" + tableId);
Log.d("resp", "Phone:" + response);
if (response == null) {
return -1;
}
try {
JSONArray tableList = new JSONArray(response);
int length = tableList.length();
for (int i = 0; i < mOrder.size(); i++) {
OrderedDish item = (OrderedDish) mOrder.get(i);
if (item.padQuantity == 0) {
mOrder.remove(item);
i--;
} else {
item.phoneQuantity = 0;
}
}
for (int i = 0; i < length; i++) {
JSONObject item = tableList.getJSONObject(i);
int quantity = item.getInt("quantity");
int dishId = item.getInt("dish_id");
Cursor cur = getDishNameAndPriceFromDB(dishId);
String name = cur.getString(0);
double dishPrice = cur.getDouble(1);
Dish mDish = new Dish(dishId, name, dishPrice, null);
addOrder(mDish, quantity, tableId, MODE_PHONE);
Log.d("phone", "phoneNum :" + i);
}
return 0;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public String getDishName(int index) {
String name = getDishNameFromDB(index);
if (name == null) {
return "菜名为空";
}
return name;
}
private String getDishNameFromDB(int id) {
Cursor cur = mDb.query(CnkDbHelper.DISH_TABLE_NAME,
new String[] { CnkDbHelper.DISH_NAME }, CnkDbHelper.DISH_ID
+ "=" + id, null, null, null, null);
if (cur.moveToNext()) {
return cur.getString(0);
}
return null;
}
private Cursor getDishNameAndPriceFromDB(int id) {
Cursor cur = mDb.query(CnkDbHelper.DISH_TABLE_NAME, new String[] {
CnkDbHelper.DISH_NAME, CnkDbHelper.DISH_PRICE },
CnkDbHelper.DISH_ID + "=" + id, null, null, null, null);
if (cur.moveToNext()) {
return cur;
}
return null;
}
public int delPhoneTable(int tableId, int dishId) {
String tableStatusPkg;
if (dishId == 0) {
tableStatusPkg = Http.get(Server.DELETE_PHONEORDER, "TID="
+ tableId);
} else {
tableStatusPkg = Http.get(Server.DELETE_PHONEORDER, "TID="
+ tableId + "&DID=" + dishId);
}
Log.d("Respond", "tableStatusPkg: " + tableStatusPkg);
if (tableStatusPkg == null) {
return -1;
}
return 0;
}
public int updatePhoneOrder(int tableId, int quantity, int dishId) {
String phoneOrderPkg = Http.get(Server.UPDATE_PHONE_ORDER, "DID="
+ dishId + "&DNUM=" + quantity + "&TID=" + tableId);
Log.d("resp", "resp:" + phoneOrderPkg);
if (phoneOrderPkg == null) {
return -1;
}
return 0;
}
public int delDish(int dishId) {
Log.d("DID", "" + dishId);
JSONObject order = new JSONObject();
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(date);
if (mOrder.size() <= 0) {
return -1;
}
try {
order.put("tableId", Info.getTableId());
order.put("tableName", Info.getTableName());
order.put("timestamp", time);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray dishes = new JSONArray();
try {
if (dishId == -1) {
for (int i = 0; i < mOrder.size(); i++) {
JSONObject dish = new JSONObject();
- dish.put("disId", mOrder.get(i).dish.getId());
+ dish.put("dishId", mOrder.get(i).dish.getId());
dish.put("name", mOrder.get(i).dish.getName());
dish.put("price", mOrder.get(i).dish.getPrice());
dish.put(
"quan",
(mOrder.get(i).padQuantity + mOrder.get(i).phoneQuantity));
dish.put("id", mOrder.get(i).getDishId());
dishes.put(dish);
}
} else {
JSONObject dish = new JSONObject();
dish.put("dishId", mOrder.get(dishId).dish.getId());
dish.put("name", mOrder.get(dishId).dish.getName());
dish.put("price", mOrder.get(dishId).dish.getPrice());
dish.put(
"quan",
(mOrder.get(dishId).padQuantity + mOrder.get(dishId).phoneQuantity));
dish.put("id", mOrder.get(dishId).getDishId());
dishes.put(dish);
}
order.put("order", dishes);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON", order.toString());
String response = Http.post(Server.DEL_ORDER, order.toString());
Log.d("response", "response:"+response);
if (response == null) {
return -1;
}
return 0;
}
@Override
protected void finalize() throws Throwable {
if (mDb != null) {
mDb.close();
}
super.finalize();
}
}
| true | true |
public int delDish(int dishId) {
Log.d("DID", "" + dishId);
JSONObject order = new JSONObject();
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(date);
if (mOrder.size() <= 0) {
return -1;
}
try {
order.put("tableId", Info.getTableId());
order.put("tableName", Info.getTableName());
order.put("timestamp", time);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray dishes = new JSONArray();
try {
if (dishId == -1) {
for (int i = 0; i < mOrder.size(); i++) {
JSONObject dish = new JSONObject();
dish.put("disId", mOrder.get(i).dish.getId());
dish.put("name", mOrder.get(i).dish.getName());
dish.put("price", mOrder.get(i).dish.getPrice());
dish.put(
"quan",
(mOrder.get(i).padQuantity + mOrder.get(i).phoneQuantity));
dish.put("id", mOrder.get(i).getDishId());
dishes.put(dish);
}
} else {
JSONObject dish = new JSONObject();
dish.put("dishId", mOrder.get(dishId).dish.getId());
dish.put("name", mOrder.get(dishId).dish.getName());
dish.put("price", mOrder.get(dishId).dish.getPrice());
dish.put(
"quan",
(mOrder.get(dishId).padQuantity + mOrder.get(dishId).phoneQuantity));
dish.put("id", mOrder.get(dishId).getDishId());
dishes.put(dish);
}
order.put("order", dishes);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON", order.toString());
String response = Http.post(Server.DEL_ORDER, order.toString());
Log.d("response", "response:"+response);
if (response == null) {
return -1;
}
return 0;
}
|
public int delDish(int dishId) {
Log.d("DID", "" + dishId);
JSONObject order = new JSONObject();
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(date);
if (mOrder.size() <= 0) {
return -1;
}
try {
order.put("tableId", Info.getTableId());
order.put("tableName", Info.getTableName());
order.put("timestamp", time);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray dishes = new JSONArray();
try {
if (dishId == -1) {
for (int i = 0; i < mOrder.size(); i++) {
JSONObject dish = new JSONObject();
dish.put("dishId", mOrder.get(i).dish.getId());
dish.put("name", mOrder.get(i).dish.getName());
dish.put("price", mOrder.get(i).dish.getPrice());
dish.put(
"quan",
(mOrder.get(i).padQuantity + mOrder.get(i).phoneQuantity));
dish.put("id", mOrder.get(i).getDishId());
dishes.put(dish);
}
} else {
JSONObject dish = new JSONObject();
dish.put("dishId", mOrder.get(dishId).dish.getId());
dish.put("name", mOrder.get(dishId).dish.getName());
dish.put("price", mOrder.get(dishId).dish.getPrice());
dish.put(
"quan",
(mOrder.get(dishId).padQuantity + mOrder.get(dishId).phoneQuantity));
dish.put("id", mOrder.get(dishId).getDishId());
dishes.put(dish);
}
order.put("order", dishes);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON", order.toString());
String response = Http.post(Server.DEL_ORDER, order.toString());
Log.d("response", "response:"+response);
if (response == null) {
return -1;
}
return 0;
}
|
diff --git a/curator-x-discovery/src/test/java/com/netflix/curator/x/discovery/TestServiceDiscovery.java b/curator-x-discovery/src/test/java/com/netflix/curator/x/discovery/TestServiceDiscovery.java
index 5dc549cb..cc61e503 100644
--- a/curator-x-discovery/src/test/java/com/netflix/curator/x/discovery/TestServiceDiscovery.java
+++ b/curator-x-discovery/src/test/java/com/netflix/curator/x/discovery/TestServiceDiscovery.java
@@ -1,160 +1,162 @@
/*
*
* Copyright 2011 Netflix, 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.netflix.curator.x.discovery;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryOneTime;
import com.netflix.curator.test.KillSession;
import com.netflix.curator.test.TestingServer;
import com.netflix.curator.x.discovery.details.JsonInstanceSerializer;
import com.netflix.curator.x.discovery.details.ServiceDiscoveryImpl;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.Closeable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class TestServiceDiscovery
{
@Test
public void testCrashedInstance() throws Exception
{
List<Closeable> closeables = Lists.newArrayList();
TestingServer server = new TestingServer();
closeables.add(server);
try
{
final int TIMEOUT_SECONDS = 5;
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), TIMEOUT_SECONDS * 1000, TIMEOUT_SECONDS * 1000, new RetryOneTime(1));
closeables.add(client);
client.start();
ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance);
closeables.add(discovery);
discovery.start();
Assert.assertEquals(discovery.queryForInstances("test").size(), 1);
KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
Assert.assertEquals(discovery.queryForInstances("test").size(), 0);
}
finally
{
Collections.reverse(closeables);
for ( Closeable c : closeables )
{
Closeables.closeQuietly(c);
}
}
}
@Test
public void testMultipleInstances() throws Exception
{
final String SERVICE_ONE = "one";
final String SERVICE_TWO = "two";
List<Closeable> closeables = Lists.newArrayList();
TestingServer server = new TestingServer();
closeables.add(server);
try
{
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
closeables.add(client);
client.start();
ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceDiscovery<Void> discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build();
closeables.add(discovery);
discovery.start();
discovery.registerService(s1_i1);
discovery.registerService(s1_i2);
discovery.registerService(s2_i1);
discovery.registerService(s2_i2);
Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO));
Collection<ServiceInstance<Void>> list = Sets.newHashSet();
list.add(s1_i1);
list.add(s1_i2);
- Assert.assertEquals(Sets.<ServiceInstance<Void>>newHashSet(discovery.queryForInstances(SERVICE_ONE)), list);
+ Collection<ServiceInstance<Void>> queriedInstances = Sets.newHashSet(discovery.queryForInstances(SERVICE_ONE));
+ Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));
list.clear();
list.add(s2_i1);
list.add(s2_i2);
- Assert.assertEquals(Sets.<ServiceInstance<Void>>newHashSet(discovery.queryForInstances(SERVICE_TWO)), list);
+ queriedInstances = Sets.newHashSet(discovery.queryForInstances(SERVICE_TWO));
+ Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));
}
finally
{
Collections.reverse(closeables);
for ( Closeable c : closeables )
{
Closeables.closeQuietly(c);
}
}
}
@Test
public void testBasic() throws Exception
{
List<Closeable> closeables = Lists.newArrayList();
TestingServer server = new TestingServer();
closeables.add(server);
try
{
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
closeables.add(client);
client.start();
ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
closeables.add(discovery);
discovery.start();
Assert.assertEquals(discovery.queryForNames(), Arrays.asList("test"));
List<ServiceInstance<String>> list = Lists.newArrayList();
list.add(instance);
Assert.assertEquals(discovery.queryForInstances("test"), list);
}
finally
{
Collections.reverse(closeables);
for ( Closeable c : closeables )
{
Closeables.closeQuietly(c);
}
}
}
}
| false | true |
public void testMultipleInstances() throws Exception
{
final String SERVICE_ONE = "one";
final String SERVICE_TWO = "two";
List<Closeable> closeables = Lists.newArrayList();
TestingServer server = new TestingServer();
closeables.add(server);
try
{
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
closeables.add(client);
client.start();
ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceDiscovery<Void> discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build();
closeables.add(discovery);
discovery.start();
discovery.registerService(s1_i1);
discovery.registerService(s1_i2);
discovery.registerService(s2_i1);
discovery.registerService(s2_i2);
Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO));
Collection<ServiceInstance<Void>> list = Sets.newHashSet();
list.add(s1_i1);
list.add(s1_i2);
Assert.assertEquals(Sets.<ServiceInstance<Void>>newHashSet(discovery.queryForInstances(SERVICE_ONE)), list);
list.clear();
list.add(s2_i1);
list.add(s2_i2);
Assert.assertEquals(Sets.<ServiceInstance<Void>>newHashSet(discovery.queryForInstances(SERVICE_TWO)), list);
}
finally
{
Collections.reverse(closeables);
for ( Closeable c : closeables )
{
Closeables.closeQuietly(c);
}
}
}
|
public void testMultipleInstances() throws Exception
{
final String SERVICE_ONE = "one";
final String SERVICE_TWO = "two";
List<Closeable> closeables = Lists.newArrayList();
TestingServer server = new TestingServer();
closeables.add(server);
try
{
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
closeables.add(client);
client.start();
ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
ServiceDiscovery<Void> discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build();
closeables.add(discovery);
discovery.start();
discovery.registerService(s1_i1);
discovery.registerService(s1_i2);
discovery.registerService(s2_i1);
discovery.registerService(s2_i2);
Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO));
Collection<ServiceInstance<Void>> list = Sets.newHashSet();
list.add(s1_i1);
list.add(s1_i2);
Collection<ServiceInstance<Void>> queriedInstances = Sets.newHashSet(discovery.queryForInstances(SERVICE_ONE));
Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));
list.clear();
list.add(s2_i1);
list.add(s2_i2);
queriedInstances = Sets.newHashSet(discovery.queryForInstances(SERVICE_TWO));
Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));
}
finally
{
Collections.reverse(closeables);
for ( Closeable c : closeables )
{
Closeables.closeQuietly(c);
}
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/editor/sections/ServicesSection.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/editor/sections/ServicesSection.java
index 18395e78f..e19986d60 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/editor/sections/ServicesSection.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/editor/sections/ServicesSection.java
@@ -1,183 +1,184 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.ui.editor.sections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.core.runtime.Assert;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer;
import org.eclipse.tcf.te.runtime.properties.PropertiesContainer;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModelProperties;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelPeerNodeQueryService;
import org.eclipse.tcf.te.tcf.ui.nls.Messages;
import org.eclipse.tcf.te.ui.forms.parts.AbstractSection;
import org.eclipse.tcf.te.ui.swt.SWTControlUtil;
import org.eclipse.tcf.te.ui.views.editor.pages.AbstractEditorPage;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
/**
* Peer services section implementation.
*/
public class ServicesSection extends AbstractSection {
// The section sub controls
private Text local;
private Text remote;
// Reference to the original data object
/* default */ IPeerModel od;
// Reference to a copy of the original data
/* default */ final IPropertiesContainer odc = new PropertiesContainer();
/**
* Constructor.
*
* @param form The parent managed form. Must not be <code>null</code>.
* @param parent The parent composite. Must not be <code>null</code>.
*/
public ServicesSection(IManagedForm form, Composite parent) {
super(form, parent, Section.DESCRIPTION | ExpandableComposite.TWISTIE);
createClient(getSection(), form.getToolkit());
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.ui.forms.parts.AbstractSection#createClient(org.eclipse.ui.forms.widgets.Section, org.eclipse.ui.forms.widgets.FormToolkit)
*/
@Override
protected void createClient(Section section, FormToolkit toolkit) {
Assert.isNotNull(section);
Assert.isNotNull(toolkit);
// Configure the section
section.setText(Messages.ServicesSection_title);
section.setDescription(Messages.ServicesSection_description);
if (section.getParent().getLayout() instanceof GridLayout) {
section.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
}
// Create the section client
Composite client = createClientContainer(section, 1, toolkit);
Assert.isNotNull(client);
section.setClient(client);
Group group = new Group(client, SWT.NONE);
group.setText(Messages.ServicesSection_group_local_title);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
local = new Text(group, SWT.READ_ONLY | SWT.WRAP | SWT.MULTI);
GridData layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
layoutData.widthHint = SWTControlUtil.convertWidthInCharsToPixels(local, 20);
layoutData.heightHint = SWTControlUtil.convertHeightInCharsToPixels(local, 5);
local.setLayoutData(layoutData);
group = new Group(client, SWT.NONE);
group.setText(Messages.ServicesSection_group_remote_title);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
remote = new Text(group, SWT.READ_ONLY | SWT.WRAP | SWT.MULTI);
layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
layoutData.widthHint = SWTControlUtil.convertWidthInCharsToPixels(local, 20);
layoutData.heightHint = SWTControlUtil.convertHeightInCharsToPixels(remote, 5);
remote.setLayoutData(layoutData);
// Mark the control update as completed now
setIsUpdating(false);
}
/**
* Indicates whether the sections parent page has become the active in the editor.
*
* @param active <code>True</code> if the parent page should be visible, <code>false</code> otherwise.
*/
public void setActive(boolean active) {
// If the parent page has become the active and it does not contain
// unsaved data, than fill in the data from the selected node
if (active) {
// Leave everything unchanged if the page is in dirty state
if (getManagedForm().getContainer() instanceof AbstractEditorPage
&& !((AbstractEditorPage)getManagedForm().getContainer()).isDirty()) {
Object node = ((AbstractEditorPage)getManagedForm().getContainer()).getEditorInputNode();
if (node instanceof IPeerModel) {
setupData((IPeerModel)node);
}
}
}
}
/**
* Initialize the page widgets based of the data from the given peer node.
* <p>
* This method may called multiple times during the lifetime of the page and
* the given configuration node might be even <code>null</code>.
*
* @param node The peer node or <code>null</code>.
*/
public void setupData(final IPeerModel node) {
// Store a reference to the original data
od = node;
// Clean the original data copy
odc.clearProperties();
// If no data is available, we are done
if (node == null) return;
// Trigger the query of the services provided by the node
final AtomicBoolean needQueryServices = new AtomicBoolean();
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
- needQueryServices.set(node.getStringProperty(IPeerModelProperties.PROP_LOCAL_SERVICES) != null
- || node.getStringProperty(IPeerModelProperties.PROP_REMOTE_SERVICES) != null);
+ // If one services key is set, the other is set to. The more important information
+ // is the remote services, so test for the remote services key.
+ needQueryServices.set(!node.containsKey(IPeerModelProperties.PROP_REMOTE_SERVICES));
}
});
if (needQueryServices.get()) {
node.getModel().getService(ILocatorModelPeerNodeQueryService.class).queryLocalServices(node);
}
// Thread access to the model is limited to the executors thread.
// Copy the data over to the working copy to ease the access.
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
Map<String, Object> properties = od.getProperties();
odc.setProperties(properties);
}
});
boolean fireRefreshTabs = needQueryServices.get();
String value = odc.getStringProperty(IPeerModelProperties.PROP_LOCAL_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(local));
SWTControlUtil.setText(local, value != null ? value : ""); //$NON-NLS-1$
value = odc.getStringProperty(IPeerModelProperties.PROP_REMOTE_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(remote));
SWTControlUtil.setText(remote, value != null ? value : ""); //$NON-NLS-1$
if (fireRefreshTabs) {
// Fire a change event to trigger the editor refresh
od.fireChangeEvent("editor.refreshTab", Boolean.FALSE, Boolean.TRUE); //$NON-NLS-1$
}
}
}
| true | true |
public void setupData(final IPeerModel node) {
// Store a reference to the original data
od = node;
// Clean the original data copy
odc.clearProperties();
// If no data is available, we are done
if (node == null) return;
// Trigger the query of the services provided by the node
final AtomicBoolean needQueryServices = new AtomicBoolean();
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
needQueryServices.set(node.getStringProperty(IPeerModelProperties.PROP_LOCAL_SERVICES) != null
|| node.getStringProperty(IPeerModelProperties.PROP_REMOTE_SERVICES) != null);
}
});
if (needQueryServices.get()) {
node.getModel().getService(ILocatorModelPeerNodeQueryService.class).queryLocalServices(node);
}
// Thread access to the model is limited to the executors thread.
// Copy the data over to the working copy to ease the access.
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
Map<String, Object> properties = od.getProperties();
odc.setProperties(properties);
}
});
boolean fireRefreshTabs = needQueryServices.get();
String value = odc.getStringProperty(IPeerModelProperties.PROP_LOCAL_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(local));
SWTControlUtil.setText(local, value != null ? value : ""); //$NON-NLS-1$
value = odc.getStringProperty(IPeerModelProperties.PROP_REMOTE_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(remote));
SWTControlUtil.setText(remote, value != null ? value : ""); //$NON-NLS-1$
if (fireRefreshTabs) {
// Fire a change event to trigger the editor refresh
od.fireChangeEvent("editor.refreshTab", Boolean.FALSE, Boolean.TRUE); //$NON-NLS-1$
}
}
|
public void setupData(final IPeerModel node) {
// Store a reference to the original data
od = node;
// Clean the original data copy
odc.clearProperties();
// If no data is available, we are done
if (node == null) return;
// Trigger the query of the services provided by the node
final AtomicBoolean needQueryServices = new AtomicBoolean();
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
// If one services key is set, the other is set to. The more important information
// is the remote services, so test for the remote services key.
needQueryServices.set(!node.containsKey(IPeerModelProperties.PROP_REMOTE_SERVICES));
}
});
if (needQueryServices.get()) {
node.getModel().getService(ILocatorModelPeerNodeQueryService.class).queryLocalServices(node);
}
// Thread access to the model is limited to the executors thread.
// Copy the data over to the working copy to ease the access.
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
Map<String, Object> properties = od.getProperties();
odc.setProperties(properties);
}
});
boolean fireRefreshTabs = needQueryServices.get();
String value = odc.getStringProperty(IPeerModelProperties.PROP_LOCAL_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(local));
SWTControlUtil.setText(local, value != null ? value : ""); //$NON-NLS-1$
value = odc.getStringProperty(IPeerModelProperties.PROP_REMOTE_SERVICES);
fireRefreshTabs |= value != null && !value.equals(SWTControlUtil.getText(remote));
SWTControlUtil.setText(remote, value != null ? value : ""); //$NON-NLS-1$
if (fireRefreshTabs) {
// Fire a change event to trigger the editor refresh
od.fireChangeEvent("editor.refreshTab", Boolean.FALSE, Boolean.TRUE); //$NON-NLS-1$
}
}
|
diff --git a/src/main/java/javax/time/chrono/Chrono.java b/src/main/java/javax/time/chrono/Chrono.java
index d6382004..3ecf4660 100644
--- a/src/main/java/javax/time/chrono/Chrono.java
+++ b/src/main/java/javax/time/chrono/Chrono.java
@@ -1,729 +1,729 @@
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time.chrono;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.time.Clock;
import javax.time.DateTimeException;
import javax.time.Instant;
import javax.time.LocalDate;
import javax.time.LocalDateTime;
import javax.time.LocalTime;
import javax.time.ZoneId;
import javax.time.ZoneOffset;
import javax.time.calendrical.ChronoField;
import javax.time.calendrical.DateTime;
import javax.time.calendrical.DateTimeAccessor;
import javax.time.calendrical.DateTimeAccessor.Query;
import javax.time.calendrical.DateTimeField;
import javax.time.calendrical.DateTimeValueRange;
import javax.time.format.DateTimeFormatterBuilder;
import javax.time.format.TextStyle;
import javax.time.jdk8.DefaultInterfaceDateTimeAccessor;
import javax.time.zone.ZoneRules;
/**
* A calendar system, defining a set of human-scale date fields.
* <p>
* The main date and time API is built on the ISO calendar system.
* This class operates behind the scenes to represent the general concept of a calendar system.
* For example, the Gregorian, Japanese, Minguo, Thai Buddhist and others.
* <p>
* Most other calendar systems also operate on the shared concepts of year, month and day,
* linked to the cycles of the Earth around the Sun, and the Moon around the Earth.
* These shared concepts are defined by {@link ChronoField} and are availalbe
* for use by any {@code Chrono} implementation:
* <pre>
* LocalDate isoDate = ...
* ChronoLocalDate<ThaiBuddhistChrono> minguoDate = ...
* int isoYear = isoDate.get(ChronoField.YEAR);
* int thaiYear = thaiDate.get(ChronoField.YEAR);
* </pre>
* As shown, although the date objects are in different calendar systems, represented by different
* {@code Chrono} instances, both can be queried using the same constant on {@code ChronoField}.
* For a full discussion of the implications of this, see {@link ChronoLocalDate}.
* In general, the advice is to use the known ISO-based {@code LocalDate}, rather than
* {@code ChronoLocalDate}.
* <p>
* While a {@code Chrono} object typically uses {@code ChronoField} and is based on
* an era, year-of-era, month-of-year, day-of-month model of a date, this is not required.
* A {@code Chrono} instance may represent a totally different kind of calendar system,
* such as the Mayan.
* <p>
* In practical terms, the {@code Chrono} instance also acts as a factory.
* The {@link #of(String)} method allows an instance to be looked up by identifier,
* while the {@link #ofLocale(Locale)} method allows lookup by locale.
* <p>
* The {@code Chrono} instance provides a set of methods to create {@code ChronoLocalDate} instances.
* The date classes are used to manipulate specific dates.
* <p><ul>
* <li> {@link #dateNow() dateNow()}
* <li> {@link #dateNow(Clock) dateNow(clock)}
* <li> {@link #dateNow(ZoneId) dateNow(zone)}
* <li> {@link #date(int, int, int) date(yearProleptic, month, day)}
* <li> {@link #date(javax.time.chrono.Era, int, int, int) date(era, yearOfEra, month, day)}
* <li> {@link #dateYearDay(int, int) dateYearDay(yearProleptic, dayOfYear)}
* <li> {@link #dateYearDay(Era, int, int) dateYearDay(era, yearOfEra, dayOfYear)}
* <li> {@link #date(DateTimeAccessor) date(DateTimeAccessor)}
* </ul><p>
*
* <h4 id="addcalendars">Adding New Calendars</h4>
* The set of available chronologies can be extended by applications.
* Adding a new calendar system requires the writing of an implementation of
* {@code Chrono}, {@code ChronoLocalDate} and {@code Era}.
* The majority of the logic specific to the calendar system will be in
* {@code ChronoLocalDate}. The {@code Chrono} subclass acts as a factory.
* <p>
* To permit the discovery of additional chronologies, the {@link java.util.ServiceLoader ServiceLoader}
* is used. A file must be added to the {@code META-INF/services} directory with the
* name 'javax.time.chrono.Chrono' listing the implementation classes.
* See the service loader for more details on service loading.
* <p>
* Each chronology must define a chronology ID that is unique within the system.
* If the chronology represents a calendar system defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification then that
* calendar type should also be specified.
*
* <h4>Implementation notes</h4>
* This interface must be implemented with care to ensure other classes operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* Subclasses should be Serializable wherever possible.
*
* @param <C> the type of the implementing subclass
*/
public abstract class Chrono<C extends Chrono<C>> implements Comparable<Chrono<?>> {
/**
* Map of available calendars by ID.
*/
private static final ConcurrentHashMap<String, Chrono<?>> CHRONOS_BY_ID;
/**
* Map of available calendars by calendar type.
*/
private static final ConcurrentHashMap<String, Chrono<?>> CHRONOS_BY_TYPE;
static {
// TODO: defer initialization?
ConcurrentHashMap<String, Chrono<?>> ids = new ConcurrentHashMap<>();
ConcurrentHashMap<String, Chrono<?>> types = new ConcurrentHashMap<>();
@SuppressWarnings("rawtypes")
ServiceLoader<Chrono> loader = ServiceLoader.load(Chrono.class);
for (Chrono<?> chrono : loader) {
ids.putIfAbsent(chrono.getId(), chrono);
String type = chrono.getCalendarType();
if (type != null) {
types.putIfAbsent(type, chrono);
}
}
CHRONOS_BY_ID = ids;
CHRONOS_BY_TYPE = types;
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Chrono} from a date-time object.
* <p>
* A {@code DateTimeAccessor} represents some form of date and time information.
* This factory converts the arbitrary date-time object to an instance of {@code Chrono}.
* If the specified date-time object does not have a chronology, {@link ISOChrono} is returned.
*
* @param dateTime the date-time to convert, not null
* @return the chronology, not null
* @throws DateTimeException if unable to convert to an {@code Chrono}
*/
public static Chrono<?> from(DateTimeAccessor dateTime) {
Objects.requireNonNull(dateTime, "dateTime");
Chrono<?> obj = dateTime.query(Query.CHRONO);
return (obj != null ? obj : ISOChrono.INSTANCE);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Chrono} from a locale.
* <p>
* The locale can be used to identify a calendar.
* This uses {@link Locale#getUnicodeLocaleType(String)} to obtain the "ca" key
* to identify the calendar system.
* <p>
* If the locale does not contain calendar system information, the standard
* ISO calendar system is used.
*
* @param locale the locale to use to obtain the calendar system, not null
* @return the calendar system associated with the locale, not null
* @throws DateTimeException if the locale-specified calendar cannot be found
*/
public static Chrono<?> ofLocale(Locale locale) {
Objects.requireNonNull(locale, "locale");
String type = locale.getUnicodeLocaleType("ca");
if (type == null) {
return ISOChrono.INSTANCE;
} else if ("iso".equals(type) || "iso8601".equals(type)) {
return ISOChrono.INSTANCE;
} else {
Chrono<?> chrono = CHRONOS_BY_TYPE.get(type);
if (chrono == null) {
throw new DateTimeException("Unknown calendar system: " + type);
}
return chrono;
}
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Chrono} from a chronology ID or
* calendar system type.
* <p>
* This returns a chronology based on either the ID or the type.
* The {@link #getId() chronology ID} uniquely identifies the chronology.
* The {@link #getCalendarType() calendar system type} is defined by the LDML specification.
* <p>
* Since some calendars can be customized, the ID or type typically refers
* to the default customization. For example, the Gregorian calendar can have multiple
* cutover dates from the Julian, but the lookup only provides the default cutover date.
*
* @param id the chronology ID or calendar system type, not null
* @return the chronology with the identifier requested, not null
* @throws DateTimeException if the chronology cannot be found
*/
public static Chrono<?> of(String id) {
Chrono<?> chrono = CHRONOS_BY_ID.get(id);
if (chrono != null) {
return chrono;
}
chrono = CHRONOS_BY_TYPE.get(id);
if (chrono != null) {
return chrono;
}
throw new DateTimeException("Unknown chronology: " + id);
}
/**
* Returns the available chronologies.
* <p>
* Each returned {@code Chrono} is available for use in the system.
*
* @return the independent, modifiable set of the available chronology IDs, not null
*/
public static Set<Chrono<?>> getAvailableChronologies() {
return new HashSet<>(CHRONOS_BY_ID.values());
}
//-----------------------------------------------------------------------
/**
* Obtains a local date-time from the a date and time.
* <p>
* This combines a {@link ChronoLocalDate}, which provides the {@code Chrono},
* with a {@link LocalTime} to produce a {@link ChronoLocalDateTime}.
* <p>
* This method is intended for chronology implementations.
* It uses a standard implementation that is shared for all chronologies.
*
* @param <R> the chronology of the date
* @param date the date, not null
* @param time the time, not null
* @return the local date-time combining the input date and time, not null
*/
public static <R extends Chrono<R>> ChronoLocalDateTime<R> dateTime(ChronoLocalDate<R> date, LocalTime time) {
return ChronoDateTimeImpl.of(date, time);
}
//-----------------------------------------------------------------------
/**
* Creates an instance.
*/
protected Chrono() {
// register the subclass
CHRONOS_BY_ID.putIfAbsent(this.getId(), this);
String type = this.getCalendarType();
if (type != null) {
CHRONOS_BY_TYPE.putIfAbsent(type, this);
}
}
/**
* Casts the {@code DateTime} to {@code ChronoLocalDate} with the same chronology.
*
* @param dateTime a date-time to cast, not null
* @return the date-time checked and cast to {@code ChronoLocalDate}, not null
* @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate
* or the chronology is not equal this Chrono
*/
public /* package-scoped */ ChronoLocalDate<C> ensureChronoLocalDate(DateTime dateTime) { // TODO: non-public
@SuppressWarnings("unchecked")
ChronoLocalDate<C> other = (ChronoLocalDate<C>) dateTime;
if (this.equals(other.getChrono()) == false) {
throw new ClassCastException("Chrono mismatch, expected: " + getId() + ", actual: " + other.getChrono().getId());
}
return other;
}
/**
* Casts the {@code DateTime} to {@code ChronoLocalDateTime} with the same chronology.
*
* @param dateTime a date-time to cast, not null
* @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null
* @throws ClassCastException if the date-time cannot be cast to ChronoDateTimeImpl
* or the chronology is not equal this Chrono
*/
public /* package-scoped */ ChronoDateTimeImpl<C> ensureChronoLocalDateTime(DateTime dateTime) { // TODO: non-public
@SuppressWarnings("unchecked")
ChronoDateTimeImpl<C> other = (ChronoDateTimeImpl<C>) dateTime;
if (this.equals(other.getDate().getChrono()) == false) {
throw new ClassCastException("Chrono mismatch, required: " + getId()
+ ", supplied: " + other.getDate().getChrono().getId());
}
return other;
}
/**
* Casts the {@code DateTime} to {@code ChronoZonedDateTimeImpl} with the same chronology.
*
* @param dateTime a date-time to cast, not null
* @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null
* @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl
* or the chronology is not equal this Chrono
*/
public /* package-scoped */ ChronoZonedDateTimeImpl<C> ensureChronoZonedDateTime(DateTime dateTime) { // TODO: non-public
@SuppressWarnings("unchecked")
ChronoZonedDateTimeImpl<C> other = (ChronoZonedDateTimeImpl<C>) dateTime;
if (this.equals(other.getDate().getChrono()) == false) {
throw new ClassCastException("Chrono mismatch, required: " + getId()
+ ", supplied: " + other.getDate().getChrono().getId());
}
return other;
}
//-----------------------------------------------------------------------
/**
* Gets the ID of the chronology.
* <p>
* The ID uniquely identifies the {@code Chrono}.
* It can be used to lookup the {@code Chrono} using {@link #of(String)}.
*
* @return the chronology ID, not null
* @see #getCalendarType()
*/
public abstract String getId();
/**
* Gets the calendar type of the underlying calendar system.
* <p>
* The calendar type is an identifier defined by the
* <em>Unicode Locale Data Markup Language (LDML)</em> specification.
* It can be used to lookup the {@code Chrono} using {@link #of(String)}.
* It can also be used as part of a locale, accessible via
* {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
*
* @return the calendar system type, null if the calendar is not defined by LDML
* @see #getId()
*/
public abstract String getCalendarType();
//-----------------------------------------------------------------------
/**
* Obtains a local date in this chronology from the era, year-of-era,
* month-of-year and day-of-month fields.
*
* @param era the era of the correct type for the chronology, not null
* @param yearOfEra the chronology year-of-era
* @param month the chronology month-of-year
* @param dayOfMonth the chronology day-of-month
* @return the local date in this chronology, not null
* @throws DateTimeException if unable to create the date
*/
public ChronoLocalDate<C> date(Era<C> era, int yearOfEra, int month, int dayOfMonth) {
return date(prolepticYear(era, yearOfEra), month, dayOfMonth);
}
/**
* Obtains a local date in this chronology from the proleptic-year,
* month-of-year and day-of-month fields.
*
* @param prolepticYear the chronology proleptic-year
* @param month the chronology month-of-year
* @param dayOfMonth the chronology day-of-month
* @return the local date in this chronology, not null
* @throws DateTimeException if unable to create the date
*/
public abstract ChronoLocalDate<C> date(int prolepticYear, int month, int dayOfMonth);
/**
* Obtains a local date in this chronology from the era, year-of-era and
* day-of-year fields.
*
* @param era the era of the correct type for the chronology, not null
* @param yearOfEra the chronology year-of-era
* @param dayOfYear the chronology day-of-year
* @return the local date in this chronology, not null
* @throws DateTimeException if unable to create the date
*/
public ChronoLocalDate<C> dateYearDay(Era<C> era, int yearOfEra, int dayOfYear) {
return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
}
/**
* Obtains a local date in this chronology from the proleptic-year and
* day-of-year fields.
*
* @param prolepticYear the chronology proleptic-year
* @param dayOfYear the chronology day-of-year
* @return the local date in this chronology, not null
* @throws DateTimeException if unable to create the date
*/
public abstract ChronoLocalDate<C> dateYearDay(int prolepticYear, int dayOfYear);
/**
* Obtains a local date in this chronology from another date-time object.
* <p>
* This creates a date in this chronology based on the specified {@code DateTimeAccessor}.
* <p>
* The standard mechanism for conversion between date types is the
* {@link ChronoField#EPOCH_DAY local epoch-day} field.
*
* @param dateTime the date-time object to convert, not null
* @return the local date in this chronology, not null
* @throws DateTimeException if unable to create the date
*/
public abstract ChronoLocalDate<C> date(DateTimeAccessor dateTime);
//-----------------------------------------------------------------------
/**
* Obtains the current local date in this chronology from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
* <p>
* This implementation uses {@link #dateNow(Clock)}.
*
* @return the current local date using the system clock and default time-zone, not null
* @throws DateTimeException if unable to create the date
*/
public ChronoLocalDate<C> dateNow() {
return dateNow(Clock.systemDefaultZone());
}
/**
* Obtains the current local date in this chronology from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current local date using the system clock, not null
* @throws DateTimeException if unable to create the date
*/
public ChronoLocalDate<C> dateNow(ZoneId zone) {
return dateNow(Clock.system(zone));
}
/**
* Obtains the current local date in this chronology from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current local date, not null
* @throws DateTimeException if unable to create the date
*/
public ChronoLocalDate<C> dateNow(Clock clock) {
Objects.requireNonNull(clock, "clock");
return date(LocalDate.now(clock));
}
//-----------------------------------------------------------------------
/**
* Creates a local date-time in this chronology from another date-time object.
* <p>
* This creates a date-time in this chronology based on the specified {@code DateTimeAccessor}.
* <p>
* The date of the date-time should be equivalent to that obtained by calling
* {@link #date(DateTimeAccessor)}.
* The standard mechanism for conversion between time types is the
* {@link ChronoField#NANO_OF_DAY nano-of-day} field.
*
* @param dateTime the date-time object to convert, not null
* @return the local date-time in this chronology, not null
* @throws DateTimeException if unable to create the date-time
*/
public ChronoLocalDateTime<C> localDateTime(DateTimeAccessor dateTime) {
return date(dateTime).atTime(LocalTime.from(dateTime));
}
/**
* Creates a local date-time in this chronology from an instant and zone.
*
* @param instant the instant, not null
* @param zoneId the zone ID, not null
* @return the local date-time, not null
*/
ChronoDateTimeImpl<C> localInstant(Instant instant, ZoneId zoneId) {
ZoneRules rules = zoneId.getRules();
ZoneOffset offset = rules.getOffset(instant);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
return ChronoDateTimeImpl.of(dateNow(), LocalTime.MIDNIGHT).with(ldt); // not very efficient...
}
/**
* Creates a zoned date-time in this chronology from another date-time object.
* <p>
* This creates a date-time in this chronology based on the specified {@code DateTimeAccessor}.
* <p>
* This should obtain a {@code ZoneId} using {@link ZoneId#from(DateTimeAccessor)}.
* The date-time should be obtained by obtaining an {@code Instant}.
* If that fails, the local date-time should be used.
*
* @param dateTime the date-time object to convert, not null
* @return the zoned date-time in this chronology, not null
* @throws DateTimeException if unable to create the date-time
*/
public ChronoZonedDateTime<C> zonedDateTime(DateTimeAccessor dateTime) {
try {
ZoneId zoneId = ZoneId.from(dateTime);
ChronoDateTimeImpl<C> cldt;
try {
Instant instant = Instant.from(dateTime);
cldt = localInstant(instant, zoneId);
} catch (DateTimeException ex1) {
cldt = ensureChronoLocalDateTime(localDateTime(dateTime));
}
return ChronoZonedDateTimeImpl.ofBest(cldt, zoneId, null);
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to convert DateTimeAccessor to ZonedDateTime: " + dateTime.getClass(), ex);
}
}
//-----------------------------------------------------------------------
/**
* Checks if the specified year is a leap year.
* <p>
* A leap-year is a year of a longer length than normal.
* The exact meaning is determined by the chronology according to the following constraints.
* <p><ul>
* <li>a leap-year must imply a year-length longer than a non leap-year.
* <li>a chronology that does not support the concept of a year must return false.
* </ul><p>
*
* @param prolepticYear the proleptic-year to check, not validated for range
* @return true if the year is a leap year
*/
public abstract boolean isLeapYear(long prolepticYear);
/**
* Calculates the proleptic-year given the era and year-of-era.
* <p>
* This combines the era and year-of-era into the single proleptic-year field.
*
* @param era the era of the correct type for the chronology, not null
* @param yearOfEra the chronology year-of-era
* @return the proleptic-year
* @throws DateTimeException if unable to convert
*/
public abstract int prolepticYear(Era<C> era, int yearOfEra);
/**
* Creates the chronology era object from the numeric value.
* <p>
* The era is, conceptually, the largest division of the time-line.
* Most calendar systems have a single epoch dividing the time-line into two eras.
* However, some have multiple eras, such as one for the reign of each leader.
* The exact meaning is determined by the chronology according to the following constraints.
* <p>
* The era in use at 1970-01-01 must have the value 1.
* Later eras must have sequentially higher values.
* Earlier eras must have sequentially lower values.
* Each chronology must refer to an enum or similar singleton to provide the era values.
* <p>
* This method returns the singleton era of the correct type for the specified era value.
*
* @param eraValue the era value
* @return the calendar system era, not null
* @throws DateTimeException if unable to create the era
*/
public abstract Era<C> eraOf(int eraValue);
/**
* Gets the list of eras for the chronology.
* <p>
* Most calendar systems have an era, within which the year has meaning.
* If the calendar system does not support the concept of eras, an empty
* list must be returned.
*
* @return the list of eras for the chronology, may be immutable, not null
*/
public abstract List<Era<C>> eras();
//-----------------------------------------------------------------------
/**
* Gets the range of valid values for the specified field.
* <p>
* All fields can be expressed as a {@code long} integer.
* This method returns an object that describes the valid range for that value.
* <p>
* Note that the result only describes the minimum and maximum valid values
* and it is important not to read too much into them. For example, there
* could be values within the range that are invalid for the field.
* <p>
* This method will return a result whether or not the chronology supports the field.
*
* @param field the field to get the range for, not null
* @return the range of valid values for the field, not null
* @throws DateTimeException if the range for the field cannot be obtained
*/
public abstract DateTimeValueRange range(ChronoField field);
//-----------------------------------------------------------------------
/**
* Gets the textual representation of this chronology.
* <p>
* This returns the textual name used to identify the chronology.
* The parameters control the length of the returned text and the locale.
*
* @param style the length of the text required, not null
* @param locale the locale to use, not null
* @return the text value of the chronology, not null
*/
public String getText(TextStyle style, Locale locale) {
return new DateTimeFormatterBuilder().appendChronoText(style).toFormatter(locale).print(new DefaultInterfaceDateTimeAccessor() {
@Override
public boolean isSupported(DateTimeField field) {
return false;
}
@Override
public long getLong(DateTimeField field) {
throw new DateTimeException("Unsupported field: " + field);
}
@SuppressWarnings("unchecked")
@Override
public <R> R query(Query<R> query) {
if (query == Query.CHRONO) {
- return (R) this;
+ return (R) Chrono.this;
}
return super.query(query);
}
});
}
//-----------------------------------------------------------------------
/**
* Compares this chronology to another chronology.
* <p>
* The comparison order first by the chronology ID string, then by any
* additional information specific to the subclass.
* It is "consistent with equals", as defined by {@link Comparable}.
* <p>
* The default implementation compares the chronology ID.
* Subclasses must compare any additional state that they store.
*
* @param other the other chronology to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Chrono<?> other) {
return getId().compareTo(other.getId());
}
/**
* Checks if this chronology is equal to another chronology.
* <p>
* The comparison is based on the entire state of the object.
* <p>
* The default implementation checks the type and calls {@link #compareTo(Chrono)}.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other chronology
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Chrono) {
return compareTo((Chrono<?>) obj) == 0;
}
return false;
}
/**
* A hash code for this chronology.
* <p>
* The default implementation is based on the ID and class.
* Subclasses should add any additional state that they store.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return getClass().hashCode() ^ getId().hashCode();
}
//-----------------------------------------------------------------------
/**
* Outputs this chronology as a {@code String}, using the ID.
*
* @return a string representation of this chronology, not null
*/
@Override
public String toString() {
return getId();
}
//-----------------------------------------------------------------------
private Object writeReplace() {
return new Ser(Ser.CHRONO_TYPE, this);
}
void writeExternal(DataOutput out) throws IOException {
out.writeUTF(getId());
}
static Chrono<?> readExternal(DataInput in) throws IOException {
String id = in.readUTF();
return Chrono.of(id);
}
}
| true | true |
public String getText(TextStyle style, Locale locale) {
return new DateTimeFormatterBuilder().appendChronoText(style).toFormatter(locale).print(new DefaultInterfaceDateTimeAccessor() {
@Override
public boolean isSupported(DateTimeField field) {
return false;
}
@Override
public long getLong(DateTimeField field) {
throw new DateTimeException("Unsupported field: " + field);
}
@SuppressWarnings("unchecked")
@Override
public <R> R query(Query<R> query) {
if (query == Query.CHRONO) {
return (R) this;
}
return super.query(query);
}
});
}
|
public String getText(TextStyle style, Locale locale) {
return new DateTimeFormatterBuilder().appendChronoText(style).toFormatter(locale).print(new DefaultInterfaceDateTimeAccessor() {
@Override
public boolean isSupported(DateTimeField field) {
return false;
}
@Override
public long getLong(DateTimeField field) {
throw new DateTimeException("Unsupported field: " + field);
}
@SuppressWarnings("unchecked")
@Override
public <R> R query(Query<R> query) {
if (query == Query.CHRONO) {
return (R) Chrono.this;
}
return super.query(query);
}
});
}
|
diff --git a/src/com/googlecode/sardine/util/SardineException.java b/src/com/googlecode/sardine/util/SardineException.java
index 62c8f9d..3693bd9 100644
--- a/src/com/googlecode/sardine/util/SardineException.java
+++ b/src/com/googlecode/sardine/util/SardineException.java
@@ -1,83 +1,83 @@
package com.googlecode.sardine.util;
import java.io.IOException;
/**
* Specialized type of exception for Sardine so
* that it is easy to get the error information from it.
*
* @author jonstevens
*/
@SuppressWarnings("serial")
public class SardineException extends IOException
{
private int statusCode;
private String responsePhrase;
private String url;
/** */
public SardineException(Exception ex)
{
this.initCause(ex);
}
/** */
public SardineException(String msg, String url)
{
this(msg, url, -1, null, null);
}
/** */
public SardineException(String msg, String url, Exception initCause)
{
this(msg, url, -1, null, initCause);
}
/** */
public SardineException(String msg, String url, int statusCode, String responsePhrase)
{
this(msg, url, statusCode, responsePhrase, null);
}
/** */
public SardineException(String url, int statusCode, String responsePhrase)
{
this("The server has returned an HTTP error", url, statusCode, responsePhrase, null);
}
/** */
public SardineException(String msg, String url, int statusCode, String responsePhrase, Exception initCause)
{
- super(msg + responsePhrase != null ? ", response: " + responsePhrase : "" + ", statusCode: " + statusCode);
+ super(msg, initCause);
this.url = url;
this.statusCode = statusCode;
this.responsePhrase = responsePhrase;
if (initCause != null)
this.initCause(initCause);
}
/**
* The url that caused the failure.
*/
public String getUrl()
{
return this.url;
}
/**
* The http client status code.
* A status code of -1 means that there isn't one and probably isn't a response phrase either.
*/
public int getStatusCode()
{
return this.statusCode;
}
/**
* The http client response phrase.
*/
public String getResponsePhrase()
{
return this.responsePhrase;
}
}
| true | true |
public SardineException(String msg, String url, int statusCode, String responsePhrase, Exception initCause)
{
super(msg + responsePhrase != null ? ", response: " + responsePhrase : "" + ", statusCode: " + statusCode);
this.url = url;
this.statusCode = statusCode;
this.responsePhrase = responsePhrase;
if (initCause != null)
this.initCause(initCause);
}
|
public SardineException(String msg, String url, int statusCode, String responsePhrase, Exception initCause)
{
super(msg, initCause);
this.url = url;
this.statusCode = statusCode;
this.responsePhrase = responsePhrase;
if (initCause != null)
this.initCause(initCause);
}
|
diff --git a/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java b/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
index f3b8466..0cb1b9b 100644
--- a/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
+++ b/src/main/java/com/kfuntak/gwt/json/serialization/SerializationGenerator.java
@@ -1,643 +1,652 @@
package com.kfuntak.gwt.json.serialization;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import com.kfuntak.gwt.json.serialization.client.DeserializerHelper;
import com.kfuntak.gwt.json.serialization.client.IncompatibleObjectException;
import com.kfuntak.gwt.json.serialization.client.JsonSerializable;
import com.kfuntak.gwt.json.serialization.client.ObjectSerializer;
import com.kfuntak.gwt.json.serialization.client.SerializerHelper;
public class SerializationGenerator extends Generator {
private JClassType serializeInterface;
private JClassType stringClass;
private SourceWriter srcWriter;
private String className;
private TypeOracle typeOracle;
private Set<String> importsList = new HashSet<String>();
public String generate(TreeLogger logger, GeneratorContext ctx,
String requestedClass) throws UnableToCompleteException {
//get the type oracle
typeOracle = ctx.getTypeOracle();
assert (typeOracle != null);
serializeInterface = typeOracle.findType(JsonSerializable.class.getName());
assert (serializeInterface != null);
stringClass = typeOracle.findType(String.class.getName());
assert (stringClass != null);
//get class from type oracle
JClassType serializeClass = typeOracle.findType(requestedClass);
if (serializeClass == null) {
logger.log(TreeLogger.ERROR, "Unable to find metadata for type '"
+ requestedClass + "'", null);
throw new UnableToCompleteException();
}
//create source writer
String packageName = serializeClass.getPackage().getName();
className = serializeClass.getSimpleSourceName() + "_TypeSerializer";
PrintWriter printWriter = ctx.tryCreate(logger, packageName, className);
if (printWriter == null) {
return packageName + "." + className;
}
ClassSourceFileComposerFactory composerFactory =
new ClassSourceFileComposerFactory(packageName, className);
composerFactory.setSuperclass("com.kfuntak.gwt.json.serialization.client.Serializer");
// // Java imports
composerFactory.addImport(java.util.Collection.class.getName());
composerFactory.addImport(java.util.List.class.getName());
composerFactory.addImport(java.util.ArrayList.class.getName());
composerFactory.addImport(java.util.LinkedList.class.getName());
composerFactory.addImport(java.util.Stack.class.getName());
composerFactory.addImport(java.util.Vector.class.getName());
composerFactory.addImport(java.util.Set.class.getName());
composerFactory.addImport(java.util.TreeSet.class.getName());
composerFactory.addImport(java.util.HashSet.class.getName());
composerFactory.addImport(java.util.LinkedHashSet.class.getName());
composerFactory.addImport(java.util.SortedSet.class.getName());
composerFactory.addImport(java.util.Date.class.getName());
// // GWT imports
composerFactory.addImport(com.google.gwt.core.client.GWT.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONNull.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONNumber.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONString.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONValue.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONObject.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONArray.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONBoolean.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONParser.class.getName());
composerFactory.addImport(com.google.gwt.json.client.JSONException.class.getName());
// // Module imports
composerFactory.addImport(ObjectSerializer.class.getName());
composerFactory.addImport(JsonSerializable.class.getName());
composerFactory.addImport(IncompatibleObjectException.class.getName());
composerFactory.addImport(SerializerHelper.class.getName());
composerFactory.addImport(DeserializerHelper.class.getName());
JClassType[] subTypes = serializeInterface.getSubtypes();
for (int i = 0; i < subTypes.length; ++i) {
composerFactory.addImport(subTypes[i].getQualifiedSourceName());
}
srcWriter = composerFactory.createSourceWriter(ctx, printWriter);
if (srcWriter == null) {
return packageName + "." + className;
}
//create a serializer for each interface that supports Serializable
for (int i = 0; i < subTypes.length; ++i) {
srcWriter.println("public class " + subTypes[i].getName() + "_SerializableImpl implements ObjectSerializer{");
// System.out.println("public class "+subTypes[i].getName()+"_SerializableImpl implements ObjectSerializer{");
srcWriter.indent();
srcWriter.println("public " + subTypes[i].getName() + "_SerializableImpl(){}");
// System.out.println("public "+subTypes[i].getName()+"_SerializableImpl(){}");
StringBuffer buffer = new StringBuffer();
try {
String defaultSerializationString = generateDefaultSerialization();
String typeSerializationString = generateTypeSerialization(subTypes[i].getQualifiedSourceName());
String defaultDeserializationString = generateDefaultDeserialization(subTypes[i].getQualifiedSourceName());
String tyepDeserializationString = generateTypeDeserialization(subTypes[i].getQualifiedSourceName());
buffer.append(defaultSerializationString);
buffer.append("\n");
buffer.append(typeSerializationString);
buffer.append("\n");
buffer.append(defaultDeserializationString);
buffer.append("\n");
buffer.append(tyepDeserializationString);
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
//System.out.println(buffer.toString());
} catch (NotFoundException e) {
e.printStackTrace();
}
srcWriter.println(buffer.toString());
// System.out.println(buffer.toString());
}
//in the class constructor, add each serializer
srcWriter.println("public " + className + "(){");
// System.out.println("public "+className+"(){");
srcWriter.indent();
for (int i = 0; i < subTypes.length; ++i) {
srcWriter.println("addObjectSerializer(\"" + subTypes[i].getQualifiedSourceName() + "\", new " + subTypes[i].getName() + "_SerializableImpl() );");
// System.out.println("addObjectSerializer(\""+subTypes[i].getQualifiedSourceName()+"\", new "+subTypes[i].getName()+"_SerializableImpl() );");
}
srcWriter.outdent();
srcWriter.println("}");
// System.out.println("}");
srcWriter.commit(logger);
return packageName + "." + className;
}
private String generateTypeDeserialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public Object deSerialize(JSONValue jsonValue, String className) throws JSONException{");
buffer.append("\n");
// Return null if the given object is null
buffer.append("if(jsonValue instanceof JSONNull){");
buffer.append("\n");
buffer.append("return null;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible exception is JsonValue is not an instance of
// JsonObject
buffer.append("if(!(jsonValue instanceof JSONObject)){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise JsonObject then
String baseTypeName = baseType.getSimpleSourceName();
buffer.append("JSONObject jsonObject=(JSONObject)jsonValue;");
buffer.append("\n");
buffer.append(baseTypeName + " mainResult=new " + baseTypeName + "();");
buffer.append("\n");
buffer.append("Serializer serializer;");
buffer.append("\n");
buffer.append("JSONArray inputJsonArray=null;");
buffer.append("\n");
buffer.append("int inpJsonArSize=0;");
buffer.append("\n");
buffer.append("JSONValue fieldJsonValue=null;");
buffer.append("\n");
// Start deSerialisation
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
for (JField field : fields) {
if (!field.isStatic() && !field.isTransient()) {
allFields.add(field);
}
}
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
JField[] subClassFields = superClassType.getFields();
for (JField subClassField : subClassFields) {
if (!subClassField.isStatic() && !subClassField.isTransient()) {
allFields.add(subClassField);
}
}
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
buffer.append("fieldJsonValue=jsonObject.get(\"" + fieldName + "\");");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getDate(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, \"" + fieldClassType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
deserializeCollection(buffer, fieldClassType, fieldNameForGS, fieldName);
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("mainResult.set" + fieldNameForGS + "(DeserializerHelper.getString(fieldJsonValue));");
buffer.append("\n");
}
}
}
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private void deserializeCollection(StringBuffer buffer, JClassType fieldClassType, String fieldNameForGS, String fieldName) throws NotFoundException {
// Return null if JSON object is null
buffer.append("if(fieldJsonValue==null){");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(null);");
buffer.append("\n");
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible exception if the JSON object is not a collection
buffer.append("if(!(fieldJsonValue instanceof JSONArray)){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Start deSerilisation
buffer.append("inputJsonArray=(JSONArray)fieldJsonValue;");
buffer.append("\n");
buffer.append("inpJsonArSize=inputJsonArray.size();");
buffer.append("\n");
String fieldTypeQualifiedName = fieldClassType.getQualifiedSourceName();
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
String parameterSimpleName = fieldClassType.getSimpleSourceName();
String fieldColName = fieldName + "Col";// Field Collection Result
// Object Name
importsList.add(fieldClassType.getQualifiedSourceName());
if (fieldTypeQualifiedName.equals("java.util.List") || fieldTypeQualifiedName.equals("java.util.ArrayList")) {
buffer.append("ArrayList<" + parameterSimpleName + "> " + fieldColName + " = new ArrayList<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Set") || fieldTypeQualifiedName.equals("java.util.HashSet")) {
buffer.append("HashSet<" + parameterSimpleName + "> " + fieldColName + " = new HashSet<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.SortedSet") || fieldTypeQualifiedName.equals("java.util.TreeSet")) {
buffer.append("TreeSet<" + parameterSimpleName + "> " + fieldColName + " = new TreeSet<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.LinkedList")) {
buffer.append("LinkedList<" + parameterSimpleName + "> " + fieldColName + " = new LinkedList<" + parameterSimpleName + ">();");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(" + fieldColName + ");");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Stack")) {
buffer.append("Stack<" + parameterSimpleName + "> " + fieldColName + " = new Stack<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.Vector")) {
buffer.append("Vector<" + parameterSimpleName + "> " + fieldColName + " = new Vector<" + parameterSimpleName + ">();");
buffer.append("\n");
} else if (fieldTypeQualifiedName.equals("java.util.LinkedHashSet")) {
buffer.append("LinkedHashSet<" + parameterSimpleName + "> " + fieldColName + "=new LinkedHashSet<" + parameterSimpleName + ">();");
buffer.append("\n");
}
buffer.append("for(int ij=0;ij<inpJsonArSize;ij++){");
// DeSerialise individual elements
buffer.append("fieldJsonValue=inputJsonArray.get(ij);");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.Short")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Byte")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getByte(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Long")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getLong(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Integer")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getInt(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Float")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getFloat(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Double")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getDouble(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getBoolean(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getShort(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getDate(fieldJsonValue));");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("JSONValue _class = ((JSONObject)fieldJsonValue).get(\"class\");");
buffer.append("\n");
buffer.append("if (_class != null && _class instanceof JSONString) {");
buffer.append("\n");
buffer.append(fieldColName + ".add((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, ((JSONString)_class).stringValue()));");
buffer.append("\n");
buffer.append("} else {");
buffer.append(fieldColName + ".add((" + fieldClassType.getSimpleSourceName() + ")serializer.deSerialize(fieldJsonValue, \"" + fieldClassType.getQualifiedSourceName() + "\"));");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append(fieldColName + ".add(DeserializerHelper.getString(fieldJsonValue));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.set" + fieldNameForGS + "(" + fieldColName + ");");
buffer.append("\n");
}
private String generateDefaultDeserialization(String className) {
StringBuffer buffer = new StringBuffer();
buffer.append("public Object deSerialize(String jsonString, String className) throws JSONException{");
buffer.append("\n");
buffer.append("return deSerialize(JSONParser.parse(jsonString), \"" + className + "\");");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
- allFields.addAll(Arrays.asList(fields));
+ for (JField field : fields) {
+ if (!field.isStatic() && !field.isTransient()) {
+ allFields.add(field);
+ }
+ }
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
- allFields.addAll(Arrays.asList(superClassType.getFields()));
+ JField[] subClassFields = superClassType.getFields();
+ for (JField subClassField : subClassFields) {
+ if (!subClassField.isStatic() && !subClassField.isTransient()) {
+ allFields.add(subClassField);
+ }
+ }
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private String generateDefaultSerialization() {
StringBuffer buffer = new StringBuffer();
buffer.append("public String serialize(Object pojo){");
buffer.append("\n");
buffer.append("return serializeToJson(pojo).toString();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
private static String getNameForGS(String name) {
StringBuffer buffer = new StringBuffer(name);
buffer.setCharAt(0, new String(new char[]{name.charAt(0)}).toUpperCase().charAt(0));
return buffer.toString();
}
}
| false | true |
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
allFields.addAll(Arrays.asList(fields));
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
allFields.addAll(Arrays.asList(superClassType.getFields()));
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
|
private String generateTypeSerialization(String typeName) throws NotFoundException {
JClassType baseType = typeOracle.getType(typeName);
String packageName = baseType.getPackage().getName();
StringBuffer buffer = new StringBuffer();
buffer.append("public JSONValue serializeToJson(Object object){");
buffer.append("\n");
// Return JSONNull instance if object is null
buffer.append("if(object==null){");
buffer.append("\n");
buffer.append("return JSONNull.getInstance();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Throw Incompatible Exception if object is not of the type it claims
// to be
buffer.append("if(!(object instanceof " + baseType.getSimpleSourceName() + ")){");
buffer.append("\n");
buffer.append("throw new IncompatibleObjectException();");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
// Initialise result object
buffer.append("JSONObject mainResult=new JSONObject();");
buffer.append("\n");
buffer.append("JSONValue jsonValue=null;");
buffer.append("\n");
buffer.append("JSONArray jsonResultArray=null;");
buffer.append("\n");
buffer.append("int index=0;");
buffer.append("\n");
buffer.append("Serializer serializer=null;");
buffer.append("\n");
buffer.append("Object fieldValue=null;");
buffer.append("\n");
buffer.append(baseType.getSimpleSourceName() + " mainVariable=(" + baseType.getSimpleSourceName() + ")object;");
buffer.append("\n");
// Serialise fields
List<JField> allFields = new ArrayList<JField>();
JField[] fields = baseType.getFields();
for (JField field : fields) {
if (!field.isStatic() && !field.isTransient()) {
allFields.add(field);
}
}
if (baseType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
boolean flag = true;
JClassType superClassType = baseType;
while (flag) {
superClassType = superClassType.getSuperclass();
if (superClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
JField[] subClassFields = superClassType.getFields();
for (JField subClassField : subClassFields) {
if (!subClassField.isStatic() && !subClassField.isTransient()) {
allFields.add(subClassField);
}
}
} else {
flag = false;
}
}
}
fields = new JField[allFields.size()];
allFields.toArray(fields);
for (JField field : fields) {
JType fieldType = field.getType();
String fieldName = field.getName();
String fieldNameForGS = getNameForGS(fieldName);
// Get field value for object
buffer.append("fieldValue=mainVariable.get" + fieldNameForGS + "();");
buffer.append("\n");
if (fieldType.isPrimitive() != null) {
JPrimitiveType fieldPrimitiveType = (JPrimitiveType) fieldType;
JClassType fieldBoxedType = typeOracle.getType(fieldPrimitiveType.getQualifiedBoxedSourceName());
if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldBoxedType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
}
} else {
JClassType fieldClassType = (JClassType) fieldType;
if (fieldClassType.isAssignableTo(typeOracle.getType("java.util.Collection"))) {
// Serialise collection
JParameterizedType parameterizedType = (JParameterizedType) fieldClassType;
fieldClassType = parameterizedType.getTypeArgs()[0];
importsList.add(fieldClassType.getQualifiedSourceName());
String fieldSimpleName = fieldClassType.getSimpleSourceName();
buffer.append("\n");
buffer.append("if(fieldValue != null){");
buffer.append("\n");
buffer.append("Collection<" + fieldSimpleName + "> " + fieldSimpleName.toLowerCase() + "ColValue=(Collection<" + fieldSimpleName + ">)fieldValue;");
buffer.append("\n");
buffer.append("jsonResultArray=new JSONArray();");
buffer.append("\n");
buffer.append("index=0;");
buffer.append("\n");
buffer.append("for(" + fieldSimpleName + " dummy : " + fieldSimpleName.toLowerCase() + "ColValue){");
buffer.append("\n");
if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)dummy);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
// TODO: Put alternalive to importsList
//importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("jsonResultArray.set(index++,serializer.serializeToJson(dummy));");
buffer.append("\n");
}
buffer.append("}");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonResultArray);");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.String")) {
buffer.append("jsonValue=SerializerHelper.getString((String)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Boolean")) {
buffer.append("jsonValue=SerializerHelper.getBoolean((Boolean)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.lang.Character")) {
buffer.append("jsonValue=SerializerHelper.getChar((Character)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("java.lang.Number"))) {
buffer.append("jsonValue=SerializerHelper.getNumber((Number)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.getQualifiedSourceName().equals("java.util.Date")) {
buffer.append("jsonValue=SerializerHelper.getDate((Date)fieldValue);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",jsonValue);");
buffer.append("\n");
} else if (fieldClassType.isAssignableTo(typeOracle.getType("com.kfuntak.gwt.json.serialization.client.JsonSerializable"))) {
importsList.add(fieldClassType.getQualifiedSourceName());
buffer.append("serializer = GWT.create(Serializer.class);");
buffer.append("\n");
buffer.append("mainResult.put(\"" + fieldName + "\",serializer.serializeToJson(fieldValue));");
buffer.append("\n");
}
}
}
// Put class type for compatibility with flex JSON [de]serialisation
buffer.append("mainResult.put(\"class\",new JSONString(\"" + baseType.getQualifiedSourceName() + "\"));");
buffer.append("\n");
// Return statement
buffer.append("return mainResult;");
buffer.append("\n");
buffer.append("}");
buffer.append("\n");
return buffer.toString();
}
|
diff --git a/src/org/imaginationforpeople/android2/projectview/InfoProjectViewFragment.java b/src/org/imaginationforpeople/android2/projectview/InfoProjectViewFragment.java
index 4917154..6635425 100644
--- a/src/org/imaginationforpeople/android2/projectview/InfoProjectViewFragment.java
+++ b/src/org/imaginationforpeople/android2/projectview/InfoProjectViewFragment.java
@@ -1,150 +1,150 @@
package org.imaginationforpeople.android2.projectview;
import java.util.List;
import org.imaginationforpeople.android2.R;
import org.imaginationforpeople.android2.helper.DataHelper;
import org.imaginationforpeople.android2.model.I4pProjectTranslation;
import org.imaginationforpeople.android2.model.Objective;
import org.imaginationforpeople.android2.model.Question;
import org.imaginationforpeople.android2.model.User;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class InfoProjectViewFragment extends Fragment implements OnClickListener {
private I4pProjectTranslation project;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
project = getArguments().getParcelable(DataHelper.PROJECT_VIEW_KEY);
ScrollView layout = (ScrollView) inflater.inflate(R.layout.projectview_info, null);
LinearLayout overlay = (LinearLayout) layout.findViewById(R.id.projectview_description_overlay);
overlay.getBackground().setAlpha(127);
if(project.getProject().getPictures().size() > 0) {
ImageView image = (ImageView) layout.findViewById(R.id.projectview_description_image);
image.setImageBitmap(project.getProject().getPictures().get(0).getImageBitmap());
}
ImageView bestof = (ImageView) layout.findViewById(R.id.projectview_description_bestof);
if(!project.getProject().getBestOf())
bestof.setVisibility(View.GONE);
TextView title = (TextView) layout.findViewById(R.id.projectview_description_title);
title.setText(project.getTitle());
TextView baseline = (TextView) layout.findViewById(R.id.projectview_description_baseline);
baseline.setText(project.getBaseline());
ImageView status = (ImageView) layout.findViewById(R.id.projectview_description_status);
if("IDEA".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_idea);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_idea));
} else if("BEGIN".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_begin);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_begin));
} else if("WIP".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_wip);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_wip));
} else if("END".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_end);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_end));
}
if(project.getProject().getLocation() != null) {
- if(!"".equals(project.getProject().getLocation().getCountry())) {
+ if(project.getProject().getLocation().getCountry() != null) {
int flag = getResources().getIdentifier("flag_"+project.getProject().getLocation().getCountry().toLowerCase(), "drawable", "org.imaginationforpeople.android2");
if(flag != 0) {
ImageView flagView = (ImageView) layout.findViewById(R.id.projectview_description_flag);
flagView.setImageResource(flag);
}
}
}
TextView website = (TextView) layout.findViewById(R.id.projectview_description_website);
if("".equals(project.getProject().getWebsite()))
website.setVisibility(View.GONE);
else
website.setOnClickListener(this);
if(project.getAboutSection() == null || "".equals(project.getAboutSection())) {
LinearLayout aboutContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_about_container);
aboutContainer.setVisibility(View.GONE);
} else {
TextView aboutText = (TextView) layout.findViewById(R.id.projectview_description_about_text);
aboutText.setText(project.getAboutSection().trim());
}
if("".equals(project.getThemes())) {
LinearLayout themesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_themes_container);
themesContainer.setVisibility(View.GONE);
} else {
TextView themesText = (TextView) layout.findViewById(R.id.projectview_description_themes_text);
themesText.setText(project.getThemes());
}
if(project.getProject().getObjectives().size() == 0) {
LinearLayout objectivesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_objectives_container);
objectivesContainer.setVisibility(View.GONE);
} else {
TextView objectivesText = (TextView) layout.findViewById(R.id.projectview_description_objectives_text);
List<Objective> objectivesObject = project.getProject().getObjectives();
String objectives = objectivesObject.get(0).getName();
for(int i = 1; i < objectivesObject.size(); i++) {
objectives += ", " + objectivesObject.get(i).getName();
}
objectivesText.setText(objectives);
}
LinearLayout questions = (LinearLayout) layout.findViewById(R.id.projectview_description_questions_container);
for(Question question : project.getProject().getQuestions()) {
if(question.getAnswer() != null) {
LinearLayout questionLayout = (LinearLayout) inflater.inflate(R.layout.projectview_question, null);
TextView questionView = (TextView) questionLayout.findViewById(R.id.projectview_question_question);
TextView answerView = (TextView) questionLayout.findViewById(R.id.projectview_question_answer);
questionView.setText(Build.VERSION.SDK_INT < 14 ? question.getQuestion().toUpperCase() : question.getQuestion());
answerView.setText(question.getAnswer().trim());
questions.addView(questionLayout);
}
}
if(project.getProject().getMembers().size() == 0) {
LinearLayout membersContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_members_container);
membersContainer.setVisibility(View.GONE);
} else {
LinearLayout members = (LinearLayout) layout.findViewById(R.id.projectview_description_members_text);
for(User member : project.getProject().getMembers()) {
TextView memberName = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, null);
memberName.setText(member.getFullname());
memberName.setCompoundDrawablesWithIntrinsicBounds(null, null, member.getAvatarDrawable(), null);
members.addView(memberName);
}
}
return layout;
}
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(project.getProject().getWebsite()));
startActivity(intent);
}
}
| true | true |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
project = getArguments().getParcelable(DataHelper.PROJECT_VIEW_KEY);
ScrollView layout = (ScrollView) inflater.inflate(R.layout.projectview_info, null);
LinearLayout overlay = (LinearLayout) layout.findViewById(R.id.projectview_description_overlay);
overlay.getBackground().setAlpha(127);
if(project.getProject().getPictures().size() > 0) {
ImageView image = (ImageView) layout.findViewById(R.id.projectview_description_image);
image.setImageBitmap(project.getProject().getPictures().get(0).getImageBitmap());
}
ImageView bestof = (ImageView) layout.findViewById(R.id.projectview_description_bestof);
if(!project.getProject().getBestOf())
bestof.setVisibility(View.GONE);
TextView title = (TextView) layout.findViewById(R.id.projectview_description_title);
title.setText(project.getTitle());
TextView baseline = (TextView) layout.findViewById(R.id.projectview_description_baseline);
baseline.setText(project.getBaseline());
ImageView status = (ImageView) layout.findViewById(R.id.projectview_description_status);
if("IDEA".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_idea);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_idea));
} else if("BEGIN".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_begin);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_begin));
} else if("WIP".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_wip);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_wip));
} else if("END".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_end);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_end));
}
if(project.getProject().getLocation() != null) {
if(!"".equals(project.getProject().getLocation().getCountry())) {
int flag = getResources().getIdentifier("flag_"+project.getProject().getLocation().getCountry().toLowerCase(), "drawable", "org.imaginationforpeople.android2");
if(flag != 0) {
ImageView flagView = (ImageView) layout.findViewById(R.id.projectview_description_flag);
flagView.setImageResource(flag);
}
}
}
TextView website = (TextView) layout.findViewById(R.id.projectview_description_website);
if("".equals(project.getProject().getWebsite()))
website.setVisibility(View.GONE);
else
website.setOnClickListener(this);
if(project.getAboutSection() == null || "".equals(project.getAboutSection())) {
LinearLayout aboutContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_about_container);
aboutContainer.setVisibility(View.GONE);
} else {
TextView aboutText = (TextView) layout.findViewById(R.id.projectview_description_about_text);
aboutText.setText(project.getAboutSection().trim());
}
if("".equals(project.getThemes())) {
LinearLayout themesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_themes_container);
themesContainer.setVisibility(View.GONE);
} else {
TextView themesText = (TextView) layout.findViewById(R.id.projectview_description_themes_text);
themesText.setText(project.getThemes());
}
if(project.getProject().getObjectives().size() == 0) {
LinearLayout objectivesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_objectives_container);
objectivesContainer.setVisibility(View.GONE);
} else {
TextView objectivesText = (TextView) layout.findViewById(R.id.projectview_description_objectives_text);
List<Objective> objectivesObject = project.getProject().getObjectives();
String objectives = objectivesObject.get(0).getName();
for(int i = 1; i < objectivesObject.size(); i++) {
objectives += ", " + objectivesObject.get(i).getName();
}
objectivesText.setText(objectives);
}
LinearLayout questions = (LinearLayout) layout.findViewById(R.id.projectview_description_questions_container);
for(Question question : project.getProject().getQuestions()) {
if(question.getAnswer() != null) {
LinearLayout questionLayout = (LinearLayout) inflater.inflate(R.layout.projectview_question, null);
TextView questionView = (TextView) questionLayout.findViewById(R.id.projectview_question_question);
TextView answerView = (TextView) questionLayout.findViewById(R.id.projectview_question_answer);
questionView.setText(Build.VERSION.SDK_INT < 14 ? question.getQuestion().toUpperCase() : question.getQuestion());
answerView.setText(question.getAnswer().trim());
questions.addView(questionLayout);
}
}
if(project.getProject().getMembers().size() == 0) {
LinearLayout membersContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_members_container);
membersContainer.setVisibility(View.GONE);
} else {
LinearLayout members = (LinearLayout) layout.findViewById(R.id.projectview_description_members_text);
for(User member : project.getProject().getMembers()) {
TextView memberName = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, null);
memberName.setText(member.getFullname());
memberName.setCompoundDrawablesWithIntrinsicBounds(null, null, member.getAvatarDrawable(), null);
members.addView(memberName);
}
}
return layout;
}
|
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
project = getArguments().getParcelable(DataHelper.PROJECT_VIEW_KEY);
ScrollView layout = (ScrollView) inflater.inflate(R.layout.projectview_info, null);
LinearLayout overlay = (LinearLayout) layout.findViewById(R.id.projectview_description_overlay);
overlay.getBackground().setAlpha(127);
if(project.getProject().getPictures().size() > 0) {
ImageView image = (ImageView) layout.findViewById(R.id.projectview_description_image);
image.setImageBitmap(project.getProject().getPictures().get(0).getImageBitmap());
}
ImageView bestof = (ImageView) layout.findViewById(R.id.projectview_description_bestof);
if(!project.getProject().getBestOf())
bestof.setVisibility(View.GONE);
TextView title = (TextView) layout.findViewById(R.id.projectview_description_title);
title.setText(project.getTitle());
TextView baseline = (TextView) layout.findViewById(R.id.projectview_description_baseline);
baseline.setText(project.getBaseline());
ImageView status = (ImageView) layout.findViewById(R.id.projectview_description_status);
if("IDEA".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_idea);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_idea));
} else if("BEGIN".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_begin);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_begin));
} else if("WIP".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_wip);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_wip));
} else if("END".equals(project.getProject().getStatus())) {
status.setImageResource(R.drawable.project_status_end);
status.setContentDescription(getResources().getString(R.string.projectview_description_status_end));
}
if(project.getProject().getLocation() != null) {
if(project.getProject().getLocation().getCountry() != null) {
int flag = getResources().getIdentifier("flag_"+project.getProject().getLocation().getCountry().toLowerCase(), "drawable", "org.imaginationforpeople.android2");
if(flag != 0) {
ImageView flagView = (ImageView) layout.findViewById(R.id.projectview_description_flag);
flagView.setImageResource(flag);
}
}
}
TextView website = (TextView) layout.findViewById(R.id.projectview_description_website);
if("".equals(project.getProject().getWebsite()))
website.setVisibility(View.GONE);
else
website.setOnClickListener(this);
if(project.getAboutSection() == null || "".equals(project.getAboutSection())) {
LinearLayout aboutContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_about_container);
aboutContainer.setVisibility(View.GONE);
} else {
TextView aboutText = (TextView) layout.findViewById(R.id.projectview_description_about_text);
aboutText.setText(project.getAboutSection().trim());
}
if("".equals(project.getThemes())) {
LinearLayout themesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_themes_container);
themesContainer.setVisibility(View.GONE);
} else {
TextView themesText = (TextView) layout.findViewById(R.id.projectview_description_themes_text);
themesText.setText(project.getThemes());
}
if(project.getProject().getObjectives().size() == 0) {
LinearLayout objectivesContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_objectives_container);
objectivesContainer.setVisibility(View.GONE);
} else {
TextView objectivesText = (TextView) layout.findViewById(R.id.projectview_description_objectives_text);
List<Objective> objectivesObject = project.getProject().getObjectives();
String objectives = objectivesObject.get(0).getName();
for(int i = 1; i < objectivesObject.size(); i++) {
objectives += ", " + objectivesObject.get(i).getName();
}
objectivesText.setText(objectives);
}
LinearLayout questions = (LinearLayout) layout.findViewById(R.id.projectview_description_questions_container);
for(Question question : project.getProject().getQuestions()) {
if(question.getAnswer() != null) {
LinearLayout questionLayout = (LinearLayout) inflater.inflate(R.layout.projectview_question, null);
TextView questionView = (TextView) questionLayout.findViewById(R.id.projectview_question_question);
TextView answerView = (TextView) questionLayout.findViewById(R.id.projectview_question_answer);
questionView.setText(Build.VERSION.SDK_INT < 14 ? question.getQuestion().toUpperCase() : question.getQuestion());
answerView.setText(question.getAnswer().trim());
questions.addView(questionLayout);
}
}
if(project.getProject().getMembers().size() == 0) {
LinearLayout membersContainer = (LinearLayout) layout.findViewById(R.id.projectview_description_members_container);
membersContainer.setVisibility(View.GONE);
} else {
LinearLayout members = (LinearLayout) layout.findViewById(R.id.projectview_description_members_text);
for(User member : project.getProject().getMembers()) {
TextView memberName = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, null);
memberName.setText(member.getFullname());
memberName.setCompoundDrawablesWithIntrinsicBounds(null, null, member.getAvatarDrawable(), null);
members.addView(memberName);
}
}
return layout;
}
|
diff --git a/amibe/src/org/jcae/mesh/stitch/EdgeProjector.java b/amibe/src/org/jcae/mesh/stitch/EdgeProjector.java
index 2eb2356a..4c5987fb 100644
--- a/amibe/src/org/jcae/mesh/stitch/EdgeProjector.java
+++ b/amibe/src/org/jcae/mesh/stitch/EdgeProjector.java
@@ -1,828 +1,832 @@
/*
* Project Info: http://jcae.sourceforge.net
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* (C) Copyright 2013, by EADS France
*/
package org.jcae.mesh.stitch;
import gnu.trove.set.hash.THashSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jcae.mesh.amibe.algos3d.VertexSwapper;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.TriangleHE;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.amibe.metrics.Location;
import org.jcae.mesh.amibe.projection.TriangleKdTree;
import org.jcae.mesh.stitch.TriangleProjector.ProjectionType;
import org.jcae.mesh.xmldata.Amibe2VTK;
import org.jcae.mesh.xmldata.MeshWriter;
/**
*
* @author Jerome Robert
*/
class EdgeProjector {
private interface Pool<E> extends Collection<E>
{
E get();
E pop();
}
private static <E> Pool<E> createPool()
{
return new DebugPool<E>();
}
private static class TPool<E> extends THashSet<E> implements Pool<E>
{
public E get()
{
int n = _set.length;
for(int i = 0; i < n; i++)
{
if(_set[i] != FREE && _set[i] != REMOVED)
return (E) _set[i];
}
throw new NoSuchElementException();
}
public E pop()
{
int n = _set.length;
for(int i = 0; i < n; i++)
{
if(_set[i] != FREE && _set[i] != REMOVED)
{
E toReturn = (E) _set[i];
removeAt(i);
return toReturn;
}
}
throw new NoSuchElementException();
}
}
private static class DebugPool<E> extends LinkedHashSet<E> implements Pool<E>
{
public E get()
{
return iterator().next();
}
public E pop()
{
Iterator<E> it = iterator();
E toReturn = it.next();
it.remove();
return toReturn;
}
@Override
public boolean add(E e) {
assert e != null;
return super.add(e);
}
}
private final static Logger LOGGER = Logger.getLogger(EdgeProjector.class.getName());
private final Pool<Triangle> triangles = createPool();
//projectors for origin vertices
private final List<TriangleProjector> triangleProjectors1 = new ArrayList<TriangleProjector>();
//the current projector for origin vertices
private TriangleProjector triangleProjector1;
private boolean projector1Valid;
//projectors for origin vertices
private final List<TriangleProjector> triangleProjectors2 = new ArrayList<TriangleProjector>();
//the current projector for origin vertices
private TriangleProjector triangleProjector2;
private boolean projector2Valid;
private Integer[] triangleProjectorOrder;
/** A projector which will alway be too far to be concidered */
private TriangleProjector farProjector = new TriangleProjector();
private final double[] aabb = new double[6];
private final Mesh mesh;
private final TriangleKdTree kdTree;
private final Pool<AbstractHalfEdge> toProject = createPool();
private final Pool<AbstractHalfEdge> halfInserted = createPool();
private final int group;
private boolean ignoreGroup;
private final Collection<Triangle> splittedTriangle = new ArrayList<Triangle>(3);
private final List<TriangleHelper> triangleHelpers = new ArrayList<TriangleHelper>();
private Vertex lastMergeSource;
private Vertex lastMergeTarget;
private AbstractHalfEdge lastSplitted1;
private AbstractHalfEdge lastSplitted2;
private AbstractHalfEdge edgeToCollapse;
double weight;
private final TriangleSplitter triangleSplitter = new TriangleSplitter();
private final VertexMerger vertexMerger = new VertexMerger();
private final VertexSwapper vertexSwapper;
public boolean checkMerge = true, boundaryOnly;
private final double maxSqrDist, sqrTol;
public EdgeProjector(Mesh mesh, TriangleKdTree kdTree,
Collection<AbstractHalfEdge> edges, int group, double maxDist,
double tol) {
this.mesh = mesh;
this.kdTree = kdTree;
final double tol3 = tol * tol * tol;
vertexSwapper = new VertexSwapper(mesh)
{
@Override
protected boolean isQualityImproved(AbstractHalfEdge.Quality quality) {
return quality.getSwappedQuality()> quality.getQuality() &&
quality.getSwappedAngle() > 0 &&
quality.swappedVolume() < tol3;
}
};
this.toProject.addAll(edges);
for(AbstractHalfEdge e: toProject)
{
e.origin().setMutable(true);
e.destination().setMutable(true);
}
vertexSwapper.setKdTree(kdTree);
this.group = group;
maxSqrDist = maxDist * maxDist;
sqrTol = tol * tol;
}
/**
* When true project on all groups but the specified one, instead of
* projecting to the specified group
*/
public void setIgnoreGroup(boolean ignore)
{
ignoreGroup = ignore;
}
public void setBoundaryOnly(boolean b)
{
boundaryOnly = b;
}
public void project() {
while (true) {
AbstractHalfEdge tp;
if (!halfInserted.isEmpty()) {
tp = halfInserted.pop();
} else if (!toProject.isEmpty()) {
tp = toProject.pop();
if(!tp.hasAttributes(AbstractHalfEdge.BOUNDARY))
//previous merge has render this edge not boundary so
//we skip it
continue;
} else {
break;
}
projectEdge(tp);
}
}
private Vertex splitTriangle(Triangle t, TriangleProjector tp) {
Vertex toInsert = mesh.createVertex(tp.getProjection());
((TriangleHE) t).split(mesh, toInsert, splittedTriangle);
kdTree.replace(t, splittedTriangle);
splittedTriangle.clear();
vertexSwapper.swap(toInsert);
return toInsert;
}
private boolean canMerge(Vertex source, Location target) {
assert source != null;
assert target != null;
if(source == target)
return false;
Location realPosition = null;
if(checkMerge)
realPosition = new Location(weight * source.getX() + (1 - weight) * target.getX(),
weight * source.getY() + (1 - weight) * target.getY(),
weight * source.getZ() + (1 - weight) * target.getZ());
Iterator<AbstractHalfEdge> it = source.getNeighbourIteratorAbstractHalfEdge();
edgeToCollapse = null;
while (it.hasNext()) {
AbstractHalfEdge e = it.next();
assert e.origin() == source;
assert e.origin().isMutable(): e;
if (checkMerge && (!e.origin().isManifold() || !mesh.canMoveOrigin(e, realPosition))) {
LOGGER.info("Cannot move " + source + " to " + realPosition +
". distance=" + source.distance3D(realPosition));
return false;
}
boolean boundary = e.hasAttributes(AbstractHalfEdge.BOUNDARY) ||
(e.sym() != null && e.sym().hasAttributes(AbstractHalfEdge.BOUNDARY));
if(boundaryOnly)
{
// check that we do not create non-manifold edges in boundary
// only mode (manifold stitch).
Iterator<AbstractHalfEdge> itt = e.destination().getNeighbourIteratorAbstractHalfEdge();
while(itt.hasNext())
{
AbstractHalfEdge ee = itt.next();
if(ee.destination() == target &&
(!ee.hasAttributes(AbstractHalfEdge.BOUNDARY) &&
!ee.sym().hasAttributes(AbstractHalfEdge.BOUNDARY) || !boundary))
return false;
}
}
if(e.destination() == target)
{
if(e.hasAttributes(AbstractHalfEdge.OUTER))
e = e.sym();
if(boundary && mesh.canCollapseEdge(e, target))
{
// target has alread been projected to the target mesh so we
// collapse the edge of the source mesh instead of merging vertices.
// Merging vertices would create degenerated triangle.
edgeToCollapse = e;
return true;
}
else
{
LOGGER.info(
"Cannot collapse " + source + " to " + target +
". boundary=" + e.hasAttributes(AbstractHalfEdge.BOUNDARY) +
" canCollapse=" + mesh.canCollapseEdge(e, target));
return false;
}
}
}
return true;
}
/** @return true if the merge was possible */
private void mergeVertices(Vertex source, Vertex target) {
saveAsVTK(mesh);
assert source != target;
assert !Double.isNaN(source.getX());
assert !Double.isNaN(target.getX());
assert !(source.getLink() instanceof Triangle[]);
assert canMerge(source, target);
target.moveTo(weight * source.getX() + (1 - weight) * target.getX(),
weight * source.getY() + (1 - weight) * target.getY(),
weight * source.getZ() + (1 - weight) * target.getZ());
if(edgeToCollapse == null)
vertexMerger.merge(mesh, target, source, target);
else
{
assert (edgeToCollapse.origin() == source && edgeToCollapse.destination() == target) ||
(edgeToCollapse.origin() == target && edgeToCollapse.destination() == source);
Triangle t = edgeToCollapse.getTri();
if(lastSplitted1 != null && lastSplitted1.getTri() == t)
lastSplitted1 = null;
if(lastSplitted2 != null && lastSplitted2 .getTri() == t)
lastSplitted2 = null;
toProject.remove(edgeToCollapse);
toProject.remove(edgeToCollapse.next());
toProject.remove(edgeToCollapse.prev());
mesh.edgeCollapse(edgeToCollapse, target);
kdTree.remove(t);
edgeToCollapse = null;
}
target.setMutable(false);
saveAsVTK(mesh);
}
private void splitEdge(AbstractHalfEdge toSplit, Vertex v) {
if (toSplit.hasAttributes(AbstractHalfEdge.BOUNDARY))
{
Triangle t = toSplit.getTri();
kdTree.remove(t);
mesh.vertexSplit(toSplit, v);
AbstractHalfEdge newEdge = toSplit.next().sym().next();
addTriangleToKdTree(toSplit.getTri());
addTriangleToKdTree(newEdge.getTri());
}
else
{
Triangle t1 = toSplit.getTri();
Triangle t2 = toSplit.sym().getTri();
kdTree.remove(t1);
kdTree.remove(t2);
mesh.vertexSplit(toSplit, v);
AbstractHalfEdge newEdge = toSplit.next().sym().next();
assert toSplit.destination() == v;
assert newEdge.origin() == v;
addTriangleToKdTree(toSplit.getTri());
addTriangleToKdTree(toSplit.sym().getTri());
addTriangleToKdTree(newEdge.getTri());
addTriangleToKdTree(newEdge.sym().getTri());
}
vertexSwapper.swap(v);
}
private void addTriangleToKdTree(Triangle triangle) {
if (!triangle.hasAttributes(AbstractHalfEdge.OUTER)) {
kdTree.addTriangle(triangle);
}
}
private Vertex splitEdge(TriangleProjector tp) {
Vertex v = mesh.createVertex(tp.getProjection());
AbstractHalfEdge toSplit = tp.getEdge();
if (toSplit.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) {
LOGGER.info(
"I will not split a non-manifold edge as there should not be "+
"any non-manifold edges here: "+toSplit);
return null;
} else {
splitEdge(toSplit, v);
}
return v;
}
/**
* Split 2 edges
* @param edge1 an edge to be splitted with a copy of vertexToInsert
* @param edge2 an edge to be splitted with vertexToInsert
* @param vertexToInsert the point to insert on edge2
* @return The vertex splitting edge1
*/
private void split2Edges(Vertex v1, AbstractHalfEdge edge1, Vertex v2,
AbstractHalfEdge edge2) {
assert v1 != null;
assert v1 != edge1.origin();
assert v1 != edge1.destination();
assert TriangleHelper.isOnEdge(v1, edge1.origin(), edge1.destination(),
triangleProjector1.sqrMaxDistance);
// I duplicate the vertex because I'm almost sure that
// vertexSplit doesn't support inserted vertex which are
// already in the mesh
check(mesh);
splitEdge(edge1, v1);
check(mesh);
if (edge2 != null) {
assert v2 != edge2.origin();
assert v2 != edge2.destination();
assert TriangleHelper.isOnEdge(v2, edge2.origin(),
edge2.destination(), triangleProjector1.sqrTolerance);
splitEdge(edge2, v2);
check(mesh);
}
}
public static boolean checkMesh = false;
private static void check(Mesh mesh) {
if(checkMesh)
{
assert mesh.isValid();
assert mesh.checkNoDegeneratedTriangles();
assert mesh.checkNoInvertedTriangles();
}
}
/**
* Find the border edge adjacent to the given edge and sharing its
* destination vertex
*/
private AbstractHalfEdge getNextBorderEdge(AbstractHalfEdge edge) {
assert edge.hasAttributes(AbstractHalfEdge.BOUNDARY): "boundary edge expected: "+edge;
AbstractHalfEdge toReturn = edge.next();
int gid = edge.getTri().getGroupId();
while (toReturn.destination() != mesh.outerVertex &&
!(toReturn.hasAttributes(AbstractHalfEdge.BOUNDARY) &&
toReturn.getTri().getGroupId() == gid)) {
toReturn = toReturn.sym().next();
}
assert toReturn.origin() == edge.destination();
return toReturn.destination() == mesh.outerVertex ? null : toReturn;
}
private AbstractHalfEdge getPreviousBorderEdge(AbstractHalfEdge edge) {
assert edge.hasAttributes(AbstractHalfEdge.BOUNDARY): "boundary edge expected: "+edge;
AbstractHalfEdge toReturn = edge.next().next();
int gid = edge.getTri().getGroupId();
while (toReturn.origin() != mesh.outerVertex &&
!(toReturn.hasAttributes(AbstractHalfEdge.BOUNDARY) &&
toReturn.getTri().getGroupId() == gid)) {
toReturn = toReturn.sym().next().next();
}
assert toReturn.destination() == edge.origin();
return toReturn.origin() == mesh.outerVertex ? null : toReturn;
}
private void handleOutOutCase(AbstractHalfEdge edge) {
lastMergeSource = null;
lastMergeTarget = null;
if (triangleProjector1.getType() == ProjectionType.OUT && triangleProjector2.getType() == ProjectionType.OUT) {
//split and edge of the triangle and split the projected
//edge. The edge may cut 2 edges of the triangle but we will
//insert only one
Location p2 = triangleProjector2.getProjection();
Location p1 = triangleProjector1.getProjection();
triangleSplitter.split(p1, p2, triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (triangleSplitter.getSplittedEdge() != null && lastMergeTarget == null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
assert TriangleHelper.isOnEdge(lastMergeTarget, p1, p2,
triangleProjector1.sqrTolerance);
}
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(p2, edge.destination(),
edge.origin(), lastMergeTarget, lastMergeSource,
triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null) {
assert lastMergeSource != null : lastMergeTarget;
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
lastSplitted2 = edge.next().sym().next();
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
}
/**
* Select the good algorithm, apply it and update lastInserted,
* lastSplitted1 and lastSplitted2.
*/
private void dispatchCases(boolean origin, boolean destination,
AbstractHalfEdge edge, Triangle t) {
lastMergeSource = null;
lastMergeTarget = null;
lastSplitted1 = null;
lastSplitted2 = null;
if (triangleProjector1.getType() == ProjectionType.OUT && !destination) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.destination(),
triangleProjector1.getProjection(),
triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
+ if(lastMergeTarget != null && !lastMergeTarget.isMutable())
+ lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector1.getProjection(),
edge.origin(), edge.destination(), lastMergeTarget,
lastMergeSource, triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (triangleProjector2.getType() == ProjectionType.OUT && !origin) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.origin(),
triangleProjector2.getProjection(),
triangleProjector2.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
+ if(lastMergeTarget != null && !lastMergeTarget.isMutable())
+ lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector2.getProjection(),
edge.destination(), edge.origin(), lastMergeTarget,
lastMergeSource, triangleProjector2.sqrTolerance);
if (l > triangleProjector2.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (origin && triangleProjector1.getType() == ProjectionType.VERTEX &&
edge.origin() != triangleProjector1.getVertex())
{
lastMergeSource = edge.origin();
lastMergeTarget = triangleProjector1.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else if (destination && triangleProjector2.getType() == ProjectionType.VERTEX &&
edge.destination() != triangleProjector2.getVertex())
{
lastMergeSource = edge.destination();
lastMergeTarget = triangleProjector2.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else if (origin && triangleProjector1.getType() == ProjectionType.FACE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.FACE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
} else if (origin && triangleProjector1.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
private boolean mergeAndFinish() {
if (lastMergeTarget != null) {
if(lastMergeSource == lastMergeTarget)
{
LOGGER.info("Something strange append around "+lastMergeSource);
return false;
}
assert lastMergeSource.sqrDistance3D(lastMergeTarget) < triangleProjector1.sqrMaxDistance * 2 : lastMergeSource.sqrDistance3D(lastMergeTarget);
check(mesh);
mergeVertices(lastMergeSource, lastMergeTarget);
check(mesh);
if (lastSplitted1 != null &&
lastSplitted1.hasAttributes(AbstractHalfEdge.BOUNDARY) &&
isToProject(lastSplitted1))
{
halfInserted.add(lastSplitted1);
}
if (lastSplitted2 != null &&
lastSplitted2.hasAttributes(AbstractHalfEdge.BOUNDARY) &&
isToProject(lastSplitted2))
{
halfInserted.add(lastSplitted2);
}
return true;
}
return false;
}
protected boolean isToProject(AbstractHalfEdge edge)
{
return true;
}
/**
* Init the triangles field with triangles where the edge may be
* projected
*/
private void findCandidateTriangles(AbstractHalfEdge edge) {
boolean origin = edge.origin().isMutable();
boolean destination = edge.destination().isMutable();
//if neither origin nor destination both extremities of the edge
//are already projected but the full edge may not be fully projected
//so we will try only the out/out case.
triangles.clear();
boolean notProjected = !origin && !destination &&
edge.hasAttributes(AbstractHalfEdge.BOUNDARY);
if ((origin && destination) || notProjected) {
compteEdgeAABB(edge, aabb);
kdTree.getNearTriangles(aabb, triangles, group, ignoreGroup);
} else {
Vertex vv = origin ? edge.destination() : edge.origin();
Iterator<Triangle> it = vv.getNeighbourIteratorTriangle();
while (it.hasNext()) {
Triangle t = it.next();
if (!t.hasAttributes(AbstractHalfEdge.OUTER) &&
((!ignoreGroup && group >= 0 && t.getGroupId() == group) ||
(ignoreGroup && group >= 0 && t.getGroupId() != group)))
{
triangles.add(t);
}
}
}
}
/**
* Fill triangleProjectors1 and triangleProjectors2, then order them in the
* triangleProjectorOrder array.
* triangleProjectorOrder can be used to iterator over triangleProjectors
* starting with the closest triangle.
* Projecting to the closest triangle instead of a random close triangle is
* more robust.
*/
private void projectToClosest(AbstractHalfEdge edge)
{
boolean origin = edge.origin().isMutable();
boolean destination = edge.destination().isMutable();
findCandidateTriangles(edge);
while(triangleHelpers.size() < triangles.size())
triangleHelpers.add(new TriangleHelper());
int k = 0;
for(Triangle t: triangles)
{
assert t.getAbstractHalfEdge() != null: t;
assert mesh.getTriangles().contains(t): t;
triangleHelpers.get(k++).setTriangle(t);
}
projector1Valid = origin || (!origin && !destination);
projector2Valid = destination || (!origin && !destination);
if (projector1Valid)
projectToClosest(edge.origin(), triangleProjectors1);
if (projector2Valid)
projectToClosest(edge.destination(), triangleProjectors2);
if(triangleProjectorOrder == null || triangleProjectorOrder.length < triangles.size())
triangleProjectorOrder = new Integer[triangles.size()];
for(int i = 0; i < triangleProjectorOrder.length; i++)
triangleProjectorOrder[i] = i;
Arrays.sort(triangleProjectorOrder, 0, triangles.size(), projectorComparator);
}
private final Comparator<Integer> projectorComparator
= new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
double v1, v2;
if(projector1Valid && projector2Valid)
{
v1 = Math.min(triangleProjectors1.get(o1).getSqrDistance(),
triangleProjectors2.get(o1).getSqrDistance());
v2 = Math.min(triangleProjectors1.get(o2).getSqrDistance(),
triangleProjectors2.get(o2).getSqrDistance());
}
else if(projector1Valid)
{
v1 = triangleProjectors1.get(o1).getSqrDistance();
v2 = triangleProjectors1.get(o2).getSqrDistance();
}
else //if(projector2Valid)
{
assert projector2Valid;
v1 = triangleProjectors2.get(o1).getSqrDistance();
v2 = triangleProjectors2.get(o2).getSqrDistance();
}
return Double.compare(v1, v2);
}
};
/**
* Project location to the closest triangle available in the triangleHelpers list.
* triangleHelpers must contains TriangleHelper initialised with the triangle
* of the triangles list.
*/
private void projectToClosest(Location location, List<TriangleProjector> projectors)
{
while(projectors.size() < triangles.size())
{
TriangleProjector tp = new TriangleProjector();
tp.sqrMaxDistance = maxSqrDist;
tp.sqrTolerance = sqrTol;
tp.boundaryOnly = boundaryOnly;
projectors.add(tp);
}
int n = triangles.size();
for(int k = 0; k < n; k++)
{
TriangleProjector tp = projectors.get(k);
tp.reset();
tp.project(location, triangleHelpers.get(k));
}
}
/**
* Project the edge on the given group of the mesh
* @param edge the edge to project
* @param halfProjected filled with the list of half projected edges. A
* half projected edges is an edge whose only one vertex is projected or
* both vertex a projected but on different triangles.
*/
private void projectEdge(AbstractHalfEdge edge) {
boolean origin = edge.origin().isMutable();
boolean destination = edge.destination().isMutable();
projectToClosest(edge);
//if neither origin nor destination both extremities of the edge
//are already projected but the full edge may not be fully projected
//so we will try only the out/out case.
int n = triangles.size();
for (int i = 0; i < n; i++) {
int index = triangleProjectorOrder[i];
triangleProjector1 = farProjector;
triangleProjector2 = farProjector;
if(projector1Valid)
triangleProjector1 = triangleProjectors1.get(index);
if(projector2Valid)
triangleProjector2 = triangleProjectors2.get(index);
TriangleHelper th = triangleHelpers.get(index);
triangleSplitter.setTriangle(th);
check(mesh);
dispatchCases(origin, destination, edge, th.getTriangle());
check(mesh);
if (lastMergeTarget != null) {
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance) : origin + " " + triangleProjector1 + "\n" + destination + " " + triangleProjector2;
}
if (mergeAndFinish()) {
return;
}
}
// OUT/OUT case have a lower priority over other cases so we process
// it in a separate loop after others.
if (origin && destination) {
for (int i = 0; i < n; i++) {
int index = triangleProjectorOrder[i];
triangleProjector1 = triangleProjectors1.get(index);
triangleProjector2 = triangleProjectors2.get(index);
triangleSplitter.setTriangle(triangleHelpers.get(index));
handleOutOutCase(edge);
if (mergeAndFinish()) {
return;
}
}
}
}
private static void compteEdgeAABB(AbstractHalfEdge edge, double[] aabb)
{
aabb[0] = Math.min(edge.origin().getX(), edge.destination().getX());
aabb[1] = Math.min(edge.origin().getY(), edge.destination().getY());
aabb[2] = Math.min(edge.origin().getZ(), edge.destination().getZ());
aabb[3] = Math.max(edge.origin().getX(), edge.destination().getX());
aabb[4] = Math.max(edge.origin().getY(), edge.destination().getY());
aabb[5] = Math.max(edge.origin().getZ(), edge.destination().getZ());
}
private static int saveVTKCounter = 0;
static boolean saveVTK = false;
public static void saveAsVTK(Mesh mesh)
{
if(saveVTK)
{
try {
String dir = "/tmp/tmp.amibe";
MeshWriter.writeObject3D(mesh, dir, null);
String name = "/tmp/non-manifold-stitch"+(saveVTKCounter++)+".vtp";
System.err.println("saving to "+name);
new Amibe2VTK(dir).write(name);
} catch (Exception ex) {
Logger.getLogger(NonManifoldStitch.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
| false | true |
private void dispatchCases(boolean origin, boolean destination,
AbstractHalfEdge edge, Triangle t) {
lastMergeSource = null;
lastMergeTarget = null;
lastSplitted1 = null;
lastSplitted2 = null;
if (triangleProjector1.getType() == ProjectionType.OUT && !destination) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.destination(),
triangleProjector1.getProjection(),
triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector1.getProjection(),
edge.origin(), edge.destination(), lastMergeTarget,
lastMergeSource, triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (triangleProjector2.getType() == ProjectionType.OUT && !origin) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.origin(),
triangleProjector2.getProjection(),
triangleProjector2.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector2.getProjection(),
edge.destination(), edge.origin(), lastMergeTarget,
lastMergeSource, triangleProjector2.sqrTolerance);
if (l > triangleProjector2.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (origin && triangleProjector1.getType() == ProjectionType.VERTEX &&
edge.origin() != triangleProjector1.getVertex())
{
lastMergeSource = edge.origin();
lastMergeTarget = triangleProjector1.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else if (destination && triangleProjector2.getType() == ProjectionType.VERTEX &&
edge.destination() != triangleProjector2.getVertex())
{
lastMergeSource = edge.destination();
lastMergeTarget = triangleProjector2.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else if (origin && triangleProjector1.getType() == ProjectionType.FACE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.FACE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
} else if (origin && triangleProjector1.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
|
private void dispatchCases(boolean origin, boolean destination,
AbstractHalfEdge edge, Triangle t) {
lastMergeSource = null;
lastMergeTarget = null;
lastSplitted1 = null;
lastSplitted2 = null;
if (triangleProjector1.getType() == ProjectionType.OUT && !destination) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.destination(),
triangleProjector1.getProjection(),
triangleProjector1.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if(lastMergeTarget != null && !lastMergeTarget.isMutable())
lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector1.getProjection(),
edge.origin(), edge.destination(), lastMergeTarget,
lastMergeSource, triangleProjector1.sqrTolerance);
if (l > triangleProjector1.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted1 = edge;
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (triangleProjector2.getType() == ProjectionType.OUT && !origin) {
//Split and edge of the triangle and split the projected edge
triangleSplitter.splitApex(edge.origin(),
triangleProjector2.getProjection(),
triangleProjector2.sqrTolerance);
lastMergeTarget = triangleSplitter.getSplitVertex();
if (lastMergeTarget == null && triangleSplitter.getSplittedEdge() != null) {
lastMergeTarget = mesh.createVertex(triangleSplitter.getSplitPoint());
}
if(lastMergeTarget != null && !lastMergeTarget.isMutable())
lastMergeTarget = null;
if (lastMergeTarget != null) {
lastMergeSource = mesh.createVertex(0, 0, 0);
double l = TriangleHelper.reverseProject(triangleProjector2.getProjection(),
edge.destination(), edge.origin(), lastMergeTarget,
lastMergeSource, triangleProjector2.sqrTolerance);
if (l > triangleProjector2.sqrMaxDistance) {
lastMergeTarget = null;
}
}
if (lastMergeTarget != null && canMerge(lastMergeSource,
lastMergeTarget)) {
split2Edges(lastMergeSource, edge, lastMergeTarget,
triangleSplitter.getSplittedEdge());
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else {
lastMergeTarget = null;
}
} else if (origin && triangleProjector1.getType() == ProjectionType.VERTEX &&
edge.origin() != triangleProjector1.getVertex())
{
lastMergeSource = edge.origin();
lastMergeTarget = triangleProjector1.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
} else if (destination && triangleProjector2.getType() == ProjectionType.VERTEX &&
edge.destination() != triangleProjector2.getVertex())
{
lastMergeSource = edge.destination();
lastMergeTarget = triangleProjector2.getVertex();
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
} else if (origin && triangleProjector1.getType() == ProjectionType.FACE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.FACE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitTriangle(t, triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
} else if (origin && triangleProjector1.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.origin();
if (canMerge(lastMergeSource, triangleProjector1.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector1);
lastSplitted1 = edge;
lastSplitted2 = getPreviousBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector1.sqrTolerance);
}
} else if (destination && triangleProjector2.getType() == ProjectionType.EDGE) {
lastMergeSource = edge.destination();
if (canMerge(lastMergeSource, triangleProjector2.getProjection())) {
lastMergeTarget = splitEdge(triangleProjector2);
lastSplitted1 = edge;
lastSplitted2 = getNextBorderEdge(edge);
assert TriangleHelper.isOnEdge(lastMergeSource, edge.origin(),
edge.destination(), triangleProjector2.sqrTolerance);
}
}
if (lastMergeSource != null && lastMergeTarget != null && !canMerge(lastMergeSource,
lastMergeTarget)) {
lastMergeTarget = null;
}
}
|
diff --git a/app/notifiers/Mails.java b/app/notifiers/Mails.java
index e8ed26b..ed3e14c 100644
--- a/app/notifiers/Mails.java
+++ b/app/notifiers/Mails.java
@@ -1,71 +1,71 @@
package notifiers;
import models.Invitation;
import models.Project;
import models.Role;
import models.User;
import play.Play;
import play.data.validation.Email;
import play.data.validation.Required;
import play.db.jpa.JPA;
import play.exceptions.MailException;
import play.i18n.Messages;
import play.libs.Codec;
import play.mvc.Mailer;
import play.mvc.Router;
import securesocial.provider.SocialUser;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: sheldon
* Date: 5/24/12
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class Mails extends Mailer {
private static final String SECURESOCIAL_MAILER_FROM = "securesocial.mailer.from";
private static final String INVITATIONS_JOIN = "security.SignUpController.join";
private static final String INVITED_CODE = "code";
public static boolean sendInvitationEmail(String email, Project project, User fromUser, Role role) {
- setSubject(Messages.get("mail_invitation_subject"));
+ setSubject(Messages.get("mail_invitation_subject", fromUser.fullName, project.title));
setFrom(Play.configuration.getProperty(SECURESOCIAL_MAILER_FROM));
Date cutoffDate = new Date(System.currentTimeMillis() - 86400000L);
List<Invitation> invitations = JPA.em().createNamedQuery("Invitation.findExistingRecent")
.setParameter("project", project)
.setParameter("fromUser", fromUser)
.setParameter("cutoffDate", cutoffDate)
.setParameter("toEmail", email)
.getResultList();
if (invitations.isEmpty()) {
// only send email if has not send the same email recently
try {
addRecipient(email);
String uuid = Codec.UUID();
Map<String, Object> args = new HashMap<String, Object>();
args.put(INVITED_CODE, uuid);
String activationUrl = Router.getFullUrl(INVITATIONS_JOIN, args);
send(fromUser, project, activationUrl);
Invitation invitation = new Invitation();
invitation.fromUser = fromUser;
invitation.project = project;
invitation.toEmail = email;
invitation.uuid = uuid;
invitation.role = role;
invitation.save();
return true;
} catch (MailException me) {
// do nothing
}
}
return false;
}
}
| true | true |
public static boolean sendInvitationEmail(String email, Project project, User fromUser, Role role) {
setSubject(Messages.get("mail_invitation_subject"));
setFrom(Play.configuration.getProperty(SECURESOCIAL_MAILER_FROM));
Date cutoffDate = new Date(System.currentTimeMillis() - 86400000L);
List<Invitation> invitations = JPA.em().createNamedQuery("Invitation.findExistingRecent")
.setParameter("project", project)
.setParameter("fromUser", fromUser)
.setParameter("cutoffDate", cutoffDate)
.setParameter("toEmail", email)
.getResultList();
if (invitations.isEmpty()) {
// only send email if has not send the same email recently
try {
addRecipient(email);
String uuid = Codec.UUID();
Map<String, Object> args = new HashMap<String, Object>();
args.put(INVITED_CODE, uuid);
String activationUrl = Router.getFullUrl(INVITATIONS_JOIN, args);
send(fromUser, project, activationUrl);
Invitation invitation = new Invitation();
invitation.fromUser = fromUser;
invitation.project = project;
invitation.toEmail = email;
invitation.uuid = uuid;
invitation.role = role;
invitation.save();
return true;
} catch (MailException me) {
// do nothing
}
}
return false;
}
|
public static boolean sendInvitationEmail(String email, Project project, User fromUser, Role role) {
setSubject(Messages.get("mail_invitation_subject", fromUser.fullName, project.title));
setFrom(Play.configuration.getProperty(SECURESOCIAL_MAILER_FROM));
Date cutoffDate = new Date(System.currentTimeMillis() - 86400000L);
List<Invitation> invitations = JPA.em().createNamedQuery("Invitation.findExistingRecent")
.setParameter("project", project)
.setParameter("fromUser", fromUser)
.setParameter("cutoffDate", cutoffDate)
.setParameter("toEmail", email)
.getResultList();
if (invitations.isEmpty()) {
// only send email if has not send the same email recently
try {
addRecipient(email);
String uuid = Codec.UUID();
Map<String, Object> args = new HashMap<String, Object>();
args.put(INVITED_CODE, uuid);
String activationUrl = Router.getFullUrl(INVITATIONS_JOIN, args);
send(fromUser, project, activationUrl);
Invitation invitation = new Invitation();
invitation.fromUser = fromUser;
invitation.project = project;
invitation.toEmail = email;
invitation.uuid = uuid;
invitation.role = role;
invitation.save();
return true;
} catch (MailException me) {
// do nothing
}
}
return false;
}
|
diff --git a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/VimInputInterceptorFactory.java b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/VimInputInterceptorFactory.java
index ec590992..496a7756 100644
--- a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/VimInputInterceptorFactory.java
+++ b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/VimInputInterceptorFactory.java
@@ -1,237 +1,238 @@
package net.sourceforge.vrapper.eclipse.interceptor;
import java.util.HashMap;
import java.util.HashSet;
import net.sourceforge.vrapper.eclipse.activator.VrapperPlugin;
import net.sourceforge.vrapper.eclipse.platform.EclipsePlatform;
import net.sourceforge.vrapper.eclipse.platform.SWTRegisterManager;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.SpecialKey;
import net.sourceforge.vrapper.keymap.vim.SimpleKeyStroke;
import net.sourceforge.vrapper.platform.Configuration;
import net.sourceforge.vrapper.platform.SimpleConfiguration;
import net.sourceforge.vrapper.utils.CaretType;
import net.sourceforge.vrapper.vim.DefaultEditorAdaptor;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.Options;
import net.sourceforge.vrapper.vim.modes.AbstractVisualMode;
import net.sourceforge.vrapper.vim.modes.InsertMode;
import net.sourceforge.vrapper.vim.modes.LinewiseVisualMode;
import net.sourceforge.vrapper.vim.modes.NormalMode;
import net.sourceforge.vrapper.vim.modes.TempVisualMode;
import net.sourceforge.vrapper.vim.modes.VisualMode;
import net.sourceforge.vrapper.vim.register.RegisterManager;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.source.ContentAssistantFacade;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.AbstractTextEditor;
/**
* A factory for interceptors which route input events to a {@link EditorAdaptor}
* instance. This instance decides whether to pass the event to the underlying
* editor or not.
*
* @author Matthias Radig
*/
public class VimInputInterceptorFactory implements InputInterceptorFactory {
private VimInputInterceptorFactory() { /* NOP */ }
public static final VimInputInterceptorFactory INSTANCE = new VimInputInterceptorFactory();
private static final HashMap<Integer, SpecialKey> specialKeys;
/** Maps "Escape characters" to the corresponding Control + <i>x</i> character. */
private static final HashMap<Character, Character> escapedChars;
private static final HashSet<Integer> ignoredKeyCodes;
static {
specialKeys = new HashMap<Integer, SpecialKey>();
specialKeys.put( SWT.ARROW_LEFT, SpecialKey.ARROW_LEFT);
specialKeys.put( SWT.ARROW_RIGHT, SpecialKey.ARROW_RIGHT);
specialKeys.put( SWT.ARROW_UP, SpecialKey.ARROW_UP);
specialKeys.put( SWT.ARROW_DOWN, SpecialKey.ARROW_DOWN);
specialKeys.put( (int)SWT.BS, SpecialKey.BACKSPACE);
specialKeys.put( (int)SWT.DEL, SpecialKey.DELETE);
specialKeys.put( (int)SWT.TAB, SpecialKey.TAB);
specialKeys.put( SWT.INSERT, SpecialKey.INSERT);
specialKeys.put( SWT.PAGE_DOWN, SpecialKey.PAGE_DOWN);
specialKeys.put( SWT.PAGE_UP, SpecialKey.PAGE_UP);
specialKeys.put( SWT.HOME, SpecialKey.HOME);
specialKeys.put( SWT.END, SpecialKey.END);
specialKeys.put( (int)SWT.ESC, SpecialKey.ESC);
specialKeys.put( (int)SWT.CR, SpecialKey.RETURN);
specialKeys.put( SWT.KEYPAD_CR, SpecialKey.RETURN);
SpecialKey[] values = SpecialKey.values();
int swtStart = SWT.F1;
int skStart = SpecialKey.F1.ordinal();
//SWT has up to F20
for (int i=0; i < 20; ++i)
specialKeys.put(swtStart+i, values[skStart+i]);
/*
* Translate the "Escape characters" sent by Ctrl + alpha keys to regular characters.
* This circumvents problems with the user language where raw keyCode values might not.
*/
escapedChars = new HashMap<Character, Character>();
escapedChars.put('\u0000', '@');
escapedChars.put('\u0001', 'a');
escapedChars.put('\u0002', 'b');
escapedChars.put('\u0003', 'c');
escapedChars.put('\u0004', 'd');
escapedChars.put('\u0005', 'e');
escapedChars.put('\u0006', 'f');
escapedChars.put('\u0007', 'g');
escapedChars.put('\u0008', 'h');
escapedChars.put('\t', 'i');
escapedChars.put('\n', 'j');
escapedChars.put('\u000B', 'k');
escapedChars.put('\u000C', 'l');
escapedChars.put('\r', 'm');
escapedChars.put('\u000E', 'n');
escapedChars.put('\u000F', 'o');
escapedChars.put('\u0010', 'p');
escapedChars.put('\u0011', 'q');
escapedChars.put('\u0012', 'r');
escapedChars.put('\u0013', 's');
escapedChars.put('\u0014', 't');
escapedChars.put('\u0015', 'u');
escapedChars.put('\u0016', 'v');
escapedChars.put('\u0017', 'w');
escapedChars.put('\u0018', 'x');
escapedChars.put('\u0019', 'y');
escapedChars.put('\u001A', 'z');
escapedChars.put('\u001B', '[');
escapedChars.put('\u001C', '\\');
escapedChars.put('\u001D', ']');
escapedChars.put('\u001E', '^');
escapedChars.put('\u001F', '_');
ignoredKeyCodes = new HashSet<Integer>();
ignoredKeyCodes.add(SWT.CTRL);
ignoredKeyCodes.add(SWT.SHIFT);
ignoredKeyCodes.add(SWT.ALT);
ignoredKeyCodes.add(SWT.CAPS_LOCK);
ignoredKeyCodes.add(SWT.COMMAND);
}
private static final RegisterManager globalRegisterManager = new SWTRegisterManager(PlatformUI.getWorkbench().getDisplay());
private static final Configuration sharedConfiguration = new SimpleConfiguration();
public InputInterceptor createInterceptor(AbstractTextEditor abstractTextEditor, ITextViewer textViewer) {
EclipsePlatform platform = new EclipsePlatform(abstractTextEditor, textViewer, sharedConfiguration);
DefaultEditorAdaptor editorAdaptor = new DefaultEditorAdaptor(
platform,
globalRegisterManager, VrapperPlugin.isVrapperEnabled());
InputInterceptor interceptor = createInterceptor(editorAdaptor);
if (editorAdaptor.getConfiguration().get(Options.EXIT_LINK_MODE)) {
LinkedModeHandler linkedModeHandler = new LinkedModeHandler(editorAdaptor);
LinkedModeHandler.registerListener(textViewer.getDocument(), linkedModeHandler);
interceptor.setLinkedModeHandler(linkedModeHandler);
}
if (editorAdaptor.getConfiguration().get(Options.CONTENT_ASSIST_MODE)) {
if (textViewer instanceof SourceViewer) {
final SourceViewer sourceViewer = (SourceViewer)textViewer;
final ContentAssistantFacade contentAssistant= sourceViewer.getContentAssistantFacade();
if (contentAssistant != null) {
contentAssistant.addCompletionListener(new ContentAssistModeHandler(editorAdaptor));
}
}
}
return interceptor;
}
public InputInterceptor createInterceptor(EditorAdaptor editorAdaptor) {
return new VimInputInterceptor(editorAdaptor);
}
private static final class VimInputInterceptor implements InputInterceptor {
private final EditorAdaptor editorAdaptor;
private LinkedModeHandler linkedModeHandler;
private VimInputInterceptor(EditorAdaptor editorAdaptor) {
this.editorAdaptor = editorAdaptor;
}
public void verifyKey(VerifyEvent event) {
if (!VrapperPlugin.isVrapperEnabled()) {
return;
}
if (ignoredKeyCodes.contains(event.keyCode)) {
return;
}
KeyStroke keyStroke;
boolean shiftKey = (event.stateMask & SWT.SHIFT) != 0;
boolean altKey = (event.stateMask & SWT.ALT) != 0;
boolean ctrlKey = (event.stateMask & SWT.CONTROL) != 0;
if(specialKeys.containsKey(event.keyCode)) {
keyStroke = new SimpleKeyStroke(specialKeys.get(event.keyCode), shiftKey, altKey, ctrlKey);
} else if (escapedChars.containsKey(event.character)) {
keyStroke = new SimpleKeyStroke(escapedChars.get(event.character), shiftKey, altKey, ctrlKey);
} else {
keyStroke = new SimpleKeyStroke(event.character, shiftKey, altKey, ctrlKey);
}
event.doit = !editorAdaptor.handleKey(keyStroke);
}
public EditorAdaptor getEditorAdaptor() {
return editorAdaptor;
}
public void selectionChanged(SelectionChangedEvent event) {
- if (!VrapperPlugin.isMouseDown()
- || !(event.getSelection() instanceof TextSelection)
- || !editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE))
+ if ( ! VrapperPlugin.isVrapperEnabled()
+ || ! VrapperPlugin.isMouseDown()
+ || ! (event.getSelection() instanceof TextSelection)
+ || ! editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE))
return;
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection instanceof TextSelection) {
if (selection.getLength() == 0) {
if(VisualMode.NAME.equals(editorAdaptor.getCurrentModeName())
|| LinewiseVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
}
else if(TempVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
}
} else if(selection.getLength() != 0) {
// Fix caret type
if (editorAdaptor.getConfiguration().get(Options.SELECTION).equals("inclusive")) {
CaretType type = CaretType.LEFT_SHIFTED_RECTANGULAR;
if (editorAdaptor.getSelection().isReversed()) {
type = CaretType.RECTANGULAR;
}
editorAdaptor.getCursorService().setCaret(type);
}
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
}
@Override
public LinkedModeHandler getLinkedModeHandler() {
return linkedModeHandler;
}
@Override
public void setLinkedModeHandler(LinkedModeHandler handler) {
this.linkedModeHandler = handler;
}
}
}
| true | true |
public void selectionChanged(SelectionChangedEvent event) {
if (!VrapperPlugin.isMouseDown()
|| !(event.getSelection() instanceof TextSelection)
|| !editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE))
return;
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection instanceof TextSelection) {
if (selection.getLength() == 0) {
if(VisualMode.NAME.equals(editorAdaptor.getCurrentModeName())
|| LinewiseVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
}
else if(TempVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
}
} else if(selection.getLength() != 0) {
// Fix caret type
if (editorAdaptor.getConfiguration().get(Options.SELECTION).equals("inclusive")) {
CaretType type = CaretType.LEFT_SHIFTED_RECTANGULAR;
if (editorAdaptor.getSelection().isReversed()) {
type = CaretType.RECTANGULAR;
}
editorAdaptor.getCursorService().setCaret(type);
}
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
}
|
public void selectionChanged(SelectionChangedEvent event) {
if ( ! VrapperPlugin.isVrapperEnabled()
|| ! VrapperPlugin.isMouseDown()
|| ! (event.getSelection() instanceof TextSelection)
|| ! editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE))
return;
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection instanceof TextSelection) {
if (selection.getLength() == 0) {
if(VisualMode.NAME.equals(editorAdaptor.getCurrentModeName())
|| LinewiseVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
}
else if(TempVisualMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
}
} else if(selection.getLength() != 0) {
// Fix caret type
if (editorAdaptor.getConfiguration().get(Options.SELECTION).equals("inclusive")) {
CaretType type = CaretType.LEFT_SHIFTED_RECTANGULAR;
if (editorAdaptor.getSelection().isReversed()) {
type = CaretType.RECTANGULAR;
}
editorAdaptor.getCursorService().setCaret(type);
}
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java
index 52f21ac8b..7515b03db 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java
@@ -1,316 +1,317 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2005 Oliver Burn
//
// 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 com.puppycrawl.tools.checkstyle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;
import java.util.LinkedList;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
/**
* Wrapper command line program for the Checker.
* @author Oliver Burn
**/
public final class Main
{
/** the options to the command line */
private static final Options OPTS = new Options();
static {
OPTS.addOption("c", true, "The check configuration file to use.");
OPTS.addOption("r", true, "Traverse the directory for source files");
OPTS.addOption("o", true, "Sets the output file. Defaults to stdout");
OPTS.addOption("p", true, "Loads the properties file");
OPTS.addOption("n", true, "Loads the package names file");
OPTS.addOption(
"f",
true,
"Sets the output format. (plain|xml). Defaults to plain");
}
/**
* Loops over the files specified checking them for errors. The exit code
* is the number of errors found in all the files.
* @param aArgs the command line arguments
**/
public static void main(String[] aArgs)
{
// parse the parameters
final CommandLineParser clp = new PosixParser();
CommandLine line = null;
try {
line = clp.parse(OPTS, aArgs);
}
catch (final ParseException e) {
e.printStackTrace();
usage();
}
+ assert line != null;
// setup the properties
final Properties props =
line.hasOption("p")
? loadProperties(new File(line.getOptionValue("p")))
: System.getProperties();
// ensure a config file is specified
if (!line.hasOption("c")) {
System.out.println("Must specify a config XML file.");
usage();
}
final Configuration config = loadConfig(line, props);
//Load the set of package names
ModuleFactory moduleFactory = null;
if (line.hasOption("n")) {
moduleFactory = loadPackages(line);
}
// setup the output stream
OutputStream out = null;
boolean closeOut = false;
if (line.hasOption("o")) {
final String fname = line.getOptionValue("o");
try {
out = new FileOutputStream(fname);
closeOut = true;
}
catch (final FileNotFoundException e) {
System.out.println("Could not find file: '" + fname + "'");
System.exit(1);
}
}
else {
out = System.out;
closeOut = false;
}
final AuditListener listener = createListener(line, out, closeOut);
final List files = getFilesToProcess(line);
final Checker c = createChecker(config, moduleFactory, listener);
final File[] processedFiles = new File[files.size()];
files.toArray(processedFiles);
final int numErrs = c.process(processedFiles);
c.destroy();
System.exit(numErrs);
}
/**
* Creates the Checker object.
*
* @param aConfig the configuration to use
* @param aFactory the module factor to use
* @param aNosy the sticky beak to track what happens
* @return a nice new fresh Checker
*/
private static Checker createChecker(Configuration aConfig,
ModuleFactory aFactory,
AuditListener aNosy)
{
Checker c = null;
try {
c = new Checker();
c.setModuleFactory(aFactory);
c.configure(aConfig);
c.addListener(aNosy);
}
catch (final Exception e) {
System.out.println("Unable to create Checker: "
+ e.getMessage());
e.printStackTrace(System.out);
System.exit(1);
}
return c;
}
/**
* Determines the files to process.
*
* @param aLine the command line options specifying what files to process
* @return list of files to process
*/
private static List getFilesToProcess(CommandLine aLine)
{
final List files = new LinkedList();
if (aLine.hasOption("r")) {
final String[] values = aLine.getOptionValues("r");
for (int i = 0; i < values.length; i++) {
traverse(new File(values[i]), files);
}
}
final String[] remainingArgs = aLine.getArgs();
for (int i = 0; i < remainingArgs.length; i++) {
files.add(new File(remainingArgs[i]));
}
if (files.isEmpty()) {
System.out.println("Must specify files to process");
usage();
}
return files;
}
/**
* Create the audit listener
*
* @param aLine command line options supplied
* @param aOut the stream to log to
* @param aCloseOut whether the stream should be closed
* @return a fresh new <code>AuditListener</code>
*/
private static AuditListener createListener(CommandLine aLine,
OutputStream aOut,
boolean aCloseOut)
{
final String format =
aLine.hasOption("f") ? aLine.getOptionValue("f") : "plain";
AuditListener listener = null;
if ("xml".equals(format)) {
listener = new XMLLogger(aOut, aCloseOut);
}
else if ("plain".equals(format)) {
listener = new DefaultLogger(aOut, aCloseOut);
}
else {
System.out.println("Invalid format: (" + format
+ "). Must be 'plain' or 'xml'.");
usage();
}
return listener;
}
/**
* Loads the packages, or exists if unable to.
*
* @param aLine the supplied command line options
* @return a fresh new <code>ModuleFactory</code>
*/
private static ModuleFactory loadPackages(CommandLine aLine)
{
try {
return PackageNamesLoader.loadModuleFactory(
aLine.getOptionValue("n"));
}
catch (final CheckstyleException e) {
System.out.println("Error loading package names file");
e.printStackTrace(System.out);
System.exit(1);
return null; // never get here
}
}
/**
* Loads the configuration file. Will exit if unable to load.
*
* @param aLine specifies the location of the configuration
* @param aProps the properties to resolve with the configuration
* @return a fresh new configuration
*/
private static Configuration loadConfig(CommandLine aLine,
Properties aProps)
{
try {
return ConfigurationLoader.loadConfiguration(
aLine.getOptionValue("c"), new PropertiesExpander(aProps));
}
catch (final CheckstyleException e) {
System.out.println("Error loading configuration file");
e.printStackTrace(System.out);
System.exit(1);
return null; // can never get here
}
}
/** Prints the usage information. **/
private static void usage()
{
final HelpFormatter hf = new HelpFormatter();
hf.printHelp(
"java "
+ Main.class.getName()
+ " [options] -c <config.xml> file...",
OPTS);
System.exit(1);
}
/**
* Traverses a specified node looking for files to check. Found
* files are added to a specified list. Subdirectories are also
* traversed.
*
* @param aNode the node to process
* @param aFiles list to add found files to
*/
private static void traverse(File aNode, List aFiles)
{
if (aNode.canRead()) {
if (aNode.isDirectory()) {
final File[] nodes = aNode.listFiles();
for (int i = 0; i < nodes.length; i++) {
traverse(nodes[i], aFiles);
}
}
else if (aNode.isFile()) {
aFiles.add(aNode);
}
}
}
/**
* Loads properties from a File.
* @param aFile the properties file
* @return the properties in aFile
*/
private static Properties loadProperties(File aFile)
{
final Properties properties = new Properties();
try {
FileInputStream fis = null;
fis = new FileInputStream(aFile);
properties.load(fis);
fis.close();
}
catch (final IOException ex) {
System.out.println("Unable to load properties from file: "
+ aFile.getAbsolutePath());
ex.printStackTrace(System.out);
System.exit(1);
}
return properties;
}
}
| true | true |
public static void main(String[] aArgs)
{
// parse the parameters
final CommandLineParser clp = new PosixParser();
CommandLine line = null;
try {
line = clp.parse(OPTS, aArgs);
}
catch (final ParseException e) {
e.printStackTrace();
usage();
}
// setup the properties
final Properties props =
line.hasOption("p")
? loadProperties(new File(line.getOptionValue("p")))
: System.getProperties();
// ensure a config file is specified
if (!line.hasOption("c")) {
System.out.println("Must specify a config XML file.");
usage();
}
final Configuration config = loadConfig(line, props);
//Load the set of package names
ModuleFactory moduleFactory = null;
if (line.hasOption("n")) {
moduleFactory = loadPackages(line);
}
// setup the output stream
OutputStream out = null;
boolean closeOut = false;
if (line.hasOption("o")) {
final String fname = line.getOptionValue("o");
try {
out = new FileOutputStream(fname);
closeOut = true;
}
catch (final FileNotFoundException e) {
System.out.println("Could not find file: '" + fname + "'");
System.exit(1);
}
}
else {
out = System.out;
closeOut = false;
}
final AuditListener listener = createListener(line, out, closeOut);
final List files = getFilesToProcess(line);
final Checker c = createChecker(config, moduleFactory, listener);
final File[] processedFiles = new File[files.size()];
files.toArray(processedFiles);
final int numErrs = c.process(processedFiles);
c.destroy();
System.exit(numErrs);
}
|
public static void main(String[] aArgs)
{
// parse the parameters
final CommandLineParser clp = new PosixParser();
CommandLine line = null;
try {
line = clp.parse(OPTS, aArgs);
}
catch (final ParseException e) {
e.printStackTrace();
usage();
}
assert line != null;
// setup the properties
final Properties props =
line.hasOption("p")
? loadProperties(new File(line.getOptionValue("p")))
: System.getProperties();
// ensure a config file is specified
if (!line.hasOption("c")) {
System.out.println("Must specify a config XML file.");
usage();
}
final Configuration config = loadConfig(line, props);
//Load the set of package names
ModuleFactory moduleFactory = null;
if (line.hasOption("n")) {
moduleFactory = loadPackages(line);
}
// setup the output stream
OutputStream out = null;
boolean closeOut = false;
if (line.hasOption("o")) {
final String fname = line.getOptionValue("o");
try {
out = new FileOutputStream(fname);
closeOut = true;
}
catch (final FileNotFoundException e) {
System.out.println("Could not find file: '" + fname + "'");
System.exit(1);
}
}
else {
out = System.out;
closeOut = false;
}
final AuditListener listener = createListener(line, out, closeOut);
final List files = getFilesToProcess(line);
final Checker c = createChecker(config, moduleFactory, listener);
final File[] processedFiles = new File[files.size()];
files.toArray(processedFiles);
final int numErrs = c.process(processedFiles);
c.destroy();
System.exit(numErrs);
}
|
diff --git a/src/main/java/cpw/mods/fml/installer/DownloadUtils.java b/src/main/java/cpw/mods/fml/installer/DownloadUtils.java
index 323c522..badb1a9 100644
--- a/src/main/java/cpw/mods/fml/installer/DownloadUtils.java
+++ b/src/main/java/cpw/mods/fml/installer/DownloadUtils.java
@@ -1,255 +1,254 @@
package cpw.mods.fml.installer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.jar.JarOutputStream;
import java.util.jar.Pack200;
import javax.swing.ProgressMonitor;
import LZMA.LzmaInputStream;
import argo.jdom.JsonNode;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
public class DownloadUtils {
private static final String PACK_NAME = ".pack.lzma";
public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad)
{
- Random r = new Random();
for (JsonNode library : libraries)
{
String libName = library.getStringValue("name");
List<String> checksums = null;
if (library.isArrayNode("checksums"))
{
checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() {
public String apply(JsonNode node)
{
return node.getText();
}
}));
}
monitor.setNote(String.format("Considering library %s", libName));
if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker))
{
String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class);
nameparts[0] = nameparts[0].replace('.', '/');
String jarName = nameparts[1] + '-' + nameparts[2] + ".jar";
String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName;
File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar));
String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/";
- if (MirrorData.INSTANCE.hasMirrors())
+ if (MirrorData.INSTANCE.hasMirrors() && library.isStringValue("url"))
{
libURL = MirrorData.INSTANCE.getMirrorURL();
}
else if (library.isStringValue("url"))
{
libURL = library.getStringValue("url") + "/";
}
if (libPath.exists() && checksumValid(libPath, checksums))
{
monitor.setProgress(progress++);
continue;
}
libPath.getParentFile().mkdirs();
monitor.setNote(String.format("Downloading library %s", libName));
libURL += pathName;
File packFile = new File(libPath.getParentFile(), libName + PACK_NAME);
if (!downloadFile(libName, packFile, libURL + PACK_NAME, null))
{
- monitor.setNote("Failed to locate packed library, trying unpacked");
+ monitor.setNote(String.format("Failed to locate packed library %s, trying unpacked", libName));
if (!downloadFile(libName, libPath, libURL, checksums))
{
bad.add(libName);
}
}
else
{
try
{
monitor.setNote(String.format("Unpacking packed file %s",packFile.getName()));
FileOutputStream jarBytes = new FileOutputStream(libPath);
JarOutputStream jos = new JarOutputStream(jarBytes);
LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile));
Pack200.newUnpacker().unpack(decompressedPackFile, jos);
monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName()));
packFile.delete();
if (checksumValid(libPath, checksums))
{
grabbed.add(libName);
}
else
{
bad.add(libName);
}
}
catch (Exception e)
{
bad.add(libName);
}
}
}
monitor.setProgress(progress++);
}
return progress;
}
private static boolean checksumValid(File libPath, List<String> checksums)
{
try
{
return checksums == null || checksums.isEmpty() || checksums.contains(Hashing.sha1().hashBytes(Files.toByteArray(libPath)).toString());
}
catch (IOException e)
{
return false;
}
}
public static List<String> downloadList(String libURL)
{
try
{
URL url = new URL(libURL);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection);
return CharStreams.readLines(CharStreams.newReaderSupplier(urlSupplier, Charsets.UTF_8));
}
catch (Exception e)
{
return Collections.emptyList();
}
}
public static boolean downloadFile(String libName, File libPath, String libURL, List<String> checksums)
{
try
{
URL url = new URL(libURL);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection);
Files.copy(urlSupplier, libPath);
if (checksumValid(libPath, checksums))
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
}
}
static class URLISSupplier implements InputSupplier<InputStream> {
private final URLConnection connection;
private URLISSupplier(URLConnection connection)
{
this.connection = connection;
}
@Override
public InputStream getInput() throws IOException
{
return connection.getInputStream();
}
}
public static IMonitor buildMonitor()
{
if (ServerInstall.headless)
{
return new IMonitor()
{
@Override
public void setMaximum(int max)
{
}
@Override
public void setNote(String note)
{
System.out.println("MESSAGE: "+ note);
}
@Override
public void setProgress(int progress)
{
}
@Override
public void close()
{
}
};
}
else
{
return new IMonitor() {
private ProgressMonitor monitor;
{
monitor = new ProgressMonitor(null, "Downloading libraries", "Libraries are being analyzed", 0, 1);
monitor.setMillisToPopup(0);
monitor.setMillisToDecideToPopup(0);
}
@Override
public void setMaximum(int max)
{
monitor.setMaximum(max);
}
@Override
public void setNote(String note)
{
monitor.setNote(note);
}
@Override
public void setProgress(int progress)
{
monitor.setProgress(progress);
}
@Override
public void close()
{
monitor.close();
}
};
}
}
}
| false | true |
public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad)
{
Random r = new Random();
for (JsonNode library : libraries)
{
String libName = library.getStringValue("name");
List<String> checksums = null;
if (library.isArrayNode("checksums"))
{
checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() {
public String apply(JsonNode node)
{
return node.getText();
}
}));
}
monitor.setNote(String.format("Considering library %s", libName));
if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker))
{
String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class);
nameparts[0] = nameparts[0].replace('.', '/');
String jarName = nameparts[1] + '-' + nameparts[2] + ".jar";
String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName;
File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar));
String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/";
if (MirrorData.INSTANCE.hasMirrors())
{
libURL = MirrorData.INSTANCE.getMirrorURL();
}
else if (library.isStringValue("url"))
{
libURL = library.getStringValue("url") + "/";
}
if (libPath.exists() && checksumValid(libPath, checksums))
{
monitor.setProgress(progress++);
continue;
}
libPath.getParentFile().mkdirs();
monitor.setNote(String.format("Downloading library %s", libName));
libURL += pathName;
File packFile = new File(libPath.getParentFile(), libName + PACK_NAME);
if (!downloadFile(libName, packFile, libURL + PACK_NAME, null))
{
monitor.setNote("Failed to locate packed library, trying unpacked");
if (!downloadFile(libName, libPath, libURL, checksums))
{
bad.add(libName);
}
}
else
{
try
{
monitor.setNote(String.format("Unpacking packed file %s",packFile.getName()));
FileOutputStream jarBytes = new FileOutputStream(libPath);
JarOutputStream jos = new JarOutputStream(jarBytes);
LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile));
Pack200.newUnpacker().unpack(decompressedPackFile, jos);
monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName()));
packFile.delete();
if (checksumValid(libPath, checksums))
{
grabbed.add(libName);
}
else
{
bad.add(libName);
}
}
catch (Exception e)
{
bad.add(libName);
}
}
}
monitor.setProgress(progress++);
}
return progress;
}
|
public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad)
{
for (JsonNode library : libraries)
{
String libName = library.getStringValue("name");
List<String> checksums = null;
if (library.isArrayNode("checksums"))
{
checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() {
public String apply(JsonNode node)
{
return node.getText();
}
}));
}
monitor.setNote(String.format("Considering library %s", libName));
if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker))
{
String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class);
nameparts[0] = nameparts[0].replace('.', '/');
String jarName = nameparts[1] + '-' + nameparts[2] + ".jar";
String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName;
File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar));
String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/";
if (MirrorData.INSTANCE.hasMirrors() && library.isStringValue("url"))
{
libURL = MirrorData.INSTANCE.getMirrorURL();
}
else if (library.isStringValue("url"))
{
libURL = library.getStringValue("url") + "/";
}
if (libPath.exists() && checksumValid(libPath, checksums))
{
monitor.setProgress(progress++);
continue;
}
libPath.getParentFile().mkdirs();
monitor.setNote(String.format("Downloading library %s", libName));
libURL += pathName;
File packFile = new File(libPath.getParentFile(), libName + PACK_NAME);
if (!downloadFile(libName, packFile, libURL + PACK_NAME, null))
{
monitor.setNote(String.format("Failed to locate packed library %s, trying unpacked", libName));
if (!downloadFile(libName, libPath, libURL, checksums))
{
bad.add(libName);
}
}
else
{
try
{
monitor.setNote(String.format("Unpacking packed file %s",packFile.getName()));
FileOutputStream jarBytes = new FileOutputStream(libPath);
JarOutputStream jos = new JarOutputStream(jarBytes);
LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile));
Pack200.newUnpacker().unpack(decompressedPackFile, jos);
monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName()));
packFile.delete();
if (checksumValid(libPath, checksums))
{
grabbed.add(libName);
}
else
{
bad.add(libName);
}
}
catch (Exception e)
{
bad.add(libName);
}
}
}
monitor.setProgress(progress++);
}
return progress;
}
|
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyBlockProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyBlockProducer.java
index 2d5b773e..ba9ef9b8 100644
--- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyBlockProducer.java
+++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ModifyBlockProducer.java
@@ -1,370 +1,368 @@
/******************************************************************************
* ModifyBlockProducer.java - created by [email protected] on Oct 2, 2006
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Contributors:
* Rui Feng ([email protected])
*****************************************************************************/
package org.sakaiproject.evaluation.tool.producers;
import java.util.ArrayList;
import java.util.List;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalItemsLogic;
import org.sakaiproject.evaluation.model.EvalTemplate;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.model.constant.EvalConstants;
import org.sakaiproject.evaluation.tool.EvaluationConstant;
import org.sakaiproject.evaluation.tool.params.BlockIdsParameters;
import org.sakaiproject.evaluation.tool.params.EvalViewParameters;
import org.sakaiproject.evaluation.tool.utils.ItemBlockUtils;
import org.sakaiproject.evaluation.tool.utils.TemplateItemUtils;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.evolvers.TextInputEvolver;
import uk.org.ponder.rsf.flow.jsfnav.DynamicNavigationCaseReporter;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
/**
* Page for Create, modify, preview, delete a Block type Item
*
* @author: Rui Feng ([email protected])
*/
public class ModifyBlockProducer implements ViewComponentProducer,
ViewParamsReporter, DynamicNavigationCaseReporter {
public static final String VIEW_ID = "modify_block"; //$NON-NLS-1$
public String getViewID() {
return VIEW_ID;
}
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
private EvalExternalLogic external;
public void setExternal(EvalExternalLogic external) {
this.external = external;
}
private EvalItemsLogic itemsLogic;
public void setItemsLogic(EvalItemsLogic itemsLogic) {
this.itemsLogic = itemsLogic;
}
private TextInputEvolver richTextEvolver;
public void setRichTextEvolver(TextInputEvolver richTextEvolver) {
this.richTextEvolver = richTextEvolver;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
BlockIdsParameters evParameters = (BlockIdsParameters) viewparams;
Long templateId = evParameters.templateId;
System.out.println("templateId=" + evParameters.templateId);
System.out.println("block item ids=" + evParameters.templateItemIds);
boolean modify = false;// this variable indicate if it is for modify
// existing Block
boolean validScaleIds = true;// this variable indicate if the passed Ids
// have the same scale
Integer firstDO = null;// the first items's original displayOrder
String templateItemIds = evParameters.templateItemIds;
boolean createFromBlock = false;
// analyze the string of templateItemIds
String[] strIds = evParameters.templateItemIds.split(",");
EvalTemplateItem templateItems[] = new EvalTemplateItem[strIds.length];
for (int i = 0; i < strIds.length; i++) {
System.out.println("checked id[" + i + "]=" + strIds[i]);
templateItems[i] = itemsLogic
.getTemplateItemById(Long.valueOf(strIds[i]));
}
firstDO = templateItems[0].getDisplayOrder();
// check if it is to modify an existing block or creating a new one
if (strIds.length == 1 && templateItems[0] != null)
modify = true;
// check if each templateItem has the same scale, otherwise show warning
// text
if (templateItems.length > 1) {
Long scaleId = templateItems[0].getItem().getScale().getId();
System.out.println("scale id[" + 0 + "]=" + scaleId.intValue());
for (int i = 1; i < templateItems.length; i++) {
Long myScaleId = templateItems[i].getItem().getScale().getId();
System.out.println("scale id[" + i + "]=" + myScaleId.intValue());
if (!myScaleId.equals(scaleId)) {
validScaleIds = false;
System.out.println("scale is not same");
break;
}
}
}
if (!modify && validScaleIds) {// creating new block with the same scale
// case
boolean shift = false;
// get the first Block ID if any, and shift it to the first of the
// templateItems array
for (int i = 0; i < templateItems.length; i++) {
if (templateItems[i].getBlockParent() != null
&& templateItems[i].getBlockParent().booleanValue() == true) {
if (i > 0) {
EvalTemplateItem tmpTI = templateItems[0];
templateItems[0] = templateItems[i];
templateItems[i] = tmpTI;
shift = true;
}
createFromBlock = true;
break;
}
}
// reconstruct IDs to be passed
if (shift) {
templateItemIds = templateItems[0].getId().toString();
for (int i = 1; i < templateItems.length; i++) {
templateItemIds = templateItemIds + ","
+ templateItems[i].getId().toString();
}// end of for loop
}
}
UIOutput.make(tofill, "modify-block-title", messageLocator
.getMessage("modifyblock.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(tofill, "create-eval-title", messageLocator
.getMessage("createeval.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIInternalLink.make(tofill,
"summary-toplink", messageLocator.getMessage("summary.page.title"), //$NON-NLS-1$ //$NON-NLS-2$
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (!validScaleIds) {
// show error page with back button
UIBranchContainer showError = UIBranchContainer
.make(tofill, "errorPage:");
UIOutput.make(showError, "errorMsg", messageLocator
.getMessage("modifyblock.error.message"));
UIOutput.make(showError, "back-button", messageLocator
.getMessage("modifyblock.back.button"));
} else {// render block page
UIBranchContainer showBlock = UIBranchContainer
.make(tofill, "blockPage:");
UIForm form = UIForm.make(showBlock, "blockForm"); //$NON-NLS-1$
UIOutput.make(form,
"item-header", messageLocator.getMessage("modifyitem.item.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "itemNo", "1."); // TODO:
UIOutput.make(form, "itemClassification", messageLocator
.getMessage("modifytemplate.itemtype.block"));
UIOutput.make(form, "added-by", messageLocator
.getMessage("modifyitem.added.by"));
UIOutput.make(form, "userInfo", external
.getUserDisplayName(templateItems[0].getOwner()));
// TODO: remove link
UIOutput.make(form, "item-header-text-header", messageLocator
.getMessage("modifyblock.item.header.text.header"));
UIOutput.make(form, "scale-type-header", messageLocator
.getMessage("modifyblock.scale.type.header"));
UIOutput.make(form, "scaleLabel", templateItems[0].getItem().getScale()
.getTitle());
UIOutput.make(form, "add-na-header", messageLocator
.getMessage("modifyitem.add.na.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "ideal-coloring-header", messageLocator
.getMessage("modifyblock.ideal.coloring.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "item-category-header", messageLocator
.getMessage("modifyitem.item.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "course-category-header", messageLocator
.getMessage("modifyitem.course.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "instructor-category-header", messageLocator
.getMessage("modifyitem.instructor.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
// Radio Buttons for "Item Category"
String[] courseCategoryList = {
messageLocator.getMessage("modifyitem.course.category.header"),
messageLocator.getMessage("modifyitem.instructor.category.header"), };
UISelect radios = null;
String itemPath = null;
if (modify) {// modify existing block
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator." + templateItems[0].getId()
+ ".itemCategory", null);
} else {// create new block
// creat new block from multiple existing Block and other scaled item
if (createFromBlock) {
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
} else {
// selected items are all normal scaled type
itemPath = "templateItemBeanLocator.new1";
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
}
}
String itemPathD = itemPath + ".";
UIInput itemtext = UIInput.make(form, "item_text:", itemPathD
+ "item.itemText", null);
richTextEvolver.evolveTextInput(itemtext);
UIBoundBoolean.make(form, "item_NA", itemPathD + "usesNA", null);
String selectID = radios.getFullID();
UISelectChoice.make(form, "item_category_C", selectID, 0); //$NON-NLS-1$
UISelectChoice.make(form, "item_category_I", selectID, 1);
if (modify) {// for modify existing block item
// get Block child item
EvalTemplate template = templateItems[0].getTemplate();
List l = itemsLogic.getTemplateItemsForTemplate(template.getId(), null);
List childList = ItemBlockUtils.getChildItems(l, templateItems[0]
.getId());
for (int i = 0; i < childList.size(); i++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(i);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", child.getDisplayOrder()
.toString());
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, child.getItem()
.getItemText());
}
} else {
if (createFromBlock) {// render the first block child , then others,
// possibly other block child
- // TODO: wait for Aaron' s logic layer method to get child
- // TemplateItems providing parent ID
List allTemplateItems = itemsLogic.getTemplateItemsForTemplate(
templateId, null);
int orderNo = 0;
for (int i = 0; i < templateItems.length; i++) {
if (TemplateItemUtils.getTemplateItemType(templateItems[i]).equals(
EvalConstants.ITEM_TYPE_BLOCK)) {
List childs = ItemBlockUtils.getChildItems(allTemplateItems,
templateItems[i].getId());
for (int k = 0; k < childs.size(); k++) {
EvalTemplateItem myChild = (EvalTemplateItem) childs.get(k);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, myChild.getItem()
.getItemText());
orderNo++;
}
} else {// normal scale type
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
orderNo++;
}
}
} else {
// selected items are all normal scaled type
for (int i = 0; i < templateItems.length; i++) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer.toString(i + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
}
}
}
UIOutput.make(form, "cancel-button", messageLocator
.getMessage("general.cancel.button"));
UICommand saveCmd = UICommand.make(form, "saveBlockAction",
messageLocator.getMessage("modifyitem.save.button"),
"#{templateBBean.saveBlockItemAction}");
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.childTemplateItemIds}", templateItemIds));
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.originalDisplayOrder}", firstDO));
}
}
public List reportNavigationCases() {
List i = new ArrayList();
i.add(new NavigationCase(PreviewItemProducer.VIEW_ID,
new SimpleViewParameters(PreviewItemProducer.VIEW_ID)));
i.add(new NavigationCase("success", new EvalViewParameters(
ModifyTemplateItemsProducer.VIEW_ID, null)));
return i;
}
public ViewParameters getViewParameters() {
return new BlockIdsParameters();
}
}
| true | true |
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
BlockIdsParameters evParameters = (BlockIdsParameters) viewparams;
Long templateId = evParameters.templateId;
System.out.println("templateId=" + evParameters.templateId);
System.out.println("block item ids=" + evParameters.templateItemIds);
boolean modify = false;// this variable indicate if it is for modify
// existing Block
boolean validScaleIds = true;// this variable indicate if the passed Ids
// have the same scale
Integer firstDO = null;// the first items's original displayOrder
String templateItemIds = evParameters.templateItemIds;
boolean createFromBlock = false;
// analyze the string of templateItemIds
String[] strIds = evParameters.templateItemIds.split(",");
EvalTemplateItem templateItems[] = new EvalTemplateItem[strIds.length];
for (int i = 0; i < strIds.length; i++) {
System.out.println("checked id[" + i + "]=" + strIds[i]);
templateItems[i] = itemsLogic
.getTemplateItemById(Long.valueOf(strIds[i]));
}
firstDO = templateItems[0].getDisplayOrder();
// check if it is to modify an existing block or creating a new one
if (strIds.length == 1 && templateItems[0] != null)
modify = true;
// check if each templateItem has the same scale, otherwise show warning
// text
if (templateItems.length > 1) {
Long scaleId = templateItems[0].getItem().getScale().getId();
System.out.println("scale id[" + 0 + "]=" + scaleId.intValue());
for (int i = 1; i < templateItems.length; i++) {
Long myScaleId = templateItems[i].getItem().getScale().getId();
System.out.println("scale id[" + i + "]=" + myScaleId.intValue());
if (!myScaleId.equals(scaleId)) {
validScaleIds = false;
System.out.println("scale is not same");
break;
}
}
}
if (!modify && validScaleIds) {// creating new block with the same scale
// case
boolean shift = false;
// get the first Block ID if any, and shift it to the first of the
// templateItems array
for (int i = 0; i < templateItems.length; i++) {
if (templateItems[i].getBlockParent() != null
&& templateItems[i].getBlockParent().booleanValue() == true) {
if (i > 0) {
EvalTemplateItem tmpTI = templateItems[0];
templateItems[0] = templateItems[i];
templateItems[i] = tmpTI;
shift = true;
}
createFromBlock = true;
break;
}
}
// reconstruct IDs to be passed
if (shift) {
templateItemIds = templateItems[0].getId().toString();
for (int i = 1; i < templateItems.length; i++) {
templateItemIds = templateItemIds + ","
+ templateItems[i].getId().toString();
}// end of for loop
}
}
UIOutput.make(tofill, "modify-block-title", messageLocator
.getMessage("modifyblock.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(tofill, "create-eval-title", messageLocator
.getMessage("createeval.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIInternalLink.make(tofill,
"summary-toplink", messageLocator.getMessage("summary.page.title"), //$NON-NLS-1$ //$NON-NLS-2$
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (!validScaleIds) {
// show error page with back button
UIBranchContainer showError = UIBranchContainer
.make(tofill, "errorPage:");
UIOutput.make(showError, "errorMsg", messageLocator
.getMessage("modifyblock.error.message"));
UIOutput.make(showError, "back-button", messageLocator
.getMessage("modifyblock.back.button"));
} else {// render block page
UIBranchContainer showBlock = UIBranchContainer
.make(tofill, "blockPage:");
UIForm form = UIForm.make(showBlock, "blockForm"); //$NON-NLS-1$
UIOutput.make(form,
"item-header", messageLocator.getMessage("modifyitem.item.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "itemNo", "1."); // TODO:
UIOutput.make(form, "itemClassification", messageLocator
.getMessage("modifytemplate.itemtype.block"));
UIOutput.make(form, "added-by", messageLocator
.getMessage("modifyitem.added.by"));
UIOutput.make(form, "userInfo", external
.getUserDisplayName(templateItems[0].getOwner()));
// TODO: remove link
UIOutput.make(form, "item-header-text-header", messageLocator
.getMessage("modifyblock.item.header.text.header"));
UIOutput.make(form, "scale-type-header", messageLocator
.getMessage("modifyblock.scale.type.header"));
UIOutput.make(form, "scaleLabel", templateItems[0].getItem().getScale()
.getTitle());
UIOutput.make(form, "add-na-header", messageLocator
.getMessage("modifyitem.add.na.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "ideal-coloring-header", messageLocator
.getMessage("modifyblock.ideal.coloring.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "item-category-header", messageLocator
.getMessage("modifyitem.item.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "course-category-header", messageLocator
.getMessage("modifyitem.course.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "instructor-category-header", messageLocator
.getMessage("modifyitem.instructor.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
// Radio Buttons for "Item Category"
String[] courseCategoryList = {
messageLocator.getMessage("modifyitem.course.category.header"),
messageLocator.getMessage("modifyitem.instructor.category.header"), };
UISelect radios = null;
String itemPath = null;
if (modify) {// modify existing block
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator." + templateItems[0].getId()
+ ".itemCategory", null);
} else {// create new block
// creat new block from multiple existing Block and other scaled item
if (createFromBlock) {
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
} else {
// selected items are all normal scaled type
itemPath = "templateItemBeanLocator.new1";
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
}
}
String itemPathD = itemPath + ".";
UIInput itemtext = UIInput.make(form, "item_text:", itemPathD
+ "item.itemText", null);
richTextEvolver.evolveTextInput(itemtext);
UIBoundBoolean.make(form, "item_NA", itemPathD + "usesNA", null);
String selectID = radios.getFullID();
UISelectChoice.make(form, "item_category_C", selectID, 0); //$NON-NLS-1$
UISelectChoice.make(form, "item_category_I", selectID, 1);
if (modify) {// for modify existing block item
// get Block child item
EvalTemplate template = templateItems[0].getTemplate();
List l = itemsLogic.getTemplateItemsForTemplate(template.getId(), null);
List childList = ItemBlockUtils.getChildItems(l, templateItems[0]
.getId());
for (int i = 0; i < childList.size(); i++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(i);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", child.getDisplayOrder()
.toString());
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, child.getItem()
.getItemText());
}
} else {
if (createFromBlock) {// render the first block child , then others,
// possibly other block child
// TODO: wait for Aaron' s logic layer method to get child
// TemplateItems providing parent ID
List allTemplateItems = itemsLogic.getTemplateItemsForTemplate(
templateId, null);
int orderNo = 0;
for (int i = 0; i < templateItems.length; i++) {
if (TemplateItemUtils.getTemplateItemType(templateItems[i]).equals(
EvalConstants.ITEM_TYPE_BLOCK)) {
List childs = ItemBlockUtils.getChildItems(allTemplateItems,
templateItems[i].getId());
for (int k = 0; k < childs.size(); k++) {
EvalTemplateItem myChild = (EvalTemplateItem) childs.get(k);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, myChild.getItem()
.getItemText());
orderNo++;
}
} else {// normal scale type
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
orderNo++;
}
}
} else {
// selected items are all normal scaled type
for (int i = 0; i < templateItems.length; i++) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer.toString(i + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
}
}
}
UIOutput.make(form, "cancel-button", messageLocator
.getMessage("general.cancel.button"));
UICommand saveCmd = UICommand.make(form, "saveBlockAction",
messageLocator.getMessage("modifyitem.save.button"),
"#{templateBBean.saveBlockItemAction}");
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.childTemplateItemIds}", templateItemIds));
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.originalDisplayOrder}", firstDO));
}
}
|
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
BlockIdsParameters evParameters = (BlockIdsParameters) viewparams;
Long templateId = evParameters.templateId;
System.out.println("templateId=" + evParameters.templateId);
System.out.println("block item ids=" + evParameters.templateItemIds);
boolean modify = false;// this variable indicate if it is for modify
// existing Block
boolean validScaleIds = true;// this variable indicate if the passed Ids
// have the same scale
Integer firstDO = null;// the first items's original displayOrder
String templateItemIds = evParameters.templateItemIds;
boolean createFromBlock = false;
// analyze the string of templateItemIds
String[] strIds = evParameters.templateItemIds.split(",");
EvalTemplateItem templateItems[] = new EvalTemplateItem[strIds.length];
for (int i = 0; i < strIds.length; i++) {
System.out.println("checked id[" + i + "]=" + strIds[i]);
templateItems[i] = itemsLogic
.getTemplateItemById(Long.valueOf(strIds[i]));
}
firstDO = templateItems[0].getDisplayOrder();
// check if it is to modify an existing block or creating a new one
if (strIds.length == 1 && templateItems[0] != null)
modify = true;
// check if each templateItem has the same scale, otherwise show warning
// text
if (templateItems.length > 1) {
Long scaleId = templateItems[0].getItem().getScale().getId();
System.out.println("scale id[" + 0 + "]=" + scaleId.intValue());
for (int i = 1; i < templateItems.length; i++) {
Long myScaleId = templateItems[i].getItem().getScale().getId();
System.out.println("scale id[" + i + "]=" + myScaleId.intValue());
if (!myScaleId.equals(scaleId)) {
validScaleIds = false;
System.out.println("scale is not same");
break;
}
}
}
if (!modify && validScaleIds) {// creating new block with the same scale
// case
boolean shift = false;
// get the first Block ID if any, and shift it to the first of the
// templateItems array
for (int i = 0; i < templateItems.length; i++) {
if (templateItems[i].getBlockParent() != null
&& templateItems[i].getBlockParent().booleanValue() == true) {
if (i > 0) {
EvalTemplateItem tmpTI = templateItems[0];
templateItems[0] = templateItems[i];
templateItems[i] = tmpTI;
shift = true;
}
createFromBlock = true;
break;
}
}
// reconstruct IDs to be passed
if (shift) {
templateItemIds = templateItems[0].getId().toString();
for (int i = 1; i < templateItems.length; i++) {
templateItemIds = templateItemIds + ","
+ templateItems[i].getId().toString();
}// end of for loop
}
}
UIOutput.make(tofill, "modify-block-title", messageLocator
.getMessage("modifyblock.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(tofill, "create-eval-title", messageLocator
.getMessage("createeval.page.title")); //$NON-NLS-1$ //$NON-NLS-2$
UIInternalLink.make(tofill,
"summary-toplink", messageLocator.getMessage("summary.page.title"), //$NON-NLS-1$ //$NON-NLS-2$
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (!validScaleIds) {
// show error page with back button
UIBranchContainer showError = UIBranchContainer
.make(tofill, "errorPage:");
UIOutput.make(showError, "errorMsg", messageLocator
.getMessage("modifyblock.error.message"));
UIOutput.make(showError, "back-button", messageLocator
.getMessage("modifyblock.back.button"));
} else {// render block page
UIBranchContainer showBlock = UIBranchContainer
.make(tofill, "blockPage:");
UIForm form = UIForm.make(showBlock, "blockForm"); //$NON-NLS-1$
UIOutput.make(form,
"item-header", messageLocator.getMessage("modifyitem.item.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "itemNo", "1."); // TODO:
UIOutput.make(form, "itemClassification", messageLocator
.getMessage("modifytemplate.itemtype.block"));
UIOutput.make(form, "added-by", messageLocator
.getMessage("modifyitem.added.by"));
UIOutput.make(form, "userInfo", external
.getUserDisplayName(templateItems[0].getOwner()));
// TODO: remove link
UIOutput.make(form, "item-header-text-header", messageLocator
.getMessage("modifyblock.item.header.text.header"));
UIOutput.make(form, "scale-type-header", messageLocator
.getMessage("modifyblock.scale.type.header"));
UIOutput.make(form, "scaleLabel", templateItems[0].getItem().getScale()
.getTitle());
UIOutput.make(form, "add-na-header", messageLocator
.getMessage("modifyitem.add.na.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "ideal-coloring-header", messageLocator
.getMessage("modifyblock.ideal.coloring.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "item-category-header", messageLocator
.getMessage("modifyitem.item.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "course-category-header", messageLocator
.getMessage("modifyitem.course.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
UIOutput.make(form, "instructor-category-header", messageLocator
.getMessage("modifyitem.instructor.category.header")); //$NON-NLS-1$ //$NON-NLS-2$
// Radio Buttons for "Item Category"
String[] courseCategoryList = {
messageLocator.getMessage("modifyitem.course.category.header"),
messageLocator.getMessage("modifyitem.instructor.category.header"), };
UISelect radios = null;
String itemPath = null;
if (modify) {// modify existing block
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator." + templateItems[0].getId()
+ ".itemCategory", null);
} else {// create new block
// creat new block from multiple existing Block and other scaled item
if (createFromBlock) {
itemPath = "templateItemBeanLocator." + templateItems[0].getId();
if (templateItems[0].getScaleDisplaySetting() != null
&& templateItems[0].getScaleDisplaySetting().equals(
EvalConstants.ITEM_SCALE_DISPLAY_STEPPED_COLORED))
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", Boolean.TRUE);
else
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
} else {
// selected items are all normal scaled type
itemPath = "templateItemBeanLocator.new1";
UIBoundBoolean.make(form, "idealColor",
"#{templateBBean.idealColor}", null);
radios = UISelect.make(form, "item_category",
EvaluationConstant.ITEM_CATEGORY_VALUES, courseCategoryList,
"templateItemBeanLocator.new1." + "itemCategory", null);
}
}
String itemPathD = itemPath + ".";
UIInput itemtext = UIInput.make(form, "item_text:", itemPathD
+ "item.itemText", null);
richTextEvolver.evolveTextInput(itemtext);
UIBoundBoolean.make(form, "item_NA", itemPathD + "usesNA", null);
String selectID = radios.getFullID();
UISelectChoice.make(form, "item_category_C", selectID, 0); //$NON-NLS-1$
UISelectChoice.make(form, "item_category_I", selectID, 1);
if (modify) {// for modify existing block item
// get Block child item
EvalTemplate template = templateItems[0].getTemplate();
List l = itemsLogic.getTemplateItemsForTemplate(template.getId(), null);
List childList = ItemBlockUtils.getChildItems(l, templateItems[0]
.getId());
for (int i = 0; i < childList.size(); i++) {
EvalTemplateItem child = (EvalTemplateItem) childList.get(i);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", child.getDisplayOrder()
.toString());
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, child.getItem()
.getItemText());
}
} else {
if (createFromBlock) {// render the first block child , then others,
// possibly other block child
List allTemplateItems = itemsLogic.getTemplateItemsForTemplate(
templateId, null);
int orderNo = 0;
for (int i = 0; i < templateItems.length; i++) {
if (TemplateItemUtils.getTemplateItemType(templateItems[i]).equals(
EvalConstants.ITEM_TYPE_BLOCK)) {
List childs = ItemBlockUtils.getChildItems(allTemplateItems,
templateItems[i].getId());
for (int k = 0; k < childs.size(); k++) {
EvalTemplateItem myChild = (EvalTemplateItem) childs.get(k);
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
// TODO: This should be rich text but it would seem no way there is
// space. NB this is now serious security hole for HTML injection.
UIInput.make(radiobranch, "queText", null, myChild.getItem()
.getItemText());
orderNo++;
}
} else {// normal scale type
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(orderNo)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer
.toString(orderNo + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
orderNo++;
}
}
} else {
// selected items are all normal scaled type
for (int i = 0; i < templateItems.length; i++) {
UIBranchContainer radiobranch = UIBranchContainer.make(form,
"queRow:", Integer.toString(i)); //$NON-NLS-1$
UIOutput.make(radiobranch, "childOrder", Integer.toString(i + 1));
UIInput.make(radiobranch, "queText", null, templateItems[i]
.getItem().getItemText());
}
}
}
UIOutput.make(form, "cancel-button", messageLocator
.getMessage("general.cancel.button"));
UICommand saveCmd = UICommand.make(form, "saveBlockAction",
messageLocator.getMessage("modifyitem.save.button"),
"#{templateBBean.saveBlockItemAction}");
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.childTemplateItemIds}", templateItemIds));
saveCmd.parameters.add(new UIELBinding(
"#{templateBBean.originalDisplayOrder}", firstDO));
}
}
|
diff --git a/mmstudio/src/org/micromanager/MMIntroDlg.java b/mmstudio/src/org/micromanager/MMIntroDlg.java
index 0befaa3b7..283753bda 100644
--- a/mmstudio/src/org/micromanager/MMIntroDlg.java
+++ b/mmstudio/src/org/micromanager/MMIntroDlg.java
@@ -1,257 +1,258 @@
///////////////////////////////////////////////////////////////////////////////
//FILE: MMIntroDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR: Nenad Amodaj, [email protected], Dec 1, 2005
//
// COPYRIGHT: University of California, San Francisco, 2006
// COPYRIGHT: University of California, San Francisco, 2006
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS: $Id$
package org.micromanager;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
import com.swtdesigner.SwingResourceManager;
import ij.IJ;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.JavaUtils;
/**
* Splash screen and introduction dialog.
* Opens up at startup and allows selection of the configuration file.
*/
public class MMIntroDlg extends JDialog {
private static final long serialVersionUID = 1L;
private JTextArea welcomeTextArea_;
private boolean okFlag_ = true;
ArrayList<String> mruCFGFileList_;
private JComboBox cfgFileDropperDown_;
public static String DISCLAIMER_TEXT =
"This software is distributed free of charge 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. In no event shall the copyright owner or contributors " +
"be liable for any direct, indirect, incidental, special, examplary, or consequential damages.\n\n" +
"Copyright University of California San Francisco, 2007, 2008, 2009, 2010. All rights reserved.";
public static String SUPPORT_TEXT =
"Micro-Manager was initially funded by grants from the Sandler Foundation and is now supported by a grant from the NIH.";
public static String CITATION_TEXT =
"If you have found this software useful, please cite Micro-Manager in your publications.";
public MMIntroDlg(String ver, ArrayList<String> mruCFGFileList) {
super();
mruCFGFileList_ = mruCFGFileList;
setFont(new Font("Arial", Font.PLAIN, 10));
setTitle("Micro-Manager Startup");
getContentPane().setLayout(null);
setName("Intro");
setResizable(false);
setModal(true);
setUndecorated(true);
if (! IJ.isMacOSX())
((JPanel) getContentPane()).setBorder(BorderFactory.createLineBorder(Color.GRAY));
setSize(new Dimension(392, 533));
Dimension winSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(screenSize.width/2 - (winSize.width/2), screenSize.height/2 - (winSize.height/2));
JLabel introImage = new JLabel();
introImage.setIcon(SwingResourceManager.getIcon(MMIntroDlg.class, "/org/micromanager/icons/splash.gif"));
introImage.setLayout(null);
introImage.setBounds(0, 0, 392, 197);
introImage.setFocusable(false);
introImage.setBorder(new LineBorder(Color.black, 1, false));
introImage.setText("New JLabel");
getContentPane().add(introImage);
final JButton okButton = new JButton();
okButton.setFont(new Font("Arial", Font.PLAIN, 10));
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = true;
setVisible(false);
}
});
okButton.setText("OK");
- if (JavaUtils.isMac())
+ if (JavaUtils.isMac()) {
okButton.setBounds(200, 497, 81, 24);
- else
+ } else {
okButton.setBounds(100, 492, 81, 24);
+ }
getContentPane().add(okButton);
getRootPane().setDefaultButton(okButton);
final JButton cancelButton = new JButton();
cancelButton.setFont(new Font("Arial", Font.PLAIN, 10));
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = false;
setVisible(false);
}
});
cancelButton.setText("Cancel");
- if (JavaUtils.isMac())
+ if (JavaUtils.isMac()) {
cancelButton.setBounds(100, 497, 81, 24);
- else
- okButton.setBounds(200, 492, 81, 24);
+ } else {
+ cancelButton.setBounds(200, 492, 81, 24);
+ }
getContentPane().add(cancelButton);
- //getRootPane().setDefaultButton(okButton);
final JLabel microscopeManagerLabel = new JLabel();
microscopeManagerLabel.setFont(new Font("", Font.BOLD, 12));
microscopeManagerLabel.setText("Micro-Manager startup configuration");
microscopeManagerLabel.setBounds(5, 198, 259, 22);
getContentPane().add(microscopeManagerLabel);
final JLabel version10betaLabel = new JLabel();
version10betaLabel.setFont(new Font("Arial", Font.PLAIN, 10));
version10betaLabel.setText("MMStudio Version " + ver);
version10betaLabel.setBounds(5, 216, 193, 13);
getContentPane().add(version10betaLabel);
final JLabel loadConfigurationLabel = new JLabel();
loadConfigurationLabel.setFont(new Font("Arial", Font.PLAIN, 10));
loadConfigurationLabel.setText("Configuration file:");
loadConfigurationLabel.setBounds(5, 225, 319, 19);
getContentPane().add(loadConfigurationLabel);
final JButton browseButton = new JButton();
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadConfigFile();
}
});
browseButton.setText("...");
browseButton.setBounds(350, 245, 36, 26);
getContentPane().add(browseButton);
cfgFileDropperDown_ = new JComboBox();
cfgFileDropperDown_.setFont(new Font("Arial", Font.PLAIN, 10));
cfgFileDropperDown_.setBounds(5, 245, 342, 26);
getContentPane().add(cfgFileDropperDown_);
welcomeTextArea_ = new JTextArea() {
@Override
public Insets getInsets() {
return new Insets(10,10,10,10);
}
};
welcomeTextArea_.setBorder(new EtchedBorder());
welcomeTextArea_.setWrapStyleWord(true);
welcomeTextArea_.setText(DISCLAIMER_TEXT + "\n\n" + SUPPORT_TEXT + "\n\n" + CITATION_TEXT);
welcomeTextArea_.setLineWrap(true);
welcomeTextArea_.setFont(new Font("Arial", Font.PLAIN, 10));
welcomeTextArea_.setFocusable(false);
welcomeTextArea_.setEditable(false);
welcomeTextArea_.setBackground(Color.WHITE);
welcomeTextArea_.setBounds(10, 284, 356, 205);
getContentPane().add(welcomeTextArea_);
}
public boolean okChosen() {
return okFlag_;
}
public void setConfigFile(String path) {
// using the provided path, setup the drop down list of config files in the same directory
cfgFileDropperDown_.removeAllItems();
//java.io.FileFilter iocfgFilter = new IOcfgFileFilter();
File cfg = new File(path);
Boolean doesExist = cfg.exists();
if(doesExist)
{
// add the new configuration file to the list
if(!mruCFGFileList_.contains(path)){
// in case persistant data is inconsistent
if( 6 <= mruCFGFileList_.size() ) {
mruCFGFileList_.remove(mruCFGFileList_.size()-2);
}
mruCFGFileList_.add(0, path);
}
}
// if the previously selected config file no longer exists, still use the directory where it had been stored
//File cfgpath = new File(cfg.getParent());
// File matches[] = cfgpath.listFiles(iocfgFilter);
for (Object ofi : mruCFGFileList_){
cfgFileDropperDown_.addItem(ofi.toString());
if(doesExist){
String tvalue = ofi.toString();
if(tvalue.equals(path)){
cfgFileDropperDown_.setSelectedIndex(cfgFileDropperDown_.getItemCount()-1);
}
}
}
cfgFileDropperDown_.addItem("(none)");
// selected configuration path does not exist
if( !doesExist)
cfgFileDropperDown_.setSelectedIndex(cfgFileDropperDown_.getItemCount()-1);
}
public String getConfigFile() {
String tvalue = cfgFileDropperDown_.getSelectedItem().toString();
String nvalue = "(none)";
if( nvalue.equals(tvalue))
tvalue = "";
return tvalue;
}
public String getScriptFile() {
return "";
}
protected void loadConfigFile() {
File f = FileDialogs.openFile(this, "Choose a config file", MMStudioMainFrame.MM_CONFIG_FILE);
if (f != null) {
setConfigFile(f.getAbsolutePath());
}
}
}
| false | true |
public MMIntroDlg(String ver, ArrayList<String> mruCFGFileList) {
super();
mruCFGFileList_ = mruCFGFileList;
setFont(new Font("Arial", Font.PLAIN, 10));
setTitle("Micro-Manager Startup");
getContentPane().setLayout(null);
setName("Intro");
setResizable(false);
setModal(true);
setUndecorated(true);
if (! IJ.isMacOSX())
((JPanel) getContentPane()).setBorder(BorderFactory.createLineBorder(Color.GRAY));
setSize(new Dimension(392, 533));
Dimension winSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(screenSize.width/2 - (winSize.width/2), screenSize.height/2 - (winSize.height/2));
JLabel introImage = new JLabel();
introImage.setIcon(SwingResourceManager.getIcon(MMIntroDlg.class, "/org/micromanager/icons/splash.gif"));
introImage.setLayout(null);
introImage.setBounds(0, 0, 392, 197);
introImage.setFocusable(false);
introImage.setBorder(new LineBorder(Color.black, 1, false));
introImage.setText("New JLabel");
getContentPane().add(introImage);
final JButton okButton = new JButton();
okButton.setFont(new Font("Arial", Font.PLAIN, 10));
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = true;
setVisible(false);
}
});
okButton.setText("OK");
if (JavaUtils.isMac())
okButton.setBounds(200, 497, 81, 24);
else
okButton.setBounds(100, 492, 81, 24);
getContentPane().add(okButton);
getRootPane().setDefaultButton(okButton);
final JButton cancelButton = new JButton();
cancelButton.setFont(new Font("Arial", Font.PLAIN, 10));
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = false;
setVisible(false);
}
});
cancelButton.setText("Cancel");
if (JavaUtils.isMac())
cancelButton.setBounds(100, 497, 81, 24);
else
okButton.setBounds(200, 492, 81, 24);
getContentPane().add(cancelButton);
//getRootPane().setDefaultButton(okButton);
final JLabel microscopeManagerLabel = new JLabel();
microscopeManagerLabel.setFont(new Font("", Font.BOLD, 12));
microscopeManagerLabel.setText("Micro-Manager startup configuration");
microscopeManagerLabel.setBounds(5, 198, 259, 22);
getContentPane().add(microscopeManagerLabel);
final JLabel version10betaLabel = new JLabel();
version10betaLabel.setFont(new Font("Arial", Font.PLAIN, 10));
version10betaLabel.setText("MMStudio Version " + ver);
version10betaLabel.setBounds(5, 216, 193, 13);
getContentPane().add(version10betaLabel);
final JLabel loadConfigurationLabel = new JLabel();
loadConfigurationLabel.setFont(new Font("Arial", Font.PLAIN, 10));
loadConfigurationLabel.setText("Configuration file:");
loadConfigurationLabel.setBounds(5, 225, 319, 19);
getContentPane().add(loadConfigurationLabel);
final JButton browseButton = new JButton();
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadConfigFile();
}
});
browseButton.setText("...");
browseButton.setBounds(350, 245, 36, 26);
getContentPane().add(browseButton);
cfgFileDropperDown_ = new JComboBox();
cfgFileDropperDown_.setFont(new Font("Arial", Font.PLAIN, 10));
cfgFileDropperDown_.setBounds(5, 245, 342, 26);
getContentPane().add(cfgFileDropperDown_);
welcomeTextArea_ = new JTextArea() {
@Override
public Insets getInsets() {
return new Insets(10,10,10,10);
}
};
welcomeTextArea_.setBorder(new EtchedBorder());
welcomeTextArea_.setWrapStyleWord(true);
welcomeTextArea_.setText(DISCLAIMER_TEXT + "\n\n" + SUPPORT_TEXT + "\n\n" + CITATION_TEXT);
welcomeTextArea_.setLineWrap(true);
welcomeTextArea_.setFont(new Font("Arial", Font.PLAIN, 10));
welcomeTextArea_.setFocusable(false);
welcomeTextArea_.setEditable(false);
welcomeTextArea_.setBackground(Color.WHITE);
welcomeTextArea_.setBounds(10, 284, 356, 205);
getContentPane().add(welcomeTextArea_);
}
|
public MMIntroDlg(String ver, ArrayList<String> mruCFGFileList) {
super();
mruCFGFileList_ = mruCFGFileList;
setFont(new Font("Arial", Font.PLAIN, 10));
setTitle("Micro-Manager Startup");
getContentPane().setLayout(null);
setName("Intro");
setResizable(false);
setModal(true);
setUndecorated(true);
if (! IJ.isMacOSX())
((JPanel) getContentPane()).setBorder(BorderFactory.createLineBorder(Color.GRAY));
setSize(new Dimension(392, 533));
Dimension winSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(screenSize.width/2 - (winSize.width/2), screenSize.height/2 - (winSize.height/2));
JLabel introImage = new JLabel();
introImage.setIcon(SwingResourceManager.getIcon(MMIntroDlg.class, "/org/micromanager/icons/splash.gif"));
introImage.setLayout(null);
introImage.setBounds(0, 0, 392, 197);
introImage.setFocusable(false);
introImage.setBorder(new LineBorder(Color.black, 1, false));
introImage.setText("New JLabel");
getContentPane().add(introImage);
final JButton okButton = new JButton();
okButton.setFont(new Font("Arial", Font.PLAIN, 10));
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = true;
setVisible(false);
}
});
okButton.setText("OK");
if (JavaUtils.isMac()) {
okButton.setBounds(200, 497, 81, 24);
} else {
okButton.setBounds(100, 492, 81, 24);
}
getContentPane().add(okButton);
getRootPane().setDefaultButton(okButton);
final JButton cancelButton = new JButton();
cancelButton.setFont(new Font("Arial", Font.PLAIN, 10));
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
okFlag_ = false;
setVisible(false);
}
});
cancelButton.setText("Cancel");
if (JavaUtils.isMac()) {
cancelButton.setBounds(100, 497, 81, 24);
} else {
cancelButton.setBounds(200, 492, 81, 24);
}
getContentPane().add(cancelButton);
final JLabel microscopeManagerLabel = new JLabel();
microscopeManagerLabel.setFont(new Font("", Font.BOLD, 12));
microscopeManagerLabel.setText("Micro-Manager startup configuration");
microscopeManagerLabel.setBounds(5, 198, 259, 22);
getContentPane().add(microscopeManagerLabel);
final JLabel version10betaLabel = new JLabel();
version10betaLabel.setFont(new Font("Arial", Font.PLAIN, 10));
version10betaLabel.setText("MMStudio Version " + ver);
version10betaLabel.setBounds(5, 216, 193, 13);
getContentPane().add(version10betaLabel);
final JLabel loadConfigurationLabel = new JLabel();
loadConfigurationLabel.setFont(new Font("Arial", Font.PLAIN, 10));
loadConfigurationLabel.setText("Configuration file:");
loadConfigurationLabel.setBounds(5, 225, 319, 19);
getContentPane().add(loadConfigurationLabel);
final JButton browseButton = new JButton();
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadConfigFile();
}
});
browseButton.setText("...");
browseButton.setBounds(350, 245, 36, 26);
getContentPane().add(browseButton);
cfgFileDropperDown_ = new JComboBox();
cfgFileDropperDown_.setFont(new Font("Arial", Font.PLAIN, 10));
cfgFileDropperDown_.setBounds(5, 245, 342, 26);
getContentPane().add(cfgFileDropperDown_);
welcomeTextArea_ = new JTextArea() {
@Override
public Insets getInsets() {
return new Insets(10,10,10,10);
}
};
welcomeTextArea_.setBorder(new EtchedBorder());
welcomeTextArea_.setWrapStyleWord(true);
welcomeTextArea_.setText(DISCLAIMER_TEXT + "\n\n" + SUPPORT_TEXT + "\n\n" + CITATION_TEXT);
welcomeTextArea_.setLineWrap(true);
welcomeTextArea_.setFont(new Font("Arial", Font.PLAIN, 10));
welcomeTextArea_.setFocusable(false);
welcomeTextArea_.setEditable(false);
welcomeTextArea_.setBackground(Color.WHITE);
welcomeTextArea_.setBounds(10, 284, 356, 205);
getContentPane().add(welcomeTextArea_);
}
|
diff --git a/solver/src/main/java/solver/constraints/ConstraintFactory.java b/solver/src/main/java/solver/constraints/ConstraintFactory.java
index 8bf651925..26a8a35d2 100644
--- a/solver/src/main/java/solver/constraints/ConstraintFactory.java
+++ b/solver/src/main/java/solver/constraints/ConstraintFactory.java
@@ -1,262 +1,262 @@
/**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package solver.constraints;
import gnu.trove.map.hash.TObjectIntHashMap;
import solver.Solver;
import solver.constraints.binary.EqualX_YC;
import solver.constraints.binary.NotEqualX_YC;
import solver.constraints.nary.IntLinComb;
import solver.constraints.nary.Sum;
import solver.constraints.unary.EqualXC;
import solver.constraints.unary.NotEqualXC;
import solver.variables.IntVar;
import java.util.Arrays;
/**
* A factory to simplify creation of <code>Constraint</code> objects, waiting for a model package.
* This <code>ConstraintFactory</code> is not complete and does not tend to be. It only help users in declaring
* basic and often-used constraints.
*
* @author Charles Prud'homme
* @version 0.01, june 2010
* @since 0.01
*/
public class ConstraintFactory {
protected ConstraintFactory() {
}
/**
* Create a <b>X = c</b> constraint.
* <br/>Based on <code>EqualXC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param c a constant
* @param solver
*/
public static Constraint eq(IntVar x, int c, Solver solver) {
return new EqualXC(x, c, solver);
}
/**
* Create a <b>X = Y</b> constraint.
* <br/>Based on <code>EqualXC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint eq(IntVar x, IntVar y, Solver solver) {
return new EqualX_YC(x, y, 0, solver);
}
/**
* Create a <b>X = Y + C</b> constraint.
* <br/>Based on <code>NotEqualX_YC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param c a constant
* @param solver
*/
public static Constraint eq(IntVar x, IntVar y, int c, Solver solver) {
return new EqualX_YC(x, y, c, solver);
}
/**
* Create a <b>X =/= c</b> constraint.
* <br/>Based on <code>NotEqualXC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param c a constant
* @param solver
*/
public static Constraint neq(IntVar x, int c, Solver solver) {
return new NotEqualXC(x, c, solver);
}
/**
* Create a <b>X =/= Y</b> constraint.
* <br/>Based on <code>NotEqualX_YC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint neq(IntVar x, IntVar y, Solver solver) {
return new NotEqualX_YC(x, y, 0, solver);
}
/**
* Create a <b>X =/= Y + C</b> constraint.
* <br/>Based on <code>NotEqualX_YC</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param c a constant
* @param solver
*/
public static Constraint neq(IntVar x, IntVar y, int c, Solver solver) {
return new NotEqualX_YC(x, y, c, solver);
}
/**
* Create a <b>X <= Y</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint leq(IntVar x, IntVar y, Solver solver) {
return Sum.leq(new IntVar[]{x, y}, new int[]{1, -1}, 0, solver);
}
/**
* Create a <b>X <= c</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param c a constant
* @param solver
*/
public static Constraint leq(IntVar x, int c, Solver solver) {
return Sum.leq(new IntVar[]{x}, new int[]{1}, c, solver);
}
/**
* Create a <b>X < Y</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint lt(IntVar x, IntVar y, Solver solver) {
return Sum.leq(new IntVar[]{x, y}, new int[]{1, -1}, -1, solver);
}
/**
* Create a <b>X >= Y</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint geq(IntVar x, IntVar y, Solver solver) {
return Sum.geq(new IntVar[]{x, y}, new int[]{1, -1}, 0, solver);
}
/**
* Create a <b>X >= c</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param c a constant object
* @param solver
*/
public static Constraint geq(IntVar x, int c, Solver solver) {
return Sum.geq(new IntVar[]{x}, new int[]{1}, c, solver);
}
/**
* Create a <b>X > Y</b> constraint.
* <br/>Based on <code>Sum</code> constraint.
*
* @param x a <code>IntVar</code> object
* @param y a <code>IntVar</code> object
* @param solver
*/
public static Constraint gt(IntVar x, IntVar y, Solver solver) {
return Sum.geq(new IntVar[]{x, y}, 1, solver);
}
public static Constraint scalar(IntVar[] vars, int[] coeffs, IntLinComb.Operator op,
int c, Solver solver) {
TObjectIntHashMap<IntVar> map = new TObjectIntHashMap<IntVar>();
for (int i = 0; i < vars.length; i++) {
map.adjustOrPutValue(vars[i], coeffs[i], coeffs[i]);
if (map.get(vars[i]) == 0) {
map.remove(vars[i]);
}
}
IntVar[] nvars = map.keys(new IntVar[map.size()]);
int b = 0, e = map.size();
IntVar[] tmpV = new IntVar[e];
int[] tmpC = new int[e];
// iteration over the paramater array to avoid non-deterministic behavior introduced by the map
- for (int i = 0; i < vars.length; i++) {
- IntVar var = vars[i];
- if (map.contains(vars[i])) {
+ for (int i = 0; i < nvars.length; i++) {
+ IntVar var = nvars[i];
+ if (map.contains(var)) {
int coeff = map.get(var);
if (coeff > 0) {
tmpV[b] = var;
tmpC[b++] = coeff;
} else if (coeff < 0) {
tmpV[--e] = var;
tmpC[e] = coeff;
}
}
}
return new IntLinComb(tmpV, tmpC, b, op, -c, solver);
}
public static Constraint scalar(IntVar[] vars, int[] coeffs, IntLinComb.Operator op,
IntVar v, int c, Solver solver) {
int size = vars.length;
IntVar[] vtmp = new IntVar[size + 1];
System.arraycopy(vars, 0, vtmp, 0, size);
vtmp[size] = v;
int[] ctmp = new int[size + 1];
System.arraycopy(coeffs, 0, ctmp, 0, size);
ctmp[size] = -c;
return scalar(vtmp, ctmp, op, 0, solver);
}
public static Constraint sum(IntVar[] vars, IntLinComb.Operator op,
IntVar v, int c, Solver solver) {
int[] coeffs = new int[vars.length];
Arrays.fill(coeffs, 1);
return scalar(vars, coeffs, op, v, c, solver);
}
public static Constraint sum(IntVar[] vars, IntLinComb.Operator op,
int c, Solver solver) {
int[] coeffs = new int[vars.length];
Arrays.fill(coeffs, 1);
return scalar(vars, coeffs, op, c, solver);
}
}
| true | true |
public static Constraint scalar(IntVar[] vars, int[] coeffs, IntLinComb.Operator op,
int c, Solver solver) {
TObjectIntHashMap<IntVar> map = new TObjectIntHashMap<IntVar>();
for (int i = 0; i < vars.length; i++) {
map.adjustOrPutValue(vars[i], coeffs[i], coeffs[i]);
if (map.get(vars[i]) == 0) {
map.remove(vars[i]);
}
}
IntVar[] nvars = map.keys(new IntVar[map.size()]);
int b = 0, e = map.size();
IntVar[] tmpV = new IntVar[e];
int[] tmpC = new int[e];
// iteration over the paramater array to avoid non-deterministic behavior introduced by the map
for (int i = 0; i < vars.length; i++) {
IntVar var = vars[i];
if (map.contains(vars[i])) {
int coeff = map.get(var);
if (coeff > 0) {
tmpV[b] = var;
tmpC[b++] = coeff;
} else if (coeff < 0) {
tmpV[--e] = var;
tmpC[e] = coeff;
}
}
}
return new IntLinComb(tmpV, tmpC, b, op, -c, solver);
}
|
public static Constraint scalar(IntVar[] vars, int[] coeffs, IntLinComb.Operator op,
int c, Solver solver) {
TObjectIntHashMap<IntVar> map = new TObjectIntHashMap<IntVar>();
for (int i = 0; i < vars.length; i++) {
map.adjustOrPutValue(vars[i], coeffs[i], coeffs[i]);
if (map.get(vars[i]) == 0) {
map.remove(vars[i]);
}
}
IntVar[] nvars = map.keys(new IntVar[map.size()]);
int b = 0, e = map.size();
IntVar[] tmpV = new IntVar[e];
int[] tmpC = new int[e];
// iteration over the paramater array to avoid non-deterministic behavior introduced by the map
for (int i = 0; i < nvars.length; i++) {
IntVar var = nvars[i];
if (map.contains(var)) {
int coeff = map.get(var);
if (coeff > 0) {
tmpV[b] = var;
tmpC[b++] = coeff;
} else if (coeff < 0) {
tmpV[--e] = var;
tmpC[e] = coeff;
}
}
}
return new IntLinComb(tmpV, tmpC, b, op, -c, solver);
}
|
diff --git a/scrplugin/src/main/java/org/apache/felix/scrplugin/tags/cl/ClassLoaderJavaClassDescription.java b/scrplugin/src/main/java/org/apache/felix/scrplugin/tags/cl/ClassLoaderJavaClassDescription.java
index 0bd8d7220..d3a301795 100644
--- a/scrplugin/src/main/java/org/apache/felix/scrplugin/tags/cl/ClassLoaderJavaClassDescription.java
+++ b/scrplugin/src/main/java/org/apache/felix/scrplugin/tags/cl/ClassLoaderJavaClassDescription.java
@@ -1,275 +1,275 @@
/*
* 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.felix.scrplugin.tags.cl;
import java.lang.reflect.*;
import java.util.*;
import org.apache.felix.scrplugin.Constants;
import org.apache.felix.scrplugin.om.*;
import org.apache.felix.scrplugin.tags.*;
import org.apache.maven.plugin.MojoExecutionException;
/**
* <code>ClassLoaderJavaClassDescription.java</code>...
*
*/
public class ClassLoaderJavaClassDescription implements JavaClassDescription {
protected static final JavaTag[] EMPTY_TAGS = new JavaTag[0];
protected final Class clazz;
protected final JavaClassDescriptorManager manager;
protected final Component component;
public ClassLoaderJavaClassDescription(Class c, Component comp, JavaClassDescriptorManager m) {
this.clazz = c;
this.manager = m;
this.component = comp;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getFields()
*/
public JavaField[] getFields() {
final Field[] fields = this.clazz.getFields();
final JavaField[] javaFields = new JavaField[fields.length];
for (int i=0; i < fields.length; i++ ) {
javaFields[i] = new ClassLoaderJavaField(fields[i], this);
}
return javaFields;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getFieldByName(java.lang.String)
*/
public JavaField getFieldByName(String name) throws MojoExecutionException {
Field field = null;
try {
field = this.clazz.getField(name);
} catch (SecurityException e) {
// ignore
} catch (NoSuchFieldException e) {
// ignore
}
if ( field != null ) {
return new ClassLoaderJavaField(field, this);
}
if ( this.getSuperClass() != null ) {
this.getSuperClass().getFieldByName(name);
}
return null;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getExternalFieldByName(java.lang.String)
*/
public JavaField getExternalFieldByName(String name)
throws MojoExecutionException {
throw new MojoExecutionException("getExternalFieldByName not support for this class.");
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getReferencedClass(java.lang.String)
*/
public JavaClassDescription getReferencedClass(String referencedName)
throws MojoExecutionException {
throw new MojoExecutionException("getDescription not support for this class.");
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getImplementedInterfaces()
*/
public JavaClassDescription[] getImplementedInterfaces() throws MojoExecutionException {
Class[] implemented = clazz.getInterfaces();
if (implemented.length == 0) {
return JavaClassDescription.EMPTY_RESULT;
}
JavaClassDescription[] jcd = new JavaClassDescription[implemented.length];
for (int i=0; i < jcd.length; i++) {
jcd[i] = manager.getJavaClassDescription(implemented[i].getName());
}
return jcd;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getMethodBySignature(java.lang.String, java.lang.String[])
*/
public JavaMethod getMethodBySignature(String name, String[] parameters)
throws MojoExecutionException {
Class[] classParameters = null;
if ( parameters != null ) {
classParameters = new Class[parameters.length];
for(int i=0; i<parameters.length; i++) {
try {
classParameters[i] = this.manager.getClassLoader().loadClass(parameters[i]);
} catch (ClassNotFoundException cnfe) {
return null;
}
}
}
Method m = null;
try {
m = this.clazz.getDeclaredMethod(name, classParameters);
} catch (NoClassDefFoundError ncdfe) {
// if this occurs it usually means that a problem with the maven
// scopes exists.
throw new MojoExecutionException("Class loading error. This error usually occurs if you have a " +
"service inheriting from a class coming from another bundle and that class using a " +
"third library and all dependencies are specified with scope 'provided'.", ncdfe);
} catch (NoSuchMethodException e) {
// ignore this
}
if ( m != null ) {
return new ClassLoaderJavaMethod(m);
}
// try super class
if ( this.getSuperClass() != null ) {
return this.getSuperClass().getMethodBySignature(name, parameters);
}
return null;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getMethods()
*/
public JavaMethod[] getMethods() {
return JavaMethod.EMPTY_RESULT;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getName()
*/
public String getName() {
return this.clazz.getName();
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getSuperClass()
*/
public JavaClassDescription getSuperClass() throws MojoExecutionException {
if ( this.clazz.getSuperclass() != null ) {
return this.manager.getJavaClassDescription(this.clazz.getSuperclass().getName());
}
return null;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getTagByName(java.lang.String)
*/
public JavaTag getTagByName(String name) {
// this is only used to retrieve the component tag, so we can ignore it
// for classes from other bundles and simply return null
return null;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#getTagsByName(java.lang.String, boolean)
*/
public JavaTag[] getTagsByName(String name, boolean inherited)
throws MojoExecutionException {
JavaTag[] javaTags = EMPTY_TAGS;
if ( this.component != null ) {
if ( Constants.SERVICE.equals(name) ) {
if ( this.component.getService() != null &&
this.component.getService().getInterfaces().size() > 0 ) {
javaTags = new JavaTag[this.component.getService().getInterfaces().size()];
for(int i=0; i<this.component.getService().getInterfaces().size(); i++) {
- javaTags[i] = new ClassLoaderJavaTag(this, (Interface)this.component.getProperties().get(i),
+ javaTags[i] = new ClassLoaderJavaTag(this, (Interface)this.component.getService().getInterfaces().get(i),
this.component.getService().isServicefactory());
}
}
} else if ( Constants.PROPERTY.equals(name) ) {
if ( this.component.getProperties().size() > 0 ) {
javaTags = new JavaTag[this.component.getProperties().size()];
for(int i=0; i<this.component.getProperties().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Property)this.component.getProperties().get(i));
}
}
} else if ( Constants.REFERENCE.equals(name) ) {
if ( this.component.getReferences().size() > 0 ) {
javaTags = new JavaTag[this.component.getReferences().size()];
for(int i=0; i<this.component.getReferences().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Reference)this.component.getReferences().get(i));
}
}
}
}
if ( inherited && this.getSuperClass() != null ) {
final JavaTag[] superTags = this.getSuperClass().getTagsByName(name, inherited);
if ( superTags.length > 0 ) {
final List list = new ArrayList(Arrays.asList(javaTags));
list.addAll(Arrays.asList(superTags));
javaTags = (JavaTag[]) list.toArray(new JavaTag[list.size()]);
}
}
return javaTags;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#isA(java.lang.String)
*/
public boolean isA(String type) {
if ( this.clazz.getName().equals(type) ) {
return true;
}
return this.testClass(this.clazz, type);
}
protected boolean testClass(Class c, String type) {
final Class[] interfaces = c.getInterfaces();
for(int i=0; i<interfaces.length; i++) {
if ( interfaces[i].getName().equals(type) ) {
return true;
}
if ( this.testClass(interfaces[i], type) ) {
return true;
}
}
return false;
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#isAbstract()
*/
public boolean isAbstract() {
return Modifier.isAbstract(this.clazz.getModifiers());
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#isInterface()
*/
public boolean isInterface() {
return Modifier.isInterface(this.clazz.getModifiers());
}
/**
* @see org.apache.felix.scrplugin.tags.JavaClassDescription#isPublic()
*/
public boolean isPublic() {
return Modifier.isPublic(this.clazz.getModifiers());
}
public String toString() {
return getName();
}
}
| true | true |
public JavaTag[] getTagsByName(String name, boolean inherited)
throws MojoExecutionException {
JavaTag[] javaTags = EMPTY_TAGS;
if ( this.component != null ) {
if ( Constants.SERVICE.equals(name) ) {
if ( this.component.getService() != null &&
this.component.getService().getInterfaces().size() > 0 ) {
javaTags = new JavaTag[this.component.getService().getInterfaces().size()];
for(int i=0; i<this.component.getService().getInterfaces().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Interface)this.component.getProperties().get(i),
this.component.getService().isServicefactory());
}
}
} else if ( Constants.PROPERTY.equals(name) ) {
if ( this.component.getProperties().size() > 0 ) {
javaTags = new JavaTag[this.component.getProperties().size()];
for(int i=0; i<this.component.getProperties().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Property)this.component.getProperties().get(i));
}
}
} else if ( Constants.REFERENCE.equals(name) ) {
if ( this.component.getReferences().size() > 0 ) {
javaTags = new JavaTag[this.component.getReferences().size()];
for(int i=0; i<this.component.getReferences().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Reference)this.component.getReferences().get(i));
}
}
}
}
if ( inherited && this.getSuperClass() != null ) {
final JavaTag[] superTags = this.getSuperClass().getTagsByName(name, inherited);
if ( superTags.length > 0 ) {
final List list = new ArrayList(Arrays.asList(javaTags));
list.addAll(Arrays.asList(superTags));
javaTags = (JavaTag[]) list.toArray(new JavaTag[list.size()]);
}
}
return javaTags;
}
|
public JavaTag[] getTagsByName(String name, boolean inherited)
throws MojoExecutionException {
JavaTag[] javaTags = EMPTY_TAGS;
if ( this.component != null ) {
if ( Constants.SERVICE.equals(name) ) {
if ( this.component.getService() != null &&
this.component.getService().getInterfaces().size() > 0 ) {
javaTags = new JavaTag[this.component.getService().getInterfaces().size()];
for(int i=0; i<this.component.getService().getInterfaces().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Interface)this.component.getService().getInterfaces().get(i),
this.component.getService().isServicefactory());
}
}
} else if ( Constants.PROPERTY.equals(name) ) {
if ( this.component.getProperties().size() > 0 ) {
javaTags = new JavaTag[this.component.getProperties().size()];
for(int i=0; i<this.component.getProperties().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Property)this.component.getProperties().get(i));
}
}
} else if ( Constants.REFERENCE.equals(name) ) {
if ( this.component.getReferences().size() > 0 ) {
javaTags = new JavaTag[this.component.getReferences().size()];
for(int i=0; i<this.component.getReferences().size(); i++) {
javaTags[i] = new ClassLoaderJavaTag(this, (Reference)this.component.getReferences().get(i));
}
}
}
}
if ( inherited && this.getSuperClass() != null ) {
final JavaTag[] superTags = this.getSuperClass().getTagsByName(name, inherited);
if ( superTags.length > 0 ) {
final List list = new ArrayList(Arrays.asList(javaTags));
list.addAll(Arrays.asList(superTags));
javaTags = (JavaTag[]) list.toArray(new JavaTag[list.size()]);
}
}
return javaTags;
}
|
diff --git a/proxy/src/main/java/org/candlepin/guice/JPAInitializer.java b/proxy/src/main/java/org/candlepin/guice/JPAInitializer.java
index d23c7343b..082c23cc9 100644
--- a/proxy/src/main/java/org/candlepin/guice/JPAInitializer.java
+++ b/proxy/src/main/java/org/candlepin/guice/JPAInitializer.java
@@ -1,32 +1,32 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.guice;
import com.google.inject.Inject;
import com.wideplay.warp.persist.PersistenceService;
/**
* Initializes the JPA service
*/
public class JPAInitializer {
/**
* Initializes the JPA service.
* @param service to be initialized.
*/
@Inject
protected JPAInitializer(PersistenceService service) {
- //service.start();
+ service.start();
}
}
| true | true |
protected JPAInitializer(PersistenceService service) {
//service.start();
}
|
protected JPAInitializer(PersistenceService service) {
service.start();
}
|
diff --git a/src/greedGame/model/player/CowardAIPlayer.java b/src/greedGame/model/player/CowardAIPlayer.java
index 1793cc1..65db4b9 100644
--- a/src/greedGame/model/player/CowardAIPlayer.java
+++ b/src/greedGame/model/player/CowardAIPlayer.java
@@ -1,35 +1,35 @@
package greedGame.model.player;
import java.util.List;
import greedGame.model.Dice;
import greedGame.model.GreedGameModel;
import greedGame.model.ScoringCombination;
import greedGame.model.ScoringRules;
public class CowardAIPlayer extends AIPlayer {
public CowardAIPlayer(String name, GreedGameModel model) {
super(name, model);
}
- public void Decide()
+ public void decide()
{
rollDice();
List<Dice> diceList = getUnreservedDice();
ScoringRules rules = getScoringRules();
List<ScoringCombination> combinations = rules.getScoringCombinations(diceList);
for(ScoringCombination forCombo : combinations)
{
if(forCombo.getScore() > 0)
{
for(Dice forDice : diceList)
{
selectDice(forDice);
}
}
}
bank();
}
}
| true | true |
public void Decide()
{
rollDice();
List<Dice> diceList = getUnreservedDice();
ScoringRules rules = getScoringRules();
List<ScoringCombination> combinations = rules.getScoringCombinations(diceList);
for(ScoringCombination forCombo : combinations)
{
if(forCombo.getScore() > 0)
{
for(Dice forDice : diceList)
{
selectDice(forDice);
}
}
}
bank();
}
|
public void decide()
{
rollDice();
List<Dice> diceList = getUnreservedDice();
ScoringRules rules = getScoringRules();
List<ScoringCombination> combinations = rules.getScoringCombinations(diceList);
for(ScoringCombination forCombo : combinations)
{
if(forCombo.getScore() > 0)
{
for(Dice forDice : diceList)
{
selectDice(forDice);
}
}
}
bank();
}
|
diff --git a/src/swarm/client/view/cell/VisualCellHighlight.java b/src/swarm/client/view/cell/VisualCellHighlight.java
index 5fa4aa1..55a358a 100644
--- a/src/swarm/client/view/cell/VisualCellHighlight.java
+++ b/src/swarm/client/view/cell/VisualCellHighlight.java
@@ -1,181 +1,182 @@
package swarm.client.view.cell;
import swarm.client.app.AppContext;
import swarm.client.entities.BufferCell;
import swarm.client.entities.Camera;
import swarm.client.managers.CellBuffer;
import swarm.client.managers.CellBufferManager;
import swarm.client.navigation.MouseNavigator;
import swarm.client.input.Mouse;
import swarm.client.states.camera.Action_Camera_SetViewSize;
import swarm.client.states.camera.Action_Camera_SnapToPoint;
import swarm.client.states.camera.StateMachine_Camera;
import swarm.client.states.camera.State_ViewingCell;
import swarm.client.view.E_ZIndex;
import swarm.client.view.I_UIElement;
import swarm.client.view.S_UI;
import swarm.client.view.U_Css;
import swarm.client.view.ViewConfig;
import swarm.client.view.ViewContext;
import swarm.shared.app.S_CommonApp;
import swarm.shared.debugging.U_Debug;
import swarm.shared.utils.U_Math;
import swarm.shared.statemachine.A_Action;
import swarm.shared.statemachine.StateEvent;
import swarm.shared.structs.GridCoordinate;
import swarm.shared.structs.Point;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
public class VisualCellHighlight extends FlowPanel implements I_UIElement
{
private final Point m_utilPoint1 = new Point();
private double m_lastScaling = -1;
private final ViewContext m_viewContext;
public VisualCellHighlight(ViewContext viewContext)
{
m_viewContext = viewContext;
this.addStyleName("cell_highlight");
this.getElement().setAttribute("ondragstart", "return false;");
E_ZIndex.CELL_HIGHLIGHT.assignTo(this);
this.setVisible(false);
}
private void update()
{
MouseNavigator navManager = m_viewContext.mouseNavigator;
boolean isMouseTouchingSnappableCell = navManager.isMouseTouchingSnappableCell();
//--- DRK > TODO: Really minor so might never fix, but this is kinda sloppy.
//--- There should probably be a "panning" state or something that the highlight listens for instead.
Mouse mouse = navManager.getMouse();
boolean isPanning = mouse.isMouseDown() && mouse.hasMouseStrayedWhileDown();
if( isPanning )
{
this.setVisible(false);
return;
}
CellBuffer buffer = m_viewContext.appContext.cellBufferMngr.getDisplayBuffer();
int subCellDim = buffer.getSubCellCount();
Camera camera = m_viewContext.appContext.cameraMngr.getCamera();
Point basePoint = null;
double highlightScaling = camera.calcDistanceRatio();
GridCoordinate mouseCoord = navManager.getMouseGridCoord();
BufferCell cell = buffer.getCellAtAbsoluteCoord(mouseCoord);
if( cell == null )
{
this.setVisible(false);
return;
}
basePoint = m_utilPoint1;
//--- DRK > For this case, we have to do all kinds of evil witch hackery to ensure that cell highlight lines up
//--- visually with individual cells in the meta cell images...this technically creates some disagreement
//--- between the highlight and the actual mouse coordinate position for near-cell-boundary cases, but it's zoomed
//--- out enough that it doesn't really matter...you'd really have to look for it to notice a discrepancy.
VisualCellManager cellManager = m_viewContext.cellMngr;
double lastScaling = cellManager.getLastScaling();
Point lastBasePoint = cellManager.getLastBasePoint();
int bufferM = buffer.getCoordinate().getM() * subCellDim;
int bufferN = buffer.getCoordinate().getN() * subCellDim;
int deltaM = mouseCoord.getM() - bufferM;
int deltaN = mouseCoord.getN() - bufferN;
//TODO: Assuming square cell size.
double apparentCellPixels = 0;
if( buffer.getSubCellCount() > 1 )
{
apparentCellPixels = ((cell.getGrid().getCellWidth() / ((double) subCellDim)) * lastScaling);
}
else
{
apparentCellPixels = (cell.getGrid().getCellWidth() + cell.getGrid().getCellPadding()) * lastScaling;
}
double deltaPixelsX = apparentCellPixels * deltaM;
double deltaPixelsY = apparentCellPixels * deltaN;
basePoint.copy(lastBasePoint);
basePoint.inc(deltaPixelsX, deltaPixelsY, 0);
double y = basePoint.getY();
if( m_viewContext.stateContext.isEntered(State_ViewingCell.class) )
{
Element scrollElement = this.getParent().getParent().getElement();
y += scrollElement.getScrollTop();
}
- String size = (cell.getGrid().getCellWidth() * highlightScaling) + "px";
- this.setSize(size, size);
+ String width = (cell.getGrid().getCellWidth() * highlightScaling) + "px";
+ String height = (cell.getGrid().getCellHeight() * highlightScaling) + "px";
+ this.setSize(width, height);
this.getElement().getStyle().setProperty("top", y + "px");
this.getElement().getStyle().setProperty("left", basePoint.getX() + "px");
ViewConfig viewConfig = m_viewContext.viewConfig;
if( m_lastScaling != highlightScaling )
{
double scale = Math.sqrt(highlightScaling);
int shadowSize = (int) (((double)viewConfig.cellHighlightMaxSize) * (scale));
shadowSize = (shadowSize < viewConfig.cellHighlightMinSize ? viewConfig.cellHighlightMinSize : shadowSize);
U_Css.setBoxShadow(this.getElement(), "0 0 "+(shadowSize/2)+"px "+(shadowSize/2)+"px " + m_viewContext.viewConfig.cellHighlightColor);
}
m_lastScaling = highlightScaling;
this.setVisible(true);
}
public void onStateEvent(StateEvent event)
{
switch(event.getType())
{
case DID_UPDATE:
{
if( event.getState().getParent() instanceof StateMachine_Camera )
{
this.update();
}
break;
}
case DID_PERFORM_ACTION:
{
if( event.getAction() == Action_Camera_SetViewSize.class ||
event.getAction() == Action_Camera_SnapToPoint.class )
{
State_ViewingCell state = event.getContext().getEnteredState(State_ViewingCell.class);
if( state != null )
{
this.update();
}
}
break;
}
}
}
}
| true | true |
private void update()
{
MouseNavigator navManager = m_viewContext.mouseNavigator;
boolean isMouseTouchingSnappableCell = navManager.isMouseTouchingSnappableCell();
//--- DRK > TODO: Really minor so might never fix, but this is kinda sloppy.
//--- There should probably be a "panning" state or something that the highlight listens for instead.
Mouse mouse = navManager.getMouse();
boolean isPanning = mouse.isMouseDown() && mouse.hasMouseStrayedWhileDown();
if( isPanning )
{
this.setVisible(false);
return;
}
CellBuffer buffer = m_viewContext.appContext.cellBufferMngr.getDisplayBuffer();
int subCellDim = buffer.getSubCellCount();
Camera camera = m_viewContext.appContext.cameraMngr.getCamera();
Point basePoint = null;
double highlightScaling = camera.calcDistanceRatio();
GridCoordinate mouseCoord = navManager.getMouseGridCoord();
BufferCell cell = buffer.getCellAtAbsoluteCoord(mouseCoord);
if( cell == null )
{
this.setVisible(false);
return;
}
basePoint = m_utilPoint1;
//--- DRK > For this case, we have to do all kinds of evil witch hackery to ensure that cell highlight lines up
//--- visually with individual cells in the meta cell images...this technically creates some disagreement
//--- between the highlight and the actual mouse coordinate position for near-cell-boundary cases, but it's zoomed
//--- out enough that it doesn't really matter...you'd really have to look for it to notice a discrepancy.
VisualCellManager cellManager = m_viewContext.cellMngr;
double lastScaling = cellManager.getLastScaling();
Point lastBasePoint = cellManager.getLastBasePoint();
int bufferM = buffer.getCoordinate().getM() * subCellDim;
int bufferN = buffer.getCoordinate().getN() * subCellDim;
int deltaM = mouseCoord.getM() - bufferM;
int deltaN = mouseCoord.getN() - bufferN;
//TODO: Assuming square cell size.
double apparentCellPixels = 0;
if( buffer.getSubCellCount() > 1 )
{
apparentCellPixels = ((cell.getGrid().getCellWidth() / ((double) subCellDim)) * lastScaling);
}
else
{
apparentCellPixels = (cell.getGrid().getCellWidth() + cell.getGrid().getCellPadding()) * lastScaling;
}
double deltaPixelsX = apparentCellPixels * deltaM;
double deltaPixelsY = apparentCellPixels * deltaN;
basePoint.copy(lastBasePoint);
basePoint.inc(deltaPixelsX, deltaPixelsY, 0);
double y = basePoint.getY();
if( m_viewContext.stateContext.isEntered(State_ViewingCell.class) )
{
Element scrollElement = this.getParent().getParent().getElement();
y += scrollElement.getScrollTop();
}
String size = (cell.getGrid().getCellWidth() * highlightScaling) + "px";
this.setSize(size, size);
this.getElement().getStyle().setProperty("top", y + "px");
this.getElement().getStyle().setProperty("left", basePoint.getX() + "px");
ViewConfig viewConfig = m_viewContext.viewConfig;
if( m_lastScaling != highlightScaling )
{
double scale = Math.sqrt(highlightScaling);
int shadowSize = (int) (((double)viewConfig.cellHighlightMaxSize) * (scale));
shadowSize = (shadowSize < viewConfig.cellHighlightMinSize ? viewConfig.cellHighlightMinSize : shadowSize);
U_Css.setBoxShadow(this.getElement(), "0 0 "+(shadowSize/2)+"px "+(shadowSize/2)+"px " + m_viewContext.viewConfig.cellHighlightColor);
}
m_lastScaling = highlightScaling;
this.setVisible(true);
}
|
private void update()
{
MouseNavigator navManager = m_viewContext.mouseNavigator;
boolean isMouseTouchingSnappableCell = navManager.isMouseTouchingSnappableCell();
//--- DRK > TODO: Really minor so might never fix, but this is kinda sloppy.
//--- There should probably be a "panning" state or something that the highlight listens for instead.
Mouse mouse = navManager.getMouse();
boolean isPanning = mouse.isMouseDown() && mouse.hasMouseStrayedWhileDown();
if( isPanning )
{
this.setVisible(false);
return;
}
CellBuffer buffer = m_viewContext.appContext.cellBufferMngr.getDisplayBuffer();
int subCellDim = buffer.getSubCellCount();
Camera camera = m_viewContext.appContext.cameraMngr.getCamera();
Point basePoint = null;
double highlightScaling = camera.calcDistanceRatio();
GridCoordinate mouseCoord = navManager.getMouseGridCoord();
BufferCell cell = buffer.getCellAtAbsoluteCoord(mouseCoord);
if( cell == null )
{
this.setVisible(false);
return;
}
basePoint = m_utilPoint1;
//--- DRK > For this case, we have to do all kinds of evil witch hackery to ensure that cell highlight lines up
//--- visually with individual cells in the meta cell images...this technically creates some disagreement
//--- between the highlight and the actual mouse coordinate position for near-cell-boundary cases, but it's zoomed
//--- out enough that it doesn't really matter...you'd really have to look for it to notice a discrepancy.
VisualCellManager cellManager = m_viewContext.cellMngr;
double lastScaling = cellManager.getLastScaling();
Point lastBasePoint = cellManager.getLastBasePoint();
int bufferM = buffer.getCoordinate().getM() * subCellDim;
int bufferN = buffer.getCoordinate().getN() * subCellDim;
int deltaM = mouseCoord.getM() - bufferM;
int deltaN = mouseCoord.getN() - bufferN;
//TODO: Assuming square cell size.
double apparentCellPixels = 0;
if( buffer.getSubCellCount() > 1 )
{
apparentCellPixels = ((cell.getGrid().getCellWidth() / ((double) subCellDim)) * lastScaling);
}
else
{
apparentCellPixels = (cell.getGrid().getCellWidth() + cell.getGrid().getCellPadding()) * lastScaling;
}
double deltaPixelsX = apparentCellPixels * deltaM;
double deltaPixelsY = apparentCellPixels * deltaN;
basePoint.copy(lastBasePoint);
basePoint.inc(deltaPixelsX, deltaPixelsY, 0);
double y = basePoint.getY();
if( m_viewContext.stateContext.isEntered(State_ViewingCell.class) )
{
Element scrollElement = this.getParent().getParent().getElement();
y += scrollElement.getScrollTop();
}
String width = (cell.getGrid().getCellWidth() * highlightScaling) + "px";
String height = (cell.getGrid().getCellHeight() * highlightScaling) + "px";
this.setSize(width, height);
this.getElement().getStyle().setProperty("top", y + "px");
this.getElement().getStyle().setProperty("left", basePoint.getX() + "px");
ViewConfig viewConfig = m_viewContext.viewConfig;
if( m_lastScaling != highlightScaling )
{
double scale = Math.sqrt(highlightScaling);
int shadowSize = (int) (((double)viewConfig.cellHighlightMaxSize) * (scale));
shadowSize = (shadowSize < viewConfig.cellHighlightMinSize ? viewConfig.cellHighlightMinSize : shadowSize);
U_Css.setBoxShadow(this.getElement(), "0 0 "+(shadowSize/2)+"px "+(shadowSize/2)+"px " + m_viewContext.viewConfig.cellHighlightColor);
}
m_lastScaling = highlightScaling;
this.setVisible(true);
}
|
diff --git a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
index 0311d04a..d8711076 100644
--- a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
+++ b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
@@ -1,151 +1,151 @@
/*
* This file is part of Vanilla.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.controller.object.moving;
import org.spout.api.entity.Entity;
import org.spout.api.entity.type.ControllerType;
import org.spout.api.entity.type.EmptyConstructorControllerType;
import org.spout.api.geo.cuboid.Block;
import org.spout.api.inventory.ItemStack;
import org.spout.api.material.Material;
import org.spout.api.math.Vector3;
import org.spout.api.player.Player;
import org.spout.vanilla.configuration.VanillaConfiguration;
import org.spout.vanilla.controller.VanillaControllerTypes;
import org.spout.vanilla.controller.living.player.VanillaPlayer;
import org.spout.vanilla.controller.object.Substance;
import org.spout.vanilla.material.VanillaMaterials;
import org.spout.vanilla.protocol.msg.CollectItemMessage;
import static org.spout.vanilla.protocol.VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers;
/**
* Controller that serves as the base for all items that are not in an inventory (dispersed in the world).
*/
public class Item extends Substance {
public static final ControllerType TYPE = new EmptyConstructorControllerType(Item.class, "Item");
private final int distance = (int) VanillaConfiguration.ITEM_PICKUP_RANGE.getDouble();
private final ItemStack is;
private int unpickable;
/**
* Creates an item controller. Intended for deserialization only.
*/
protected Item() {
this(new ItemStack(VanillaMaterials.AIR, 1), Vector3.ZERO);
}
/**
* Creates an item controller
* @param itemstack this item controller represents
* @param initial velocity that this item has
*/
public Item(ItemStack itemstack, Vector3 initial) {
super(VanillaControllerTypes.DROPPED_ITEM);
this.is = itemstack;
unpickable = 10;
setVelocity(initial);
}
@Override
public void onAttached() {
super.onAttached();
if (data().containsKey("Itemstack")) {
ItemStack item = (ItemStack) data().get("Itemstack");
is.setMaterial(item.getMaterial(), item.getData());
is.setAmount(item.getAmount());
is.setNBTData(item.getNBTData());
is.getAuxData().putAll(item.getAuxData());
}
unpickable = (Integer) data().get("unpickable", unpickable);
}
@Override
public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0));
if (!block.getMaterial().isPlacementObstacle()) {
Vector3 next = block.getPosition();
getParent().translate(block.getPosition().multiply(dt));
}
Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance);
if (closestPlayer == null) {
return;
}
Entity entity = closestPlayer.getEntity();
if (!(entity.getController() instanceof VanillaPlayer)) {
return;
}
int collected = getParent().getId();
int collector = entity.getId();
- sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collector, collected));
+ sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collected, collector));
((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true);
getParent().kill();
}
/**
* Gets what block the item is.
* @return block of item.
*/
public Material getMaterial() {
return is.getMaterial();
}
/**
* Gets the amount of the block there is in the ItemStack.
* @return amount of items
*/
public int getAmount() {
return is.getAmount();
}
/**
* Gets the data of the item
* @return item data
*/
public short getData() {
return is.getData();
}
@Override
public void onSave() {
super.onSave();
data().put("Itemstack", is);
data().put("unpickable", unpickable);
}
}
| true | true |
public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0));
if (!block.getMaterial().isPlacementObstacle()) {
Vector3 next = block.getPosition();
getParent().translate(block.getPosition().multiply(dt));
}
Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance);
if (closestPlayer == null) {
return;
}
Entity entity = closestPlayer.getEntity();
if (!(entity.getController() instanceof VanillaPlayer)) {
return;
}
int collected = getParent().getId();
int collector = entity.getId();
sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collector, collected));
((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true);
getParent().kill();
}
|
public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0));
if (!block.getMaterial().isPlacementObstacle()) {
Vector3 next = block.getPosition();
getParent().translate(block.getPosition().multiply(dt));
}
Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance);
if (closestPlayer == null) {
return;
}
Entity entity = closestPlayer.getEntity();
if (!(entity.getController() instanceof VanillaPlayer)) {
return;
}
int collected = getParent().getId();
int collector = entity.getId();
sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collected, collector));
((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true);
getParent().kill();
}
|
diff --git a/app/src/main/java/org/sensapp/android/sensappdroid/restservice/PutMeasuresTask.java b/app/src/main/java/org/sensapp/android/sensappdroid/restservice/PutMeasuresTask.java
index f5c4438..5d922d3 100644
--- a/app/src/main/java/org/sensapp/android/sensappdroid/restservice/PutMeasuresTask.java
+++ b/app/src/main/java/org/sensapp/android/sensappdroid/restservice/PutMeasuresTask.java
@@ -1,168 +1,168 @@
package org.sensapp.android.sensappdroid.restservice;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.sensapp.android.sensappdroid.contentprovider.SensAppCPContract;
import org.sensapp.android.sensappdroid.datarequests.DatabaseRequest;
import org.sensapp.android.sensappdroid.json.JsonPrinter;
import org.sensapp.android.sensappdroid.json.MeasureJsonModel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class PutMeasuresTask extends AsyncTask<Void, Integer, Integer> {
private static final String TAG = PutMeasuresTask.class.getSimpleName();
private Context context;
private Uri uri;
public PutMeasuresTask(Context context, Uri uri) {
super();
this.context = context;
this.uri = uri;
}
private String getUnit(String sensorName) {
String[] projection = {SensAppCPContract.Sensor.UNIT};
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Sensor.CONTENT_URI + "/" + sensorName), projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String unit = cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Sensor.UNIT));
cursor.close();
return unit;
}
return null;
}
private Uri getUri(String sensorName) {
String[] projection = {SensAppCPContract.Sensor.URI};
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Sensor.CONTENT_URI + "/" + sensorName), projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String uri = cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Sensor.URI));
cursor.close();
return Uri.parse(uri);
}
return null;
}
private boolean isSensorUploaded(String sensorName) {
String[] projection = {SensAppCPContract.Sensor.NAME};
String selection = SensAppCPContract.Sensor.UPLOADED + " = 1";
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Sensor.CONTENT_URI + "/" + sensorName), projection, selection, null, null);
if (cursor != null) {
boolean uploaded = cursor.getCount() > 0;
cursor.close();
return uploaded;
}
return false;
}
private List<Long> getBasetimes(String sensorName) {
List<Long> basetimes = new ArrayList<Long>();
String[] projection = {"DISTINCT " + SensAppCPContract.Measure.BASETIME};
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + sensorName), projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
basetimes.add(cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.BASETIME)));
}
cursor.close();
}
return basetimes;
}
private List<Integer> fillMeasureJsonModel(MeasureJsonModel model) {
List<Integer> ids = new ArrayList<Integer>();
String[] projection = {SensAppCPContract.Measure.ID, SensAppCPContract.Measure.VALUE, SensAppCPContract.Measure.TIME};
String selection = SensAppCPContract.Measure.BASETIME + " = " + model.getBt() + " AND " + SensAppCPContract.Measure.UPLOADED + " = 0";
Cursor cursor = context.getContentResolver().query(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + model.getBn()), projection, selection, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
ids.add(cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.ID)));
int value = cursor.getInt(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.VALUE));
long time = cursor.getLong(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.TIME));
model.appendMeasure(value, time);
}
cursor.close();
}
return ids;
}
@Override
protected Integer doInBackground(Void... params) {
int rowsUploaded = 0;
ArrayList<String> sensorNames = new ArrayList<String>();
Cursor cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
for (String sensorName : sensorNames) {
if (!isSensorUploaded(sensorName)) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context).executeOnExecutor(THREAD_POOL_EXECUTOR, sensorName).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Sensor.UPLOADED, 1);
DatabaseRequest.SensorRQ.updateSensor(context, sensorName, values);
}
Uri uri = getUri(sensorName);
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
MeasureJsonModel model = new MeasureJsonModel(sensorName, basetime, getUnit(sensorName));
- ids = fillMeasureJsonModel(model);
+ ids.addAll(fillMeasureJsonModel(model));
if (ids.size() > 0) {
try {
RestRequest.putData(uri, JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
}
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Measure.UPLOADED, 1);
String selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
rowsUploaded += context.getContentResolver().update(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + sensorName), values, selection, null);
}
return rowsUploaded;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == null) {
Log.e(TAG, "Put data error");
Toast.makeText(context, "Upload failed", Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, "Put data succed: " + result + " measures uploaded");
Toast.makeText(context, "Upload succeed", Toast.LENGTH_LONG).show();
}
}
}
| true | true |
protected Integer doInBackground(Void... params) {
int rowsUploaded = 0;
ArrayList<String> sensorNames = new ArrayList<String>();
Cursor cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
for (String sensorName : sensorNames) {
if (!isSensorUploaded(sensorName)) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context).executeOnExecutor(THREAD_POOL_EXECUTOR, sensorName).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Sensor.UPLOADED, 1);
DatabaseRequest.SensorRQ.updateSensor(context, sensorName, values);
}
Uri uri = getUri(sensorName);
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
MeasureJsonModel model = new MeasureJsonModel(sensorName, basetime, getUnit(sensorName));
ids = fillMeasureJsonModel(model);
if (ids.size() > 0) {
try {
RestRequest.putData(uri, JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
}
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Measure.UPLOADED, 1);
String selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
rowsUploaded += context.getContentResolver().update(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + sensorName), values, selection, null);
}
return rowsUploaded;
}
|
protected Integer doInBackground(Void... params) {
int rowsUploaded = 0;
ArrayList<String> sensorNames = new ArrayList<String>();
Cursor cursor = context.getContentResolver().query(uri, new String[]{"DISTINCT " + SensAppCPContract.Measure.SENSOR}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
sensorNames.add(cursor.getString(cursor.getColumnIndexOrThrow(SensAppCPContract.Measure.SENSOR)));
}
cursor.close();
}
for (String sensorName : sensorNames) {
if (!isSensorUploaded(sensorName)) {
Uri postSensorResult = null;
try {
postSensorResult = new PostSensorRestTask(context).executeOnExecutor(THREAD_POOL_EXECUTOR, sensorName).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (postSensorResult == null) {
Log.e(TAG, "Post sensor failed");
return null;
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Sensor.UPLOADED, 1);
DatabaseRequest.SensorRQ.updateSensor(context, sensorName, values);
}
Uri uri = getUri(sensorName);
List<Integer> ids = new ArrayList<Integer>();
for (Long basetime : getBasetimes(sensorName)) {
MeasureJsonModel model = new MeasureJsonModel(sensorName, basetime, getUnit(sensorName));
ids.addAll(fillMeasureJsonModel(model));
if (ids.size() > 0) {
try {
RestRequest.putData(uri, JsonPrinter.measuresToJson(model));
} catch (RequestErrorException e) {
Log.e(TAG, e.getMessage());
if (e.getCause() != null) {
Log.e(TAG, e.getCause().getMessage());
}
return null;
}
}
}
ContentValues values = new ContentValues();
values.put(SensAppCPContract.Measure.UPLOADED, 1);
String selection = SensAppCPContract.Measure.ID + " IN " + ids.toString().replace('[', '(').replace(']', ')');
rowsUploaded += context.getContentResolver().update(Uri.parse(SensAppCPContract.Measure.CONTENT_URI + "/" + sensorName), values, selection, null);
}
return rowsUploaded;
}
|
diff --git a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java
index 2f733fa9..ae5583d7 100644
--- a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java
+++ b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java
@@ -1,1039 +1,1049 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Eclipse Public License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.eclipse.org/org/documents/epl-v10.php
*
* 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.ide.eclipse.adt.internal.build;
import com.android.ide.eclipse.adt.AdtConstants;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.AndroidConstants;
import com.android.ide.eclipse.adt.internal.project.AndroidManifestParser;
import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
import com.android.ide.eclipse.adt.internal.project.FixLaunchConfig;
import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.BasicXmlErrorListener;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.xml.ManifestConstants;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
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.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Pre Java Compiler.
* This incremental builder performs 2 tasks:
* <ul>
* <li>compiles the resources located in the res/ folder, along with the
* AndroidManifest.xml file into the R.java class.</li>
* <li>compiles any .aidl files into a corresponding java file.</li>
* </ul>
*
*/
public class PreCompilerBuilder extends BaseBuilder {
public static final String ID = "com.android.ide.eclipse.adt.PreCompilerBuilder"; //$NON-NLS-1$
private static final String PROPERTY_PACKAGE = "manifestPackage"; //$NON-NLS-1$
private static final String PROPERTY_COMPILE_RESOURCES = "compileResources"; //$NON-NLS-1$
private static final String PROPERTY_COMPILE_AIDL = "compileAidl"; //$NON-NLS-1$
/**
* Single line aidl error<br>
* "<path>:<line>: <error>"
* or
* "<path>:<line> <error>"
*/
private static Pattern sAidlPattern1 = Pattern.compile("^(.+?):(\\d+):?\\s(.+)$"); //$NON-NLS-1$
/**
* Data to temporarly store aidl source file information
*/
static class AidlData {
IFile aidlFile;
IFolder sourceFolder;
AidlData(IFolder sourceFolder, IFile aidlFile) {
this.sourceFolder = sourceFolder;
this.aidlFile = aidlFile;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof AidlData) {
AidlData file = (AidlData)obj;
return aidlFile.equals(file.aidlFile) && sourceFolder.equals(file.sourceFolder);
}
return false;
}
}
/**
* Resource Compile flag. This flag is reset to false after each successful compilation, and
* stored in the project persistent properties. This allows the builder to remember its state
* when the project is closed/opened.
*/
private boolean mMustCompileResources = false;
/** List of .aidl files found that are modified or new. */
private final ArrayList<AidlData> mAidlToCompile = new ArrayList<AidlData>();
/** List of .aidl files that have been removed. */
private final ArrayList<AidlData> mAidlToRemove = new ArrayList<AidlData>();
/** cache of the java package defined in the manifest */
private String mManifestPackage;
/** Output folder for generated Java File. Created on the Builder init
* @see #startupOnInitialize()
*/
private IFolder mGenFolder;
/**
* Progress monitor used at the end of every build to refresh the content of the 'gen' folder
* and set the generated files as derived.
*/
private DerivedProgressMonitor mDerivedProgressMonitor;
/**
* Progress monitor waiting the end of the process to set a persistent value
* in a file. This is typically used in conjunction with <code>IResource.refresh()</code>,
* since this call is asysnchronous, and we need to wait for it to finish for the file
* to be known by eclipse, before we can call <code>resource.setPersistentProperty</code> on
* a new file.
*/
private static class DerivedProgressMonitor implements IProgressMonitor {
private boolean mCancelled = false;
private final ArrayList<IFile> mFileList = new ArrayList<IFile>();
private boolean mDone = false;
public DerivedProgressMonitor() {
}
void addFile(IFile file) {
mFileList.add(file);
}
void reset() {
mFileList.clear();
mDone = false;
}
public void beginTask(String name, int totalWork) {
}
public void done() {
if (mDone == false) {
mDone = true;
for (IFile file : mFileList) {
if (file.exists()) {
try {
file.setDerived(true);
} catch (CoreException e) {
// This really shouldn't happen since we check that the resource exist.
// Worst case scenario, the resource isn't marked as derived.
}
}
}
}
}
public void internalWorked(double work) {
}
public boolean isCanceled() {
return mCancelled;
}
public void setCanceled(boolean value) {
mCancelled = value;
}
public void setTaskName(String name) {
}
public void subTask(String name) {
}
public void worked(int work) {
}
}
public PreCompilerBuilder() {
super();
}
// build() returns a list of project from which this project depends for future compilation.
@SuppressWarnings("unchecked")
@Override
protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
throws CoreException {
try {
mDerivedProgressMonitor.reset();
// First thing we do is go through the resource delta to not
// lose it if we have to abort the build for any reason.
// get the project objects
IProject project = getProject();
// Top level check to make sure the build can move forward.
abortOnBadSetup(project);
IJavaProject javaProject = JavaCore.create(project);
IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
// now we need to get the classpath list
ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(
javaProject);
PreCompilerDeltaVisitor dv = null;
String javaPackage = null;
String minSdkVersion = null;
if (kind == FULL_BUILD) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Full_Pre_Compiler);
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Inc_Pre_Compiler);
// Go through the resources and see if something changed.
// Even if the mCompileResources flag is true from a previously aborted
// build, we need to go through the Resource delta to get a possible
// list of aidl files to compile/remove.
IResourceDelta delta = getDelta(project);
if (delta == null) {
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList);
delta.accept(dv);
// record the state
mMustCompileResources |= dv.getCompileResources();
if (dv.getForceAidlCompile()) {
buildAidlCompilationList(project, sourceFolderPathList);
} else {
// handle aidl modification, and update mMustCompileAidl
mergeAidlFileModifications(dv.getAidlToCompile(),
dv.getAidlToRemove());
}
// get the java package from the visitor
javaPackage = dv.getManifestPackage();
minSdkVersion = dv.getMinSdkVersion();
}
}
// store the build status in the persistent storage
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources);
// if there was some XML errors, we just return w/o doing
// anything since we've put some markers in the files anyway.
if (dv != null && dv.mXmlError) {
AdtPlugin.printErrorToConsole(project, Messages.Xml_Error);
// This interrupts the build. The next builders will not run.
stopBuild(Messages.Xml_Error);
}
// get the manifest file
IFile manifest = AndroidManifestParser.getManifest(project);
if (manifest == null) {
String msg = String.format(Messages.s_File_Missing,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses manifest (which is now guaranteed
// to be null) will actually be executed or not.
}
// lets check the XML of the manifest first, if that hasn't been done by the
// resource delta visitor yet.
if (dv == null || dv.getCheckedManifestXml() == false) {
BasicXmlErrorListener errorListener = new BasicXmlErrorListener();
AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest,
errorListener);
if (errorListener.mHasXmlError == true) {
// there was an error in the manifest, its file has been marked,
// by the XmlErrorHandler.
// We return;
String msg = String.format(Messages.s_Contains_Xml_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// get the java package from the parser
javaPackage = parser.getPackage();
minSdkVersion = parser.getApiLevelRequirement();
}
if (minSdkVersion != null) {
int minSdkValue = -1;
try {
minSdkValue = Integer.parseInt(minSdkVersion);
} catch (NumberFormatException e) {
// it's ok, it means minSdkVersion contains a (hopefully) valid codename.
}
AndroidVersion projectVersion = projectTarget.getVersion();
if (minSdkValue != -1) {
String codename = projectVersion.getCodename();
if (codename != null) {
// integer minSdk when the target is a preview => fatal error
String msg = String.format(
- "Platform %1$s is a preview and requires appication manifests to set %2$s to '%3$s'",
- codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION,
- codename);
+ "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'",
+ codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (minSdkValue < projectVersion.getApiLevel()) {
// integer minSdk is not high enough for the target => warning
String msg = String.format(
"Manifest min SDK version (%1$s) is lower than project target API level (%2$d)",
minSdkVersion, projectVersion.getApiLevel());
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_WARNING);
}
} else {
// looks like the min sdk is a codename, check it matches the codename
// of the platform
String codename = projectVersion.getCodename();
if (codename == null) {
// platform is not a preview => fatal error
String msg = String.format(
"Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (codename.equals(minSdkVersion) == false) {
// platform and manifest codenames don't match => fatal error.
String msg = String.format(
"Value of manifest attribute '%1$s' does not match platform codename '%2$s'",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
}
}
+ } else if (projectTarget.getVersion().isPreview()) {
+ // else the minSdkVersion is not set but we are using a preview target.
+ // Display an error
+ String codename = projectTarget.getVersion().getCodename();
+ String msg = String.format(
+ "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'",
+ codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION);
+ AdtPlugin.printErrorToConsole(project, msg);
+ BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
+ IMarker.SEVERITY_ERROR);
+ stopBuild(msg);
}
if (javaPackage == null || javaPackage.length() == 0) {
// looks like the AndroidManifest file isn't valid.
String msg = String.format(Messages.s_Doesnt_Declare_Package_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses javaPackage (which is now guaranteed
// to be null) will actually be executed or not.
}
// at this point we have the java package. We need to make sure it's not a different
// package than the previous one that were built.
if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) {
// The manifest package has changed, the user may want to update
// the launch configuration
if (mManifestPackage != null) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Checking_Package_Change);
FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage,
javaPackage);
flc.start();
}
// now we delete the generated classes from their previous location
deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS,
mManifestPackage);
deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS,
mManifestPackage);
// record the new manifest package, and save it.
mManifestPackage = javaPackage;
saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage);
}
if (mMustCompileResources) {
// we need to figure out where to store the R class.
// get the parent folder for R.java and update mManifestPackageSourceFolder
IFolder packageFolder = getGenManifestPackageFolder(project);
// get the resource folder
IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES);
// get the file system path
IPath outputLocation = mGenFolder.getLocation();
IPath resLocation = resFolder.getLocation();
IPath manifestLocation = manifest == null ? null : manifest.getLocation();
// those locations have to exist for us to do something!
if (outputLocation != null && resLocation != null
&& manifestLocation != null) {
String osOutputPath = outputLocation.toOSString();
String osResPath = resLocation.toOSString();
String osManifestPath = manifestLocation.toOSString();
// remove the aapt markers
removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE);
removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Preparing_Generated_Files);
// since the R.java file may be already existing in read-only
// mode we need to make it readable so that aapt can overwrite
// it
IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS);
// do the same for the Manifest.java class
IFile manifestJavaFile = packageFolder.getFile(
AndroidConstants.FN_MANIFEST_CLASS);
// we actually need to delete the manifest.java as it may become empty and
// in this case aapt doesn't generate an empty one, but instead doesn't
// touch it.
manifestJavaFile.delete(true, null);
// launch aapt: create the command line
ArrayList<String> array = new ArrayList<String>();
array.add(projectTarget.getPath(IAndroidTarget.AAPT));
array.add("package"); //$NON-NLS-1$
array.add("-m"); //$NON-NLS-1$
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
array.add("-v"); //$NON-NLS-1$
}
array.add("-J"); //$NON-NLS-1$
array.add(osOutputPath);
array.add("-M"); //$NON-NLS-1$
array.add(osManifestPath);
array.add("-S"); //$NON-NLS-1$
array.add(osResPath);
array.add("-I"); //$NON-NLS-1$
array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR));
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
StringBuilder sb = new StringBuilder();
for (String c : array) {
sb.append(c);
sb.append(' ');
}
String cmd_line = sb.toString();
AdtPlugin.printToConsole(project, cmd_line);
}
// launch
int execError = 1;
try {
// launch the command line process
Process process = Runtime.getRuntime().exec(
array.toArray(new String[array.size()]));
// list to store each line of stderr
ArrayList<String> results = new ArrayList<String>();
// get the output and return code from the process
execError = grabProcessOutput(process, results);
// attempt to parse the error output
boolean parsingError = parseAaptOutput(results, project);
// if we couldn't parse the output we display it in the console.
if (parsingError) {
if (execError != 0) {
AdtPlugin.printErrorToConsole(project, results.toArray());
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL,
project, results.toArray());
}
}
if (execError != 0) {
// if the exec failed, and we couldn't parse the error output
// (and therefore not all files that should have been marked,
// were marked), we put a generic marker on the project and abort.
if (parsingError) {
markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors,
IMarker.SEVERITY_ERROR);
}
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.AAPT_Error);
// abort if exec failed.
// This interrupts the build. The next builders will not run.
stopBuild(Messages.AAPT_Error);
}
} catch (IOException e1) {
// something happen while executing the process,
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
} catch (InterruptedException e) {
// we got interrupted waiting for the process to end...
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// if the return code was OK, we refresh the folder that
// contains R.java to force a java recompile.
if (execError == 0) {
// now add the R.java/Manifest.java to the list of file to be marked
// as derived.
mDerivedProgressMonitor.addFile(rJavaFile);
mDerivedProgressMonitor.addFile(manifestJavaFile);
// build has been done. reset the state of the builder
mMustCompileResources = false;
// and store it
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES,
mMustCompileResources);
}
}
} else {
// nothing to do
}
// now handle the aidl stuff.
boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor);
if (aidlStatus == false && mMustCompileResources == false) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Nothing_To_Compile);
}
} finally {
// refresh the 'gen' source folder. Once this is done with the custom progress
// monitor to mark all new files as derived
mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
}
return null;
}
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
super.clean(monitor);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(),
Messages.Removing_Generated_Classes);
// remove all the derived resources from the 'gen' source folder.
removeDerivedResources(mGenFolder, monitor);
}
@Override
protected void startupOnInitialize() {
super.startupOnInitialize();
mDerivedProgressMonitor = new DerivedProgressMonitor();
IProject project = getProject();
// load the previous IFolder and java package.
mManifestPackage = loadProjectStringProperty(PROPERTY_PACKAGE);
// get the source folder in which all the Java files are created
mGenFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
// Load the current compile flags. We ask for true if not found to force a
// recompile.
mMustCompileResources = loadProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, true);
boolean mustCompileAidl = loadProjectBooleanProperty(PROPERTY_COMPILE_AIDL, true);
// if we stored that we have to compile some aidl, we build the list that will compile them
// all
if (mustCompileAidl) {
IJavaProject javaProject = JavaCore.create(project);
ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(
javaProject);
buildAidlCompilationList(project, sourceFolderPathList);
}
}
/**
* Delete the a generated java class associated with the specified java package.
* @param filename Name of the generated file to remove.
* @param javaPackage the old java package
*/
private void deleteObsoleteGeneratedClass(String filename, String javaPackage) {
if (javaPackage == null) {
return;
}
IPath packagePath = getJavaPackagePath(javaPackage);
IPath iPath = packagePath.append(filename);
// Find a matching resource object.
IResource javaFile = mGenFolder.findMember(iPath);
if (javaFile != null && javaFile.exists() && javaFile.getType() == IResource.FILE) {
try {
// delete
javaFile.delete(true, null);
// refresh parent
javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
} catch (CoreException e) {
// failed to delete it, the user will have to delete it manually.
String message = String.format(Messages.Delete_Obsolete_Error,
javaFile.getFullPath());
IProject project = getProject();
AdtPlugin.printErrorToConsole(project, message);
AdtPlugin.printErrorToConsole(project, e.getMessage());
}
}
}
/**
* Creates a relative {@link IPath} from a java package.
* @param javaPackageName the java package.
*/
private IPath getJavaPackagePath(String javaPackageName) {
// convert the java package into path
String[] segments = javaPackageName.split(AndroidConstants.RE_DOT);
StringBuilder path = new StringBuilder();
for (String s : segments) {
path.append(AndroidConstants.WS_SEP_CHAR);
path.append(s);
}
return new Path(path.toString());
}
/**
* Returns an {@link IFolder} (located inside the 'gen' source folder), that matches the
* package defined in the manifest. This {@link IFolder} may not actually exist
* (aapt will create it anyway).
* @param project The project.
* @return the {@link IFolder} that will contain the R class or null if the folder was not found.
* @throws CoreException
*/
private IFolder getGenManifestPackageFolder(IProject project)
throws CoreException {
// get the path for the package
IPath packagePath = getJavaPackagePath(mManifestPackage);
// get a folder for this path under the 'gen' source folder, and return it.
// This IFolder may not reference an actual existing folder.
return mGenFolder.getFolder(packagePath);
}
/**
* Compiles aidl files into java. This will also removes old java files
* created from aidl files that are now gone.
* @param projectTarget Target of the project
* @param sourceFolders the list of source folders, relative to the workspace.
* @param monitor the projess monitor
* @returns true if it did something
* @throws CoreException
*/
private boolean handleAidl(IAndroidTarget projectTarget, ArrayList<IPath> sourceFolders,
IProgressMonitor monitor) throws CoreException {
if (mAidlToCompile.size() == 0 && mAidlToRemove.size() == 0) {
return false;
}
// create the command line
String[] command = new String[4 + sourceFolders.size()];
int index = 0;
command[index++] = projectTarget.getPath(IAndroidTarget.AIDL);
command[index++] = "-p" + Sdk.getCurrent().getTarget(getProject()).getPath( //$NON-NLS-1$
IAndroidTarget.ANDROID_AIDL);
// since the path are relative to the workspace and not the project itself, we need
// the workspace root.
IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
for (IPath p : sourceFolders) {
IFolder f = wsRoot.getFolder(p);
command[index++] = "-I" + f.getLocation().toOSString(); //$NON-NLS-1$
}
// list of files that have failed compilation.
ArrayList<AidlData> stillNeedCompilation = new ArrayList<AidlData>();
// if an aidl file is being removed before we managed to compile it, it'll be in
// both list. We *need* to remove it from the compile list or it'll never go away.
for (AidlData aidlFile : mAidlToRemove) {
int pos = mAidlToCompile.indexOf(aidlFile);
if (pos != -1) {
mAidlToCompile.remove(pos);
}
}
// loop until we've compile them all
for (AidlData aidlData : mAidlToCompile) {
// Remove the AIDL error markers from the aidl file
removeMarkersFromFile(aidlData.aidlFile, AndroidConstants.MARKER_AIDL);
// get the path of the source file.
IPath sourcePath = aidlData.aidlFile.getLocation();
String osSourcePath = sourcePath.toOSString();
IFile javaFile = getGenDestinationFile(aidlData, true /*createFolders*/, monitor);
// finish to set the command line.
command[index] = osSourcePath;
command[index + 1] = javaFile.getLocation().toOSString();
// launch the process
if (execAidl(command, aidlData.aidlFile) == false) {
// aidl failed. File should be marked. We add the file to the list
// of file that will need compilation again.
stillNeedCompilation.add(aidlData);
// and we move on to the next one.
continue;
} else {
// make sure the file will be marked as derived once we refresh the 'gen' source
// folder.
mDerivedProgressMonitor.addFile(javaFile);
}
}
// change the list to only contains the file that have failed compilation
mAidlToCompile.clear();
mAidlToCompile.addAll(stillNeedCompilation);
// Remove the java files created from aidl files that have been removed.
for (AidlData aidlData : mAidlToRemove) {
IFile javaFile = getGenDestinationFile(aidlData, false /*createFolders*/, monitor);
if (javaFile.exists()) {
// This confirms the java file was generated by the builder,
// we can delete the aidlFile.
javaFile.delete(true, null);
// Refresh parent.
javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, monitor);
}
}
mAidlToRemove.clear();
// store the build state. If there are any files that failed to compile, we will
// force a full aidl compile on the next project open. (unless a full compilation succeed
// before the project is closed/re-opened.)
// TODO: Optimize by saving only the files that need compilation
saveProjectBooleanProperty(PROPERTY_COMPILE_AIDL , mAidlToCompile.size() > 0);
return true;
}
/**
* Returns the {@link IFile} handle to the destination file for a given aild source file
* ({@link AidlData}).
* @param aidlData the data for the aidl source file.
* @param createFolders whether or not the parent folder of the destination should be created
* if it does not exist.
* @param monitor the progress monitor
* @return the handle to the destination file.
* @throws CoreException
*/
private IFile getGenDestinationFile(AidlData aidlData, boolean createFolders,
IProgressMonitor monitor) throws CoreException {
// build the destination folder path.
// Use the path of the source file, except for the path leading to its source folder,
// and for the last segment which is the filename.
int segmentToSourceFolderCount = aidlData.sourceFolder.getFullPath().segmentCount();
IPath packagePath = aidlData.aidlFile.getFullPath().removeFirstSegments(
segmentToSourceFolderCount).removeLastSegments(1);
Path destinationPath = new Path(packagePath.toString());
// get an IFolder for this path. It's relative to the 'gen' folder already
IFolder destinationFolder = mGenFolder.getFolder(destinationPath);
// create it if needed.
if (destinationFolder.exists() == false && createFolders) {
createFolder(destinationFolder, monitor);
}
// Build the Java file name from the aidl name.
String javaName = aidlData.aidlFile.getName().replaceAll(AndroidConstants.RE_AIDL_EXT,
AndroidConstants.DOT_JAVA);
// get the resource for the java file.
IFile javaFile = destinationFolder.getFile(javaName);
return javaFile;
}
/**
* Creates the destination folder. Because
* {@link IFolder#create(boolean, boolean, IProgressMonitor)} only works if the parent folder
* already exists, this goes and ensure that all the parent folders actually exist, or it
* creates them as well.
* @param destinationFolder The folder to create
* @param monitor the {@link IProgressMonitor},
* @throws CoreException
*/
private void createFolder(IFolder destinationFolder, IProgressMonitor monitor)
throws CoreException {
// check the parent exist and create if necessary.
IContainer parent = destinationFolder.getParent();
if (parent.getType() == IResource.FOLDER && parent.exists() == false) {
createFolder((IFolder)parent, monitor);
}
// create the folder.
destinationFolder.create(true /*force*/, true /*local*/,
new SubProgressMonitor(monitor, 10));
}
/**
* Execute the aidl command line, parse the output, and mark the aidl file
* with any reported errors.
* @param command the String array containing the command line to execute.
* @param file The IFile object representing the aidl file being
* compiled.
* @return false if the exec failed, and build needs to be aborted.
*/
private boolean execAidl(String[] command, IFile file) {
// do the exec
try {
Process p = Runtime.getRuntime().exec(command);
// list to store each line of stderr
ArrayList<String> results = new ArrayList<String>();
// get the output and return code from the process
int result = grabProcessOutput(p, results);
// attempt to parse the error output
boolean error = parseAidlOutput(results, file);
// If the process failed and we couldn't parse the output
// we pring a message, mark the project and exit
if (result != 0 && error == true) {
// display the message in the console.
AdtPlugin.printErrorToConsole(getProject(), results.toArray());
// mark the project and exit
markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AIDL_Errors,
IMarker.SEVERITY_ERROR);
return false;
}
} catch (IOException e) {
// mark the project and exit
String msg = String.format(Messages.AIDL_Exec_Error, command[0]);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
return false;
} catch (InterruptedException e) {
// mark the project and exit
String msg = String.format(Messages.AIDL_Exec_Error, command[0]);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
return false;
}
return true;
}
/**
* Goes through the build paths and fills the list of aidl files to compile
* ({@link #mAidlToCompile}).
* @param project The project.
* @param sourceFolderPathList The list of source folder paths.
*/
private void buildAidlCompilationList(IProject project,
ArrayList<IPath> sourceFolderPathList) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
for (IPath sourceFolderPath : sourceFolderPathList) {
IFolder sourceFolder = root.getFolder(sourceFolderPath);
// we don't look in the 'gen' source folder as there will be no source in there.
if (sourceFolder.exists() && sourceFolder.equals(mGenFolder) == false) {
scanFolderForAidl(sourceFolder, sourceFolder);
}
}
}
/**
* Scans a folder and fills the list of aidl files to compile.
* @param sourceFolder the root source folder.
* @param folder The folder to scan.
*/
private void scanFolderForAidl(IFolder sourceFolder, IFolder folder) {
try {
IResource[] members = folder.members();
for (IResource r : members) {
// get the type of the resource
switch (r.getType()) {
case IResource.FILE:
// if this a file, check that the file actually exist
// and that it's an aidl file
if (r.exists() &&
AndroidConstants.EXT_AIDL.equalsIgnoreCase(r.getFileExtension())) {
mAidlToCompile.add(new AidlData(sourceFolder, (IFile)r));
}
break;
case IResource.FOLDER:
// recursively go through children
scanFolderForAidl(sourceFolder, (IFolder)r);
break;
default:
// this would mean it's a project or the workspace root
// which is unlikely to happen. we do nothing
break;
}
}
} catch (CoreException e) {
// Couldn't get the members list for some reason. Just return.
}
}
/**
* Parse the output of aidl and mark the file with any errors.
* @param lines The output to parse.
* @param file The file to mark with error.
* @return true if the parsing failed, false if success.
*/
private boolean parseAidlOutput(ArrayList<String> lines, IFile file) {
// nothing to parse? just return false;
if (lines.size() == 0) {
return false;
}
Matcher m;
for (int i = 0; i < lines.size(); i++) {
String p = lines.get(i);
m = sAidlPattern1.matcher(p);
if (m.matches()) {
// we can ignore group 1 which is the location since we already
// have a IFile object representing the aidl file.
String lineStr = m.group(2);
String msg = m.group(3);
// get the line number
int line = 0;
try {
line = Integer.parseInt(lineStr);
} catch (NumberFormatException e) {
// looks like the string we extracted wasn't a valid
// file number. Parsing failed and we return true
return true;
}
// mark the file
BaseProjectHelper.addMarker(file, AndroidConstants.MARKER_AIDL, msg, line,
IMarker.SEVERITY_ERROR);
// success, go to the next line
continue;
}
// invalid line format, flag as error, and bail
return true;
}
return false;
}
/**
* Merge the current list of aidl file to compile/remove with the new one.
* @param toCompile List of file to compile
* @param toRemove List of file to remove
*/
private void mergeAidlFileModifications(ArrayList<AidlData> toCompile,
ArrayList<AidlData> toRemove) {
// loop through the new toRemove list, and add it to the old one,
// plus remove any file that was still to compile and that are now
// removed
for (AidlData r : toRemove) {
if (mAidlToRemove.indexOf(r) == -1) {
mAidlToRemove.add(r);
}
int index = mAidlToCompile.indexOf(r);
if (index != -1) {
mAidlToCompile.remove(index);
}
}
// now loop through the new files to compile and add it to the list.
// Also look for them in the remove list, this would mean that they
// were removed, then added back, and we shouldn't remove them, just
// recompile them.
for (AidlData r : toCompile) {
if (mAidlToCompile.indexOf(r) == -1) {
mAidlToCompile.add(r);
}
int index = mAidlToRemove.indexOf(r);
if (index != -1) {
mAidlToRemove.remove(index);
}
}
}
}
| false | true |
protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
throws CoreException {
try {
mDerivedProgressMonitor.reset();
// First thing we do is go through the resource delta to not
// lose it if we have to abort the build for any reason.
// get the project objects
IProject project = getProject();
// Top level check to make sure the build can move forward.
abortOnBadSetup(project);
IJavaProject javaProject = JavaCore.create(project);
IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
// now we need to get the classpath list
ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(
javaProject);
PreCompilerDeltaVisitor dv = null;
String javaPackage = null;
String minSdkVersion = null;
if (kind == FULL_BUILD) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Full_Pre_Compiler);
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Inc_Pre_Compiler);
// Go through the resources and see if something changed.
// Even if the mCompileResources flag is true from a previously aborted
// build, we need to go through the Resource delta to get a possible
// list of aidl files to compile/remove.
IResourceDelta delta = getDelta(project);
if (delta == null) {
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList);
delta.accept(dv);
// record the state
mMustCompileResources |= dv.getCompileResources();
if (dv.getForceAidlCompile()) {
buildAidlCompilationList(project, sourceFolderPathList);
} else {
// handle aidl modification, and update mMustCompileAidl
mergeAidlFileModifications(dv.getAidlToCompile(),
dv.getAidlToRemove());
}
// get the java package from the visitor
javaPackage = dv.getManifestPackage();
minSdkVersion = dv.getMinSdkVersion();
}
}
// store the build status in the persistent storage
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources);
// if there was some XML errors, we just return w/o doing
// anything since we've put some markers in the files anyway.
if (dv != null && dv.mXmlError) {
AdtPlugin.printErrorToConsole(project, Messages.Xml_Error);
// This interrupts the build. The next builders will not run.
stopBuild(Messages.Xml_Error);
}
// get the manifest file
IFile manifest = AndroidManifestParser.getManifest(project);
if (manifest == null) {
String msg = String.format(Messages.s_File_Missing,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses manifest (which is now guaranteed
// to be null) will actually be executed or not.
}
// lets check the XML of the manifest first, if that hasn't been done by the
// resource delta visitor yet.
if (dv == null || dv.getCheckedManifestXml() == false) {
BasicXmlErrorListener errorListener = new BasicXmlErrorListener();
AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest,
errorListener);
if (errorListener.mHasXmlError == true) {
// there was an error in the manifest, its file has been marked,
// by the XmlErrorHandler.
// We return;
String msg = String.format(Messages.s_Contains_Xml_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// get the java package from the parser
javaPackage = parser.getPackage();
minSdkVersion = parser.getApiLevelRequirement();
}
if (minSdkVersion != null) {
int minSdkValue = -1;
try {
minSdkValue = Integer.parseInt(minSdkVersion);
} catch (NumberFormatException e) {
// it's ok, it means minSdkVersion contains a (hopefully) valid codename.
}
AndroidVersion projectVersion = projectTarget.getVersion();
if (minSdkValue != -1) {
String codename = projectVersion.getCodename();
if (codename != null) {
// integer minSdk when the target is a preview => fatal error
String msg = String.format(
"Platform %1$s is a preview and requires appication manifests to set %2$s to '%3$s'",
codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION,
codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (minSdkValue < projectVersion.getApiLevel()) {
// integer minSdk is not high enough for the target => warning
String msg = String.format(
"Manifest min SDK version (%1$s) is lower than project target API level (%2$d)",
minSdkVersion, projectVersion.getApiLevel());
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_WARNING);
}
} else {
// looks like the min sdk is a codename, check it matches the codename
// of the platform
String codename = projectVersion.getCodename();
if (codename == null) {
// platform is not a preview => fatal error
String msg = String.format(
"Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (codename.equals(minSdkVersion) == false) {
// platform and manifest codenames don't match => fatal error.
String msg = String.format(
"Value of manifest attribute '%1$s' does not match platform codename '%2$s'",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
}
}
}
if (javaPackage == null || javaPackage.length() == 0) {
// looks like the AndroidManifest file isn't valid.
String msg = String.format(Messages.s_Doesnt_Declare_Package_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses javaPackage (which is now guaranteed
// to be null) will actually be executed or not.
}
// at this point we have the java package. We need to make sure it's not a different
// package than the previous one that were built.
if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) {
// The manifest package has changed, the user may want to update
// the launch configuration
if (mManifestPackage != null) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Checking_Package_Change);
FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage,
javaPackage);
flc.start();
}
// now we delete the generated classes from their previous location
deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS,
mManifestPackage);
deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS,
mManifestPackage);
// record the new manifest package, and save it.
mManifestPackage = javaPackage;
saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage);
}
if (mMustCompileResources) {
// we need to figure out where to store the R class.
// get the parent folder for R.java and update mManifestPackageSourceFolder
IFolder packageFolder = getGenManifestPackageFolder(project);
// get the resource folder
IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES);
// get the file system path
IPath outputLocation = mGenFolder.getLocation();
IPath resLocation = resFolder.getLocation();
IPath manifestLocation = manifest == null ? null : manifest.getLocation();
// those locations have to exist for us to do something!
if (outputLocation != null && resLocation != null
&& manifestLocation != null) {
String osOutputPath = outputLocation.toOSString();
String osResPath = resLocation.toOSString();
String osManifestPath = manifestLocation.toOSString();
// remove the aapt markers
removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE);
removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Preparing_Generated_Files);
// since the R.java file may be already existing in read-only
// mode we need to make it readable so that aapt can overwrite
// it
IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS);
// do the same for the Manifest.java class
IFile manifestJavaFile = packageFolder.getFile(
AndroidConstants.FN_MANIFEST_CLASS);
// we actually need to delete the manifest.java as it may become empty and
// in this case aapt doesn't generate an empty one, but instead doesn't
// touch it.
manifestJavaFile.delete(true, null);
// launch aapt: create the command line
ArrayList<String> array = new ArrayList<String>();
array.add(projectTarget.getPath(IAndroidTarget.AAPT));
array.add("package"); //$NON-NLS-1$
array.add("-m"); //$NON-NLS-1$
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
array.add("-v"); //$NON-NLS-1$
}
array.add("-J"); //$NON-NLS-1$
array.add(osOutputPath);
array.add("-M"); //$NON-NLS-1$
array.add(osManifestPath);
array.add("-S"); //$NON-NLS-1$
array.add(osResPath);
array.add("-I"); //$NON-NLS-1$
array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR));
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
StringBuilder sb = new StringBuilder();
for (String c : array) {
sb.append(c);
sb.append(' ');
}
String cmd_line = sb.toString();
AdtPlugin.printToConsole(project, cmd_line);
}
// launch
int execError = 1;
try {
// launch the command line process
Process process = Runtime.getRuntime().exec(
array.toArray(new String[array.size()]));
// list to store each line of stderr
ArrayList<String> results = new ArrayList<String>();
// get the output and return code from the process
execError = grabProcessOutput(process, results);
// attempt to parse the error output
boolean parsingError = parseAaptOutput(results, project);
// if we couldn't parse the output we display it in the console.
if (parsingError) {
if (execError != 0) {
AdtPlugin.printErrorToConsole(project, results.toArray());
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL,
project, results.toArray());
}
}
if (execError != 0) {
// if the exec failed, and we couldn't parse the error output
// (and therefore not all files that should have been marked,
// were marked), we put a generic marker on the project and abort.
if (parsingError) {
markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors,
IMarker.SEVERITY_ERROR);
}
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.AAPT_Error);
// abort if exec failed.
// This interrupts the build. The next builders will not run.
stopBuild(Messages.AAPT_Error);
}
} catch (IOException e1) {
// something happen while executing the process,
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
} catch (InterruptedException e) {
// we got interrupted waiting for the process to end...
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// if the return code was OK, we refresh the folder that
// contains R.java to force a java recompile.
if (execError == 0) {
// now add the R.java/Manifest.java to the list of file to be marked
// as derived.
mDerivedProgressMonitor.addFile(rJavaFile);
mDerivedProgressMonitor.addFile(manifestJavaFile);
// build has been done. reset the state of the builder
mMustCompileResources = false;
// and store it
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES,
mMustCompileResources);
}
}
} else {
// nothing to do
}
// now handle the aidl stuff.
boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor);
if (aidlStatus == false && mMustCompileResources == false) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Nothing_To_Compile);
}
} finally {
// refresh the 'gen' source folder. Once this is done with the custom progress
// monitor to mark all new files as derived
mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
}
return null;
}
|
protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
throws CoreException {
try {
mDerivedProgressMonitor.reset();
// First thing we do is go through the resource delta to not
// lose it if we have to abort the build for any reason.
// get the project objects
IProject project = getProject();
// Top level check to make sure the build can move forward.
abortOnBadSetup(project);
IJavaProject javaProject = JavaCore.create(project);
IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
// now we need to get the classpath list
ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(
javaProject);
PreCompilerDeltaVisitor dv = null;
String javaPackage = null;
String minSdkVersion = null;
if (kind == FULL_BUILD) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Full_Pre_Compiler);
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Start_Inc_Pre_Compiler);
// Go through the resources and see if something changed.
// Even if the mCompileResources flag is true from a previously aborted
// build, we need to go through the Resource delta to get a possible
// list of aidl files to compile/remove.
IResourceDelta delta = getDelta(project);
if (delta == null) {
mMustCompileResources = true;
buildAidlCompilationList(project, sourceFolderPathList);
} else {
dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList);
delta.accept(dv);
// record the state
mMustCompileResources |= dv.getCompileResources();
if (dv.getForceAidlCompile()) {
buildAidlCompilationList(project, sourceFolderPathList);
} else {
// handle aidl modification, and update mMustCompileAidl
mergeAidlFileModifications(dv.getAidlToCompile(),
dv.getAidlToRemove());
}
// get the java package from the visitor
javaPackage = dv.getManifestPackage();
minSdkVersion = dv.getMinSdkVersion();
}
}
// store the build status in the persistent storage
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources);
// if there was some XML errors, we just return w/o doing
// anything since we've put some markers in the files anyway.
if (dv != null && dv.mXmlError) {
AdtPlugin.printErrorToConsole(project, Messages.Xml_Error);
// This interrupts the build. The next builders will not run.
stopBuild(Messages.Xml_Error);
}
// get the manifest file
IFile manifest = AndroidManifestParser.getManifest(project);
if (manifest == null) {
String msg = String.format(Messages.s_File_Missing,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses manifest (which is now guaranteed
// to be null) will actually be executed or not.
}
// lets check the XML of the manifest first, if that hasn't been done by the
// resource delta visitor yet.
if (dv == null || dv.getCheckedManifestXml() == false) {
BasicXmlErrorListener errorListener = new BasicXmlErrorListener();
AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest,
errorListener);
if (errorListener.mHasXmlError == true) {
// there was an error in the manifest, its file has been marked,
// by the XmlErrorHandler.
// We return;
String msg = String.format(Messages.s_Contains_Xml_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// get the java package from the parser
javaPackage = parser.getPackage();
minSdkVersion = parser.getApiLevelRequirement();
}
if (minSdkVersion != null) {
int minSdkValue = -1;
try {
minSdkValue = Integer.parseInt(minSdkVersion);
} catch (NumberFormatException e) {
// it's ok, it means minSdkVersion contains a (hopefully) valid codename.
}
AndroidVersion projectVersion = projectTarget.getVersion();
if (minSdkValue != -1) {
String codename = projectVersion.getCodename();
if (codename != null) {
// integer minSdk when the target is a preview => fatal error
String msg = String.format(
"Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'",
codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (minSdkValue < projectVersion.getApiLevel()) {
// integer minSdk is not high enough for the target => warning
String msg = String.format(
"Manifest min SDK version (%1$s) is lower than project target API level (%2$d)",
minSdkVersion, projectVersion.getApiLevel());
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_WARNING);
}
} else {
// looks like the min sdk is a codename, check it matches the codename
// of the platform
String codename = projectVersion.getCodename();
if (codename == null) {
// platform is not a preview => fatal error
String msg = String.format(
"Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
} else if (codename.equals(minSdkVersion) == false) {
// platform and manifest codenames don't match => fatal error.
String msg = String.format(
"Value of manifest attribute '%1$s' does not match platform codename '%2$s'",
ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
}
}
} else if (projectTarget.getVersion().isPreview()) {
// else the minSdkVersion is not set but we are using a preview target.
// Display an error
String codename = projectTarget.getVersion().getCodename();
String msg = String.format(
"Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'",
codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION);
AdtPlugin.printErrorToConsole(project, msg);
BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg,
IMarker.SEVERITY_ERROR);
stopBuild(msg);
}
if (javaPackage == null || javaPackage.length() == 0) {
// looks like the AndroidManifest file isn't valid.
String msg = String.format(Messages.s_Doesnt_Declare_Package_Error,
AndroidConstants.FN_ANDROID_MANIFEST);
AdtPlugin.printErrorToConsole(project, msg);
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
// TODO: document whether code below that uses javaPackage (which is now guaranteed
// to be null) will actually be executed or not.
}
// at this point we have the java package. We need to make sure it's not a different
// package than the previous one that were built.
if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) {
// The manifest package has changed, the user may want to update
// the launch configuration
if (mManifestPackage != null) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Checking_Package_Change);
FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage,
javaPackage);
flc.start();
}
// now we delete the generated classes from their previous location
deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS,
mManifestPackage);
deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS,
mManifestPackage);
// record the new manifest package, and save it.
mManifestPackage = javaPackage;
saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage);
}
if (mMustCompileResources) {
// we need to figure out where to store the R class.
// get the parent folder for R.java and update mManifestPackageSourceFolder
IFolder packageFolder = getGenManifestPackageFolder(project);
// get the resource folder
IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES);
// get the file system path
IPath outputLocation = mGenFolder.getLocation();
IPath resLocation = resFolder.getLocation();
IPath manifestLocation = manifest == null ? null : manifest.getLocation();
// those locations have to exist for us to do something!
if (outputLocation != null && resLocation != null
&& manifestLocation != null) {
String osOutputPath = outputLocation.toOSString();
String osResPath = resLocation.toOSString();
String osManifestPath = manifestLocation.toOSString();
// remove the aapt markers
removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE);
removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE);
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Preparing_Generated_Files);
// since the R.java file may be already existing in read-only
// mode we need to make it readable so that aapt can overwrite
// it
IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS);
// do the same for the Manifest.java class
IFile manifestJavaFile = packageFolder.getFile(
AndroidConstants.FN_MANIFEST_CLASS);
// we actually need to delete the manifest.java as it may become empty and
// in this case aapt doesn't generate an empty one, but instead doesn't
// touch it.
manifestJavaFile.delete(true, null);
// launch aapt: create the command line
ArrayList<String> array = new ArrayList<String>();
array.add(projectTarget.getPath(IAndroidTarget.AAPT));
array.add("package"); //$NON-NLS-1$
array.add("-m"); //$NON-NLS-1$
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
array.add("-v"); //$NON-NLS-1$
}
array.add("-J"); //$NON-NLS-1$
array.add(osOutputPath);
array.add("-M"); //$NON-NLS-1$
array.add(osManifestPath);
array.add("-S"); //$NON-NLS-1$
array.add(osResPath);
array.add("-I"); //$NON-NLS-1$
array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR));
if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) {
StringBuilder sb = new StringBuilder();
for (String c : array) {
sb.append(c);
sb.append(' ');
}
String cmd_line = sb.toString();
AdtPlugin.printToConsole(project, cmd_line);
}
// launch
int execError = 1;
try {
// launch the command line process
Process process = Runtime.getRuntime().exec(
array.toArray(new String[array.size()]));
// list to store each line of stderr
ArrayList<String> results = new ArrayList<String>();
// get the output and return code from the process
execError = grabProcessOutput(process, results);
// attempt to parse the error output
boolean parsingError = parseAaptOutput(results, project);
// if we couldn't parse the output we display it in the console.
if (parsingError) {
if (execError != 0) {
AdtPlugin.printErrorToConsole(project, results.toArray());
} else {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL,
project, results.toArray());
}
}
if (execError != 0) {
// if the exec failed, and we couldn't parse the error output
// (and therefore not all files that should have been marked,
// were marked), we put a generic marker on the project and abort.
if (parsingError) {
markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors,
IMarker.SEVERITY_ERROR);
}
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.AAPT_Error);
// abort if exec failed.
// This interrupts the build. The next builders will not run.
stopBuild(Messages.AAPT_Error);
}
} catch (IOException e1) {
// something happen while executing the process,
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
} catch (InterruptedException e) {
// we got interrupted waiting for the process to end...
// mark the project and exit
String msg = String.format(Messages.AAPT_Exec_Error, array.get(0));
markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
// This interrupts the build. The next builders will not run.
stopBuild(msg);
}
// if the return code was OK, we refresh the folder that
// contains R.java to force a java recompile.
if (execError == 0) {
// now add the R.java/Manifest.java to the list of file to be marked
// as derived.
mDerivedProgressMonitor.addFile(rJavaFile);
mDerivedProgressMonitor.addFile(manifestJavaFile);
// build has been done. reset the state of the builder
mMustCompileResources = false;
// and store it
saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES,
mMustCompileResources);
}
}
} else {
// nothing to do
}
// now handle the aidl stuff.
boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor);
if (aidlStatus == false && mMustCompileResources == false) {
AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project,
Messages.Nothing_To_Compile);
}
} finally {
// refresh the 'gen' source folder. Once this is done with the custom progress
// monitor to mark all new files as derived
mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
}
return null;
}
|
diff --git a/cadpage/src/net/anei/cadpage/parsers/MDAlleganyCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/MDAlleganyCountyParser.java
index 0ae80d7cd..b3ba40b2e 100644
--- a/cadpage/src/net/anei/cadpage/parsers/MDAlleganyCountyParser.java
+++ b/cadpage/src/net/anei/cadpage/parsers/MDAlleganyCountyParser.java
@@ -1,77 +1,77 @@
package net.anei.cadpage.parsers;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.anei.cadpage.Log;
import net.anei.cadpage.SmsMsgInfo.Data;
/*
Alleghany County, MD
Contact: Joseph Hoffman <[email protected]>
Sender: unpredicatable
FRM:LogiSYSCAD\nSUBJ:CAD Page for CFS 100110-96\nMSG:UNCONCIOUS/UNRESPONSIVE 91 S BROADWAY\nUnits: A53 CO16
FRM:LogiSYSCAD\nSUBJ:CAD Page for CFS 100710-102\nMSG:AUTOMATIC HOUSE ALARM 106 SUNSET DR\nUnits: CO2 ENG9 A52 TR16
FRM:LogiSYSCAD\nSUBJ:CAD Page for CFS 101310-67\nMSG:HOUSE FIRE 147 ORMAND ST\nUnits: ENG16 TR16 ENG17
FRM:LogiSYSCAD\nSUBJ:CAD Page for CFS 101510-80\nMSG:HOUSE FIRE 72 HOSPITAL ROAD\nUnits: ENG16 TR16 ENG17
FRM:LogiSYSCAD\nSUBJ:CAD Page for CFS 100210-88\nMSG:SMOKE INVESTIGATION U:LOWER CONSEL RD\nUnits: CO16
*/
public class MDAlleganyCountyParser extends SmsMsgParser {
// Pattern matching a sequence of two or more blanks
protected static final Pattern MULT_BLANKS = Pattern.compile(" +");
@Override
public boolean isPageMsg(String body) {
return body.startsWith("FRM:LogiSYSCAD\n");
}
@Override
protected void parse(String body, Data data) {
Log.v("DecodeAlleganyCo: Message Body of:" + body);
data.defState="MD";
data.defCity="ALLEGANY COUNTY";
Properties props = parseMessage(body, "\n");
// SUBJ: line contains the call ID as the last token
String line = props.getProperty("SUBJ", "");
int pt = line.lastIndexOf(' ');
if (pt >= 0) line = line.substring(pt+1);
data.strCallId = line;
// MSG: line contains call description and address.
// The separator can be several different things
line = props.getProperty("MSG", "");
String address = null;
Matcher match;
// Address may start with "U:"
pt = line.indexOf(" U:");
if (pt >= 0) {
data.strCall = line.substring(0, pt).trim();
address = line.substring(pt+3).trim();
}
// May be separated by string of 2 or more blanks
else if ((match = MULT_BLANKS.matcher(line)).find()) {
data.strCall = line.substring(0, match.start());
address = line.substring(match.end());
}
// Or address may start with a numeric token
else if ((match = NUMERIC.matcher(line)).find()) {
data.strCall = line.substring(0,match.start()).trim();
address = line.substring(match.start());
}
// parse address line
if (address != null) parseAddress(address, data);
// UNITS: line contains the units
- data.strUnit = props.getProperty("Units");
+ data.strUnit = props.getProperty("Units", "");
}
}
| true | true |
protected void parse(String body, Data data) {
Log.v("DecodeAlleganyCo: Message Body of:" + body);
data.defState="MD";
data.defCity="ALLEGANY COUNTY";
Properties props = parseMessage(body, "\n");
// SUBJ: line contains the call ID as the last token
String line = props.getProperty("SUBJ", "");
int pt = line.lastIndexOf(' ');
if (pt >= 0) line = line.substring(pt+1);
data.strCallId = line;
// MSG: line contains call description and address.
// The separator can be several different things
line = props.getProperty("MSG", "");
String address = null;
Matcher match;
// Address may start with "U:"
pt = line.indexOf(" U:");
if (pt >= 0) {
data.strCall = line.substring(0, pt).trim();
address = line.substring(pt+3).trim();
}
// May be separated by string of 2 or more blanks
else if ((match = MULT_BLANKS.matcher(line)).find()) {
data.strCall = line.substring(0, match.start());
address = line.substring(match.end());
}
// Or address may start with a numeric token
else if ((match = NUMERIC.matcher(line)).find()) {
data.strCall = line.substring(0,match.start()).trim();
address = line.substring(match.start());
}
// parse address line
if (address != null) parseAddress(address, data);
// UNITS: line contains the units
data.strUnit = props.getProperty("Units");
}
|
protected void parse(String body, Data data) {
Log.v("DecodeAlleganyCo: Message Body of:" + body);
data.defState="MD";
data.defCity="ALLEGANY COUNTY";
Properties props = parseMessage(body, "\n");
// SUBJ: line contains the call ID as the last token
String line = props.getProperty("SUBJ", "");
int pt = line.lastIndexOf(' ');
if (pt >= 0) line = line.substring(pt+1);
data.strCallId = line;
// MSG: line contains call description and address.
// The separator can be several different things
line = props.getProperty("MSG", "");
String address = null;
Matcher match;
// Address may start with "U:"
pt = line.indexOf(" U:");
if (pt >= 0) {
data.strCall = line.substring(0, pt).trim();
address = line.substring(pt+3).trim();
}
// May be separated by string of 2 or more blanks
else if ((match = MULT_BLANKS.matcher(line)).find()) {
data.strCall = line.substring(0, match.start());
address = line.substring(match.end());
}
// Or address may start with a numeric token
else if ((match = NUMERIC.matcher(line)).find()) {
data.strCall = line.substring(0,match.start()).trim();
address = line.substring(match.start());
}
// parse address line
if (address != null) parseAddress(address, data);
// UNITS: line contains the units
data.strUnit = props.getProperty("Units", "");
}
|
diff --git a/src/com/android/phone/NotificationMgr.java b/src/com/android/phone/NotificationMgr.java
index 56d42294..f797be3c 100644
--- a/src/com/android/phone/NotificationMgr.java
+++ b/src/com/android/phone/NotificationMgr.java
@@ -1,1243 +1,1243 @@
/*
* Copyright (C) 2006 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.phone;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.StatusBarManager;
import android.content.AsyncQueryHandler;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallerInfo;
import com.android.internal.telephony.CallerInfoAsyncQuery;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneBase;
import com.android.internal.telephony.CallManager;
/**
* NotificationManager-related utility code for the Phone app.
*
* This is a singleton object which acts as the interface to the
* framework's NotificationManager, and is used to display status bar
* icons and control other status bar-related behavior.
*
* @see PhoneApp.notificationMgr
*/
public class NotificationMgr implements CallerInfoAsyncQuery.OnQueryCompleteListener{
private static final String LOG_TAG = "NotificationMgr";
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final String[] CALL_LOG_PROJECTION = new String[] {
Calls._ID,
Calls.NUMBER,
Calls.DATE,
Calls.DURATION,
Calls.TYPE,
};
// notification types
static final int MISSED_CALL_NOTIFICATION = 1;
static final int IN_CALL_NOTIFICATION = 2;
static final int MMI_NOTIFICATION = 3;
static final int NETWORK_SELECTION_NOTIFICATION = 4;
static final int VOICEMAIL_NOTIFICATION = 5;
static final int CALL_FORWARD_NOTIFICATION = 6;
static final int DATA_DISCONNECTED_ROAMING_NOTIFICATION = 7;
static final int SELECTED_OPERATOR_FAIL_NOTIFICATION = 8;
/** The singleton NotificationMgr instance. */
private static NotificationMgr sInstance;
private PhoneApp mApp;
private Phone mPhone;
private CallManager mCM;
private Context mContext;
private NotificationManager mNotificationManager;
private StatusBarManager mStatusBarManager;
private Toast mToast;
private boolean mShowingSpeakerphoneIcon;
private boolean mShowingMuteIcon;
public StatusBarHelper statusBarHelper;
// used to track the missed call counter, default to 0.
private int mNumberMissedCalls = 0;
// Currently-displayed resource IDs for some status bar icons (or zero
// if no notification is active):
private int mInCallResId;
// used to track the notification of selected network unavailable
private boolean mSelectedUnavailableNotify = false;
// Retry params for the getVoiceMailNumber() call; see updateMwi().
private static final int MAX_VM_NUMBER_RETRIES = 5;
private static final int VM_NUMBER_RETRY_DELAY_MILLIS = 10000;
private int mVmNumberRetriesRemaining = MAX_VM_NUMBER_RETRIES;
// Query used to look up caller-id info for the "call log" notification.
private QueryHandler mQueryHandler = null;
private static final int CALL_LOG_TOKEN = -1;
private static final int CONTACT_TOKEN = -2;
/**
* Private constructor (this is a singleton).
* @see init()
*/
private NotificationMgr(PhoneApp app) {
mApp = app;
mContext = app;
mNotificationManager =
(NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);
mStatusBarManager =
(StatusBarManager) app.getSystemService(Context.STATUS_BAR_SERVICE);
mPhone = app.phone; // TODO: better style to use mCM.getDefaultPhone() everywhere instead
mCM = app.mCM;
statusBarHelper = new StatusBarHelper();
}
/**
* Initialize the singleton NotificationMgr instance.
*
* This is only done once, at startup, from PhoneApp.onCreate().
* From then on, the NotificationMgr instance is available via the
* PhoneApp's public "notificationMgr" field, which is why there's no
* getInstance() method here.
*/
/* package */ static NotificationMgr init(PhoneApp app) {
synchronized (NotificationMgr.class) {
if (sInstance == null) {
sInstance = new NotificationMgr(app);
// Update the notifications that need to be touched at startup.
sInstance.updateNotificationsAtStartup();
} else {
Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
}
return sInstance;
}
}
/**
* Helper class that's a wrapper around the framework's
* StatusBarManager.disable() API.
*
* This class is used to control features like:
*
* - Disabling the status bar "notification windowshade"
* while the in-call UI is up
*
* - Disabling notification alerts (audible or vibrating)
* while a phone call is active
*
* - Disabling navigation via the system bar (the "soft buttons" at
* the bottom of the screen on devices with no hard buttons)
*
* We control these features through a single point of control to make
* sure that the various StatusBarManager.disable() calls don't
* interfere with each other.
*/
public class StatusBarHelper {
// Current desired state of status bar / system bar behavior
private boolean mIsNotificationEnabled = true;
private boolean mIsExpandedViewEnabled = true;
private boolean mIsSystemBarNavigationEnabled = true;
private StatusBarHelper () {
}
/**
* Enables or disables auditory / vibrational alerts.
*
* (We disable these any time a voice call is active, regardless
* of whether or not the in-call UI is visible.)
*/
public void enableNotificationAlerts(boolean enable) {
if (mIsNotificationEnabled != enable) {
mIsNotificationEnabled = enable;
updateStatusBar();
}
}
/**
* Enables or disables the expanded view of the status bar
* (i.e. the ability to pull down the "notification windowshade").
*
* (This feature is disabled by the InCallScreen while the in-call
* UI is active.)
*/
public void enableExpandedView(boolean enable) {
if (mIsExpandedViewEnabled != enable) {
mIsExpandedViewEnabled = enable;
updateStatusBar();
}
}
/**
* Enables or disables the navigation via the system bar (the
* "soft buttons" at the bottom of the screen)
*
* (This feature is disabled while an incoming call is ringing,
* because it's easy to accidentally touch the system bar while
* pulling the phone out of your pocket.)
*/
public void enableSystemBarNavigation(boolean enable) {
if (mIsSystemBarNavigationEnabled != enable) {
mIsSystemBarNavigationEnabled = enable;
updateStatusBar();
}
}
/**
* Updates the status bar to reflect the current desired state.
*/
private void updateStatusBar() {
int state = StatusBarManager.DISABLE_NONE;
if (!mIsExpandedViewEnabled) {
state |= StatusBarManager.DISABLE_EXPAND;
}
if (!mIsNotificationEnabled) {
state |= StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
}
if (!mIsSystemBarNavigationEnabled) {
state |= StatusBarManager.DISABLE_NAVIGATION;
}
if (DBG) log("updateStatusBar: state = 0x" + Integer.toHexString(state));
mStatusBarManager.disable(state);
}
}
/**
* Makes sure phone-related notifications are up to date on a
* freshly-booted device.
*/
private void updateNotificationsAtStartup() {
if (DBG) log("updateNotificationsAtStartup()...");
// instantiate query handler
mQueryHandler = new QueryHandler(mContext.getContentResolver());
// setup query spec, look for all Missed calls that are new.
StringBuilder where = new StringBuilder("type=");
where.append(Calls.MISSED_TYPE);
where.append(" AND new=1");
// start the query
if (DBG) log("- start call log query...");
mQueryHandler.startQuery(CALL_LOG_TOKEN, null, Calls.CONTENT_URI, CALL_LOG_PROJECTION,
where.toString(), null, Calls.DEFAULT_SORT_ORDER);
// Update (or cancel) the in-call notification
if (DBG) log("- updating in-call notification at startup...");
updateInCallNotification();
// Depend on android.app.StatusBarManager to be set to
// disable(DISABLE_NONE) upon startup. This will be the
// case even if the phone app crashes.
}
/** The projection to use when querying the phones table */
static final String[] PHONES_PROJECTION = new String[] {
PhoneLookup.NUMBER,
PhoneLookup.DISPLAY_NAME
};
/**
* Class used to run asynchronous queries to re-populate
* the notifications we care about.
*/
private class QueryHandler extends AsyncQueryHandler {
/**
* Used to store relevant fields for the Missed Call
* notifications.
*/
private class NotificationInfo {
public String name;
public String number;
public String label;
public long date;
}
public QueryHandler(ContentResolver cr) {
super(cr);
}
/**
* Handles the query results. There are really 2 steps to this,
* similar to what happens in CallLogActivity.
* 1. Find the list of missed calls
* 2. For each call, run a query to retrieve the caller's name.
*/
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// TODO: it would be faster to use a join here, but for the purposes
// of this small record set, it should be ok.
// Note that CursorJoiner is not useable here because the number
// comparisons are not strictly equals; the comparisons happen in
// the SQL function PHONE_NUMBERS_EQUAL, which is not available for
// the CursorJoiner.
// Executing our own query is also feasible (with a join), but that
// will require some work (possibly destabilizing) in Contacts
// Provider.
// At this point, we will execute subqueries on each row just as
// CallLogActivity.java does.
switch (token) {
case CALL_LOG_TOKEN:
if (DBG) log("call log query complete.");
// initial call to retrieve the call list.
if (cursor != null) {
while (cursor.moveToNext()) {
// for each call in the call log list, create
// the notification object and query contacts
NotificationInfo n = getNotificationInfo (cursor);
if (DBG) log("query contacts for number: " + n.number);
mQueryHandler.startQuery(CONTACT_TOKEN, n,
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, n.number),
PHONES_PROJECTION, null, null, PhoneLookup.NUMBER);
}
if (DBG) log("closing call log cursor.");
cursor.close();
}
break;
case CONTACT_TOKEN:
if (DBG) log("contact query complete.");
// subqueries to get the caller name.
if ((cursor != null) && (cookie != null)){
NotificationInfo n = (NotificationInfo) cookie;
if (cursor.moveToFirst()) {
// we have contacts data, get the name.
if (DBG) log("contact :" + n.name + " found for phone: " + n.number);
n.name = cursor.getString(
cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
}
// send the notification
if (DBG) log("sending notification.");
notifyMissedCall(n.name, n.number, n.label, n.date);
if (DBG) log("closing contact cursor.");
cursor.close();
}
break;
default:
}
}
/**
* Factory method to generate a NotificationInfo object given a
* cursor from the call log table.
*/
private final NotificationInfo getNotificationInfo(Cursor cursor) {
NotificationInfo n = new NotificationInfo();
n.name = null;
n.number = cursor.getString(cursor.getColumnIndexOrThrow(Calls.NUMBER));
n.label = cursor.getString(cursor.getColumnIndexOrThrow(Calls.TYPE));
n.date = cursor.getLong(cursor.getColumnIndexOrThrow(Calls.DATE));
// make sure we update the number depending upon saved values in
// CallLog.addCall(). If either special values for unknown or
// private number are detected, we need to hand off the message
// to the missed call notification.
if ( (n.number.equals(CallerInfo.UNKNOWN_NUMBER)) ||
(n.number.equals(CallerInfo.PRIVATE_NUMBER)) ||
(n.number.equals(CallerInfo.PAYPHONE_NUMBER)) ) {
n.number = null;
}
if (DBG) log("NotificationInfo constructed for number: " + n.number);
return n;
}
}
/**
* Configures a Notification to emit the blinky green message-waiting/
* missed-call signal.
*/
private static void configureLedNotification(Notification note) {
note.flags |= Notification.FLAG_SHOW_LIGHTS;
note.defaults |= Notification.DEFAULT_LIGHTS;
}
/**
* Displays a notification about a missed call.
*
* @param nameOrNumber either the contact name, or the phone number if no contact
* @param label the label of the number if nameOrNumber is a name, null if it is a number
*/
void notifyMissedCall(String name, String number, String label, long date) {
// When the user clicks this notification, we go to the call log.
final Intent callLogIntent = PhoneApp.createCallLogIntent();
// Never display the missed call notification on non-voice-capable
// devices, even if the device does somehow manage to get an
// incoming call.
if (!PhoneApp.sVoiceCapable) {
if (DBG) log("notifyMissedCall: non-voice-capable device, not posting notification");
return;
}
// title resource id
int titleResId;
// the text in the notification's line 1 and 2.
String expandedText, callName;
// increment number of missed calls.
mNumberMissedCalls++;
// get the name for the ticker text
// i.e. "Missed call from <caller name or number>"
if (name != null && TextUtils.isGraphic(name)) {
callName = name;
} else if (!TextUtils.isEmpty(number)){
callName = number;
} else {
// use "unknown" if the caller is unidentifiable.
callName = mContext.getString(R.string.unknown);
}
// display the first line of the notification:
// 1 missed call: call name
// more than 1 missed call: <number of calls> + "missed calls"
if (mNumberMissedCalls == 1) {
titleResId = R.string.notification_missedCallTitle;
expandedText = callName;
} else {
titleResId = R.string.notification_missedCallsTitle;
expandedText = mContext.getString(R.string.notification_missedCallsMsg,
mNumberMissedCalls);
}
// make the notification
Notification note = new Notification(
android.R.drawable.stat_notify_missed_call, // icon
mContext.getString(R.string.notification_missedCallTicker, callName), // tickerText
date // when
);
note.setLatestEventInfo(mContext, mContext.getText(titleResId), expandedText,
PendingIntent.getActivity(mContext, 0, callLogIntent, 0));
note.flags |= Notification.FLAG_AUTO_CANCEL;
// This intent will be called when the notification is dismissed.
// It will take care of clearing the list of missed calls.
note.deleteIntent = createClearMissedCallsIntent();
configureLedNotification(note);
mNotificationManager.notify(MISSED_CALL_NOTIFICATION, note);
}
/** Returns an intent to be invoked when the missed call notification is cleared. */
private PendingIntent createClearMissedCallsIntent() {
Intent intent = new Intent(mContext, ClearMissedCallsService.class);
intent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
return PendingIntent.getService(mContext, 0, intent, 0);
}
/**
* Cancels the "missed call" notification.
*
* @see ITelephony.cancelMissedCallsNotification()
*/
void cancelMissedCallNotification() {
// reset the number of missed calls to 0.
mNumberMissedCalls = 0;
mNotificationManager.cancel(MISSED_CALL_NOTIFICATION);
}
void notifySpeakerphone() {
if (!mShowingSpeakerphoneIcon) {
mStatusBarManager.setIcon("speakerphone", android.R.drawable.stat_sys_speakerphone, 0,
mContext.getString(R.string.accessibility_speakerphone_enabled));
mShowingSpeakerphoneIcon = true;
}
}
void cancelSpeakerphone() {
if (mShowingSpeakerphoneIcon) {
mStatusBarManager.removeIcon("speakerphone");
mShowingSpeakerphoneIcon = false;
}
}
/**
* Calls either notifySpeakerphone() or cancelSpeakerphone() based on
* the actual current state of the speaker.
*/
void updateSpeakerNotification() {
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
if ((mPhone.getState() == Phone.State.OFFHOOK) && audioManager.isSpeakerphoneOn()) {
if (DBG) log("updateSpeakerNotification: speaker ON");
notifySpeakerphone();
} else {
if (DBG) log("updateSpeakerNotification: speaker OFF (or not offhook)");
cancelSpeakerphone();
}
}
private void notifyMute() {
if (!mShowingMuteIcon) {
mStatusBarManager.setIcon("mute", android.R.drawable.stat_notify_call_mute, 0,
mContext.getString(R.string.accessibility_call_muted));
mShowingMuteIcon = true;
}
}
private void cancelMute() {
if (mShowingMuteIcon) {
mStatusBarManager.removeIcon("mute");
mShowingMuteIcon = false;
}
}
/**
* Calls either notifyMute() or cancelMute() based on
* the actual current mute state of the Phone.
*/
void updateMuteNotification() {
if ((mCM.getState() == Phone.State.OFFHOOK) && PhoneUtils.getMute()) {
if (DBG) log("updateMuteNotification: MUTED");
notifyMute();
} else {
if (DBG) log("updateMuteNotification: not muted (or not offhook)");
cancelMute();
}
}
/**
* Updates the phone app's status bar notification based on the
* current telephony state, or cancels the notification if the phone
* is totally idle.
*
* This method will never actually launch the incoming-call UI.
* (Use updateNotificationAndLaunchIncomingCallUi() for that.)
*/
public void updateInCallNotification() {
// allowFullScreenIntent=false means *don't* allow the incoming
// call UI to be launched.
updateInCallNotification(false);
}
/**
* Updates the phone app's status bar notification *and* launches the
* incoming call UI in response to a new incoming call.
*
* This is just like updateInCallNotification(), with one exception:
* If an incoming call is ringing (or call-waiting), the notification
* will also include a "fullScreenIntent" that will cause the
* InCallScreen to be launched immediately, unless the current
* foreground activity is marked as "immersive".
*
* (This is the mechanism that actually brings up the incoming call UI
* when we receive a "new ringing connection" event from the telephony
* layer.)
*
* Watch out: this method should ONLY be called directly from the code
* path in CallNotifier that handles the "new ringing connection"
* event from the telephony layer. All other places that update the
* in-call notification (like for phone state changes) should call
* updateInCallNotification() instead. (This ensures that we don't
* end up launching the InCallScreen multiple times for a single
* incoming call, which could cause slow responsiveness and/or visible
* glitches.)
*
* Also note that this method is safe to call even if the phone isn't
* actually ringing (or, more likely, if an incoming call *was*
* ringing briefly but then disconnected). In that case, we'll simply
* update or cancel the in-call notification based on the current
* phone state.
*
* @see updateInCallNotification()
*/
public void updateNotificationAndLaunchIncomingCallUi() {
// Set allowFullScreenIntent=true to indicate that we *should*
// launch the incoming call UI if necessary.
updateInCallNotification(true);
}
/**
* Helper method for updateInCallNotification() and
* updateNotificationAndLaunchIncomingCallUi(): Update the phone app's
* status bar notification based on the current telephony state, or
* cancels the notification if the phone is totally idle.
*
* @param allowLaunchInCallScreen If true, *and* an incoming call is
* ringing, the notification will include a "fullScreenIntent"
* pointing at the InCallScreen (which will cause the InCallScreen
* to be launched.)
* Watch out: This should be set to true *only* when directly
* handling the "new ringing connection" event from the telephony
* layer (see updateNotificationAndLaunchIncomingCallUi().)
*/
private void updateInCallNotification(boolean allowFullScreenIntent) {
int resId;
if (DBG) log("updateInCallNotification(allowFullScreenIntent = "
+ allowFullScreenIntent + ")...");
// Never display the "ongoing call" notification on
// non-voice-capable devices, even if the phone is actually
// offhook (like during a non-interactive OTASP call.)
if (!PhoneApp.sVoiceCapable) {
if (DBG) log("- non-voice-capable device; suppressing notification.");
return;
}
// If the phone is idle, completely clean up all call-related
// notifications.
if (mCM.getState() == Phone.State.IDLE) {
cancelInCall();
cancelMute();
cancelSpeakerphone();
return;
}
final boolean hasRingingCall = mCM.hasActiveRingingCall();
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
if (DBG) {
log(" - hasRingingCall = " + hasRingingCall);
log(" - hasActiveCall = " + hasActiveCall);
log(" - hasHoldingCall = " + hasHoldingCall);
}
// Suppress the in-call notification if the the InCallScreen is the
// foreground activity, since it's already obvious that you're on a
// call. (The status bar icon is needed only if you navigate *away*
// from the in-call UI.)
//
// But *never* do this if there's an incoming ringing call: We need the
// in-call notification to actually launch the incoming call UI in the
// first place (see notification.fullScreenIntent below) and we can't
// safely assume that the InCallScreen will never be in the foreground
// when a new incoming call comes in.
if (mApp.isShowingCallScreen() && !hasRingingCall) {
cancelInCall();
return;
}
// Display the appropriate icon in the status bar,
// based on the current phone and/or bluetooth state.
boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState();
if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy);
if (hasRingingCall) {
// There's an incoming ringing call.
resId = R.drawable.stat_sys_phone_call_ringing;
} else if (!hasActiveCall && hasHoldingCall) {
// There's only one call, and it's on hold.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_on_hold;
} else {
resId = R.drawable.stat_sys_phone_call_on_hold;
}
} else if (mApp.showBluetoothIndication()) {
// Bluetooth is active.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_bluetooth;
} else {
resId = R.drawable.stat_sys_phone_call_bluetooth;
}
} else {
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call;
} else {
resId = R.drawable.stat_sys_phone_call;
}
}
// Note we can't just bail out now if (resId == mInCallResId),
// since even if the status icon hasn't changed, some *other*
// notification-related info may be different from the last time
// we were here (like the caller-id info of the foreground call,
// if the user swapped calls...)
if (DBG) log("- Updating status bar icon: resId = " + resId);
mInCallResId = resId;
// The icon in the expanded view is the same as in the status bar.
int expandedViewIcon = mInCallResId;
// Even if both lines are in use, we only show a single item in
// the expanded Notifications UI. It's labeled "Ongoing call"
// (or "On hold" if there's only one call, and it's on hold.)
// Also, we don't have room to display caller-id info from two
// different calls. So if both lines are in use, display info
// from the foreground call. And if there's a ringing call,
// display that regardless of the state of the other calls.
Call currentCall;
if (hasRingingCall) {
currentCall = mCM.getFirstActiveRingingCall();
} else if (hasActiveCall) {
currentCall = mCM.getActiveFgCall();
} else {
currentCall = mCM.getFirstActiveBgCall();
}
Connection currentConn = currentCall.getEarliestConnection();
Notification notification = new Notification();
notification.icon = mInCallResId;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// PendingIntent that can be used to launch the InCallScreen. The
// system fires off this intent if the user pulls down the windowshade
// and clicks the notification's expanded view. It's also used to
// launch the InCallScreen immediately when when there's an incoming
// call (see the "fullScreenIntent" field below).
PendingIntent inCallPendingIntent =
PendingIntent.getActivity(mContext, 0,
PhoneApp.createInCallIntent(), 0);
notification.contentIntent = inCallPendingIntent;
// When expanded, the "Ongoing call" notification is (visually)
// different from most other Notifications, so we need to use a
// custom view hierarchy.
// Our custom view, which includes an icon (either "ongoing call" or
// "on hold") and 2 lines of text: (1) the label (either "ongoing
// call" with time counter, or "on hold), and (2) the compact name of
// the current Connection.
RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
R.layout.ongoing_call_notification);
contentView.setImageViewResource(R.id.icon, expandedViewIcon);
// if the connection is valid, then build what we need for the
// first line of notification information, and start the chronometer.
// Otherwise, don't bother and just stick with line 2.
if (currentConn != null) {
// Determine the "start time" of the current connection, in terms
// of the SystemClock.elapsedRealtime() timebase (which is what
// the Chronometer widget needs.)
// We can't use currentConn.getConnectTime(), because (1) that's
// in the currentTimeMillis() time base, and (2) it's zero when
// the phone first goes off hook, since the getConnectTime counter
// doesn't start until the DIALING -> ACTIVE transition.
// Instead we start with the current connection's duration,
// and translate that into the elapsedRealtime() timebase.
long callDurationMsec = currentConn.getDurationMillis();
long chronometerBaseTime = SystemClock.elapsedRealtime() - callDurationMsec;
// Line 1 of the expanded view (in bold text):
String expandedViewLine1;
if (hasRingingCall) {
// Incoming call is ringing.
// Note this isn't a format string! (We want "Incoming call"
// here, not "Incoming call (1:23)".) But that's OK; if you
// call String.format() with more arguments than format
// specifiers, the extra arguments are ignored.
expandedViewLine1 = mContext.getString(R.string.notification_incoming_call);
} else if (hasHoldingCall && !hasActiveCall) {
// Only one call, and it's on hold.
// Note this isn't a format string either (see comment above.)
expandedViewLine1 = mContext.getString(R.string.notification_on_hold);
} else {
// Normal ongoing call.
// Format string with a "%s" where the current call time should go.
expandedViewLine1 = mContext.getString(R.string.notification_ongoing_call_format);
}
if (DBG) log("- Updating expanded view: line 1 '" + /*expandedViewLine1*/ "xxxxxxx" + "'");
// Text line #1 is actually a Chronometer, not a plain TextView.
// We format the elapsed time of the current call into a line like
// "Ongoing call (01:23)".
contentView.setChronometer(R.id.text1,
chronometerBaseTime,
expandedViewLine1,
true);
} else if (DBG) {
Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1.");
}
// display conference call string if this call is a conference
// call, otherwise display the connection information.
// Line 2 of the expanded view (smaller text). This is usually a
// contact name or phone number.
String expandedViewLine2 = "";
// TODO: it may not make sense for every point to make separate
// checks for isConferenceCall, so we need to think about
// possibly including this in startGetCallerInfo or some other
// common point.
if (PhoneUtils.isConferenceCall(currentCall)) {
// if this is a conference call, just use that as the caller name.
expandedViewLine2 = mContext.getString(R.string.card_title_conf_call);
} else {
// If necessary, start asynchronous query to do the caller-id lookup.
PhoneUtils.CallerInfoToken cit =
PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this);
expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext);
// Note: For an incoming call, the very first time we get here we
// won't have a contact name yet, since we only just started the
// caller-id query. So expandedViewLine2 will start off as a raw
// phone number, but we'll update it very quickly when the query
// completes (see onQueryComplete() below.)
}
if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'");
- contentView.setTextViewText(R.id.text2, expandedViewLine2);
+ contentView.setTextViewText(R.id.title, expandedViewLine2);
notification.contentView = contentView;
// TODO: We also need to *update* this notification in some cases,
// like when a call ends on one line but the other is still in use
// (ie. make sure the caller info here corresponds to the active
// line), and maybe even when the user swaps calls (ie. if we only
// show info here for the "current active call".)
// Activate a couple of special Notification features if an
// incoming call is ringing:
if (hasRingingCall) {
if (DBG) log("- Using hi-pri notification for ringing call!");
// This is a high-priority event that should be shown even if the
// status bar is hidden or if an immersive activity is running.
notification.flags |= Notification.FLAG_HIGH_PRIORITY;
// If an immersive activity is running, we have room for a single
// line of text in the small notification popup window.
// We use expandedViewLine2 for this (i.e. the name or number of
// the incoming caller), since that's more relevant than
// expandedViewLine1 (which is something generic like "Incoming
// call".)
notification.tickerText = expandedViewLine2;
if (allowFullScreenIntent) {
// Ok, we actually want to launch the incoming call
// UI at this point (in addition to simply posting a notification
// to the status bar). Setting fullScreenIntent will cause
// the InCallScreen to be launched immediately *unless* the
// current foreground activity is marked as "immersive".
if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent);
notification.fullScreenIntent = inCallPendingIntent;
// Ugly hack alert:
//
// The NotificationManager has the (undocumented) behavior
// that it will *ignore* the fullScreenIntent field if you
// post a new Notification that matches the ID of one that's
// already active. Unfortunately this is exactly what happens
// when you get an incoming call-waiting call: the
// "ongoing call" notification is already visible, so the
// InCallScreen won't get launched in this case!
// (The result: if you bail out of the in-call UI while on a
// call and then get a call-waiting call, the incoming call UI
// won't come up automatically.)
//
// The workaround is to just notice this exact case (this is a
// call-waiting call *and* the InCallScreen is not in the
// foreground) and manually cancel the in-call notification
// before (re)posting it.
//
// TODO: there should be a cleaner way of avoiding this
// problem (see discussion in bug 3184149.)
Call ringingCall = mCM.getFirstActiveRingingCall();
if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) {
Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch...");
// Cancel the IN_CALL_NOTIFICATION immediately before
// (re)posting it; this seems to force the
// NotificationManager to launch the fullScreenIntent.
mNotificationManager.cancel(IN_CALL_NOTIFICATION);
}
}
}
if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification);
mNotificationManager.notify(IN_CALL_NOTIFICATION,
notification);
// Finally, refresh the mute and speakerphone notifications (since
// some phone state changes can indirectly affect the mute and/or
// speaker state).
updateSpeakerNotification();
updateMuteNotification();
}
/**
* Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
* refreshes the contentView when called.
*/
public void onQueryComplete(int token, Object cookie, CallerInfo ci){
if (DBG) log("CallerInfo query complete (for NotificationMgr), "
+ "updating in-call notification..");
if (DBG) log("- cookie: " + cookie);
if (DBG) log("- ci: " + ci);
if (cookie == this) {
// Ok, this is the caller-id query we fired off in
// updateInCallNotification(), presumably when an incoming call
// first appeared. If the caller-id info matched any contacts,
// compactName should now be a real person name rather than a raw
// phone number:
if (DBG) log("- compactName is now: "
+ PhoneUtils.getCompactNameFromCallerInfo(ci, mContext));
// Now that our CallerInfo object has been fully filled-in,
// refresh the in-call notification.
if (DBG) log("- updating notification after query complete...");
updateInCallNotification();
} else {
Log.w(LOG_TAG, "onQueryComplete: caller-id query from unknown source! "
+ "cookie = " + cookie);
}
}
/**
* Take down the in-call notification.
* @see updateInCallNotification()
*/
private void cancelInCall() {
if (DBG) log("cancelInCall()...");
mNotificationManager.cancel(IN_CALL_NOTIFICATION);
mInCallResId = 0;
}
/**
* Completely take down the in-call notification *and* the mute/speaker
* notifications as well, to indicate that the phone is now idle.
*/
/* package */ void cancelCallInProgressNotifications() {
if (DBG) log("cancelCallInProgressNotifications()...");
if (mInCallResId == 0) {
return;
}
if (DBG) log("cancelCallInProgressNotifications: " + mInCallResId);
cancelInCall();
cancelMute();
cancelSpeakerphone();
}
/**
* Updates the message waiting indicator (voicemail) notification.
*
* @param visible true if there are messages waiting
*/
/* package */ void updateMwi(boolean visible) {
if (DBG) log("updateMwi(): " + visible);
if (visible) {
int resId = android.R.drawable.stat_notify_voicemail;
// This Notification can get a lot fancier once we have more
// information about the current voicemail messages.
// (For example, the current voicemail system can't tell
// us the caller-id or timestamp of a message, or tell us the
// message count.)
// But for now, the UI is ultra-simple: if the MWI indication
// is supposed to be visible, just show a single generic
// notification.
String notificationTitle = mContext.getString(R.string.notification_voicemail_title);
String vmNumber = mPhone.getVoiceMailNumber();
if (DBG) log("- got vm number: '" + vmNumber + "'");
// Watch out: vmNumber may be null, for two possible reasons:
//
// (1) This phone really has no voicemail number
//
// (2) This phone *does* have a voicemail number, but
// the SIM isn't ready yet.
//
// Case (2) *does* happen in practice if you have voicemail
// messages when the device first boots: we get an MWI
// notification as soon as we register on the network, but the
// SIM hasn't finished loading yet.
//
// So handle case (2) by retrying the lookup after a short
// delay.
if ((vmNumber == null) && !mPhone.getIccRecordsLoaded()) {
if (DBG) log("- Null vm number: SIM records not loaded (yet)...");
// TODO: rather than retrying after an arbitrary delay, it
// would be cleaner to instead just wait for a
// SIM_RECORDS_LOADED notification.
// (Unfortunately right now there's no convenient way to
// get that notification in phone app code. We'd first
// want to add a call like registerForSimRecordsLoaded()
// to Phone.java and GSMPhone.java, and *then* we could
// listen for that in the CallNotifier class.)
// Limit the number of retries (in case the SIM is broken
// or missing and can *never* load successfully.)
if (mVmNumberRetriesRemaining-- > 0) {
if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec...");
mApp.notifier.sendMwiChangedDelayed(VM_NUMBER_RETRY_DELAY_MILLIS);
return;
} else {
Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after "
+ MAX_VM_NUMBER_RETRIES + " retries; giving up.");
// ...and continue with vmNumber==null, just as if the
// phone had no VM number set up in the first place.
}
}
if (TelephonyCapabilities.supportsVoiceMessageCount(mPhone)) {
int vmCount = mPhone.getVoiceMessageCount();
String titleFormat = mContext.getString(R.string.notification_voicemail_title_count);
notificationTitle = String.format(titleFormat, vmCount);
}
String notificationText;
if (TextUtils.isEmpty(vmNumber)) {
notificationText = mContext.getString(
R.string.notification_voicemail_no_vm_number);
} else {
notificationText = String.format(
mContext.getString(R.string.notification_voicemail_text_format),
PhoneNumberUtils.formatNumber(vmNumber));
}
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.fromParts(Constants.SCHEME_VOICEMAIL, "", null));
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Notification notification = new Notification(
resId, // icon
null, // tickerText
System.currentTimeMillis() // Show the time the MWI notification came in,
// since we don't know the actual time of the
// most recent voicemail message
);
notification.setLatestEventInfo(
mContext, // context
notificationTitle, // contentTitle
notificationText, // contentText
pendingIntent // contentIntent
);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_NO_CLEAR;
configureLedNotification(notification);
mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification);
} else {
mNotificationManager.cancel(VOICEMAIL_NOTIFICATION);
}
}
/**
* Updates the message call forwarding indicator notification.
*
* @param visible true if there are messages waiting
*/
/* package */ void updateCfi(boolean visible) {
if (DBG) log("updateCfi(): " + visible);
if (visible) {
// If Unconditional Call Forwarding (forward all calls) for VOICE
// is enabled, just show a notification. We'll default to expanded
// view for now, so the there is less confusion about the icon. If
// it is deemed too weird to have CF indications as expanded views,
// then we'll flip the flag back.
// TODO: We may want to take a look to see if the notification can
// display the target to forward calls to. This will require some
// effort though, since there are multiple layers of messages that
// will need to propagate that information.
Notification notification;
final boolean showExpandedNotification = true;
if (showExpandedNotification) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.android.phone",
"com.android.phone.CallFeaturesSetting");
notification = new Notification(
R.drawable.stat_sys_phone_call_forward, // icon
null, // tickerText
0); // The "timestamp" of this notification is meaningless;
// we only care about whether CFI is currently on or not.
notification.setLatestEventInfo(
mContext, // context
mContext.getString(R.string.labelCF), // expandedTitle
mContext.getString(R.string.sum_cfu_enabled_indicator), // expandedText
PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
} else {
notification = new Notification(
R.drawable.stat_sys_phone_call_forward, // icon
null, // tickerText
System.currentTimeMillis() // when
);
}
notification.flags |= Notification.FLAG_ONGOING_EVENT; // also implies FLAG_NO_CLEAR
mNotificationManager.notify(
CALL_FORWARD_NOTIFICATION,
notification);
} else {
mNotificationManager.cancel(CALL_FORWARD_NOTIFICATION);
}
}
/**
* Shows the "data disconnected due to roaming" notification, which
* appears when you lose data connectivity because you're roaming and
* you have the "data roaming" feature turned off.
*/
/* package */ void showDataDisconnectedRoaming() {
if (DBG) log("showDataDisconnectedRoaming()...");
Intent intent = new Intent(mContext,
com.android.phone.Settings.class); // "Mobile network settings" screen / dialog
Notification notification = new Notification(
android.R.drawable.stat_sys_warning, // icon
null, // tickerText
System.currentTimeMillis());
notification.setLatestEventInfo(
mContext, // Context
mContext.getString(R.string.roaming), // expandedTitle
mContext.getString(R.string.roaming_reenable_message), // expandedText
PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent
mNotificationManager.notify(
DATA_DISCONNECTED_ROAMING_NOTIFICATION,
notification);
}
/**
* Turns off the "data disconnected due to roaming" notification.
*/
/* package */ void hideDataDisconnectedRoaming() {
if (DBG) log("hideDataDisconnectedRoaming()...");
mNotificationManager.cancel(DATA_DISCONNECTED_ROAMING_NOTIFICATION);
}
/**
* Display the network selection "no service" notification
* @param operator is the numeric operator number
*/
private void showNetworkSelection(String operator) {
if (DBG) log("showNetworkSelection(" + operator + ")...");
String titleText = mContext.getString(
R.string.notification_network_selection_title);
String expandedText = mContext.getString(
R.string.notification_network_selection_text, operator);
Notification notification = new Notification();
notification.icon = android.R.drawable.stat_sys_warning;
notification.when = 0;
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.tickerText = null;
// create the target network operators settings intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// Use NetworkSetting to handle the selection intent
intent.setComponent(new ComponentName("com.android.phone",
"com.android.phone.NetworkSetting"));
PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
notification.setLatestEventInfo(mContext, titleText, expandedText, pi);
mNotificationManager.notify(SELECTED_OPERATOR_FAIL_NOTIFICATION, notification);
}
/**
* Turn off the network selection "no service" notification
*/
private void cancelNetworkSelection() {
if (DBG) log("cancelNetworkSelection()...");
mNotificationManager.cancel(SELECTED_OPERATOR_FAIL_NOTIFICATION);
}
/**
* Update notification about no service of user selected operator
*
* @param serviceState Phone service state
*/
void updateNetworkSelection(int serviceState) {
if (TelephonyCapabilities.supportsNetworkSelection(mPhone)) {
// get the shared preference of network_selection.
// empty is auto mode, otherwise it is the operator alpha name
// in case there is no operator name, check the operator numeric
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(mContext);
String networkSelection =
sp.getString(PhoneBase.NETWORK_SELECTION_NAME_KEY, "");
if (TextUtils.isEmpty(networkSelection)) {
networkSelection =
sp.getString(PhoneBase.NETWORK_SELECTION_KEY, "");
}
if (DBG) log("updateNetworkSelection()..." + "state = " +
serviceState + " new network " + networkSelection);
if (serviceState == ServiceState.STATE_OUT_OF_SERVICE
&& !TextUtils.isEmpty(networkSelection)) {
if (!mSelectedUnavailableNotify) {
showNetworkSelection(networkSelection);
mSelectedUnavailableNotify = true;
}
} else {
if (mSelectedUnavailableNotify) {
cancelNetworkSelection();
mSelectedUnavailableNotify = false;
}
}
}
}
/* package */ void postTransientNotification(int notifyId, CharSequence msg) {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
mToast.show();
}
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| true | true |
private void updateInCallNotification(boolean allowFullScreenIntent) {
int resId;
if (DBG) log("updateInCallNotification(allowFullScreenIntent = "
+ allowFullScreenIntent + ")...");
// Never display the "ongoing call" notification on
// non-voice-capable devices, even if the phone is actually
// offhook (like during a non-interactive OTASP call.)
if (!PhoneApp.sVoiceCapable) {
if (DBG) log("- non-voice-capable device; suppressing notification.");
return;
}
// If the phone is idle, completely clean up all call-related
// notifications.
if (mCM.getState() == Phone.State.IDLE) {
cancelInCall();
cancelMute();
cancelSpeakerphone();
return;
}
final boolean hasRingingCall = mCM.hasActiveRingingCall();
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
if (DBG) {
log(" - hasRingingCall = " + hasRingingCall);
log(" - hasActiveCall = " + hasActiveCall);
log(" - hasHoldingCall = " + hasHoldingCall);
}
// Suppress the in-call notification if the the InCallScreen is the
// foreground activity, since it's already obvious that you're on a
// call. (The status bar icon is needed only if you navigate *away*
// from the in-call UI.)
//
// But *never* do this if there's an incoming ringing call: We need the
// in-call notification to actually launch the incoming call UI in the
// first place (see notification.fullScreenIntent below) and we can't
// safely assume that the InCallScreen will never be in the foreground
// when a new incoming call comes in.
if (mApp.isShowingCallScreen() && !hasRingingCall) {
cancelInCall();
return;
}
// Display the appropriate icon in the status bar,
// based on the current phone and/or bluetooth state.
boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState();
if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy);
if (hasRingingCall) {
// There's an incoming ringing call.
resId = R.drawable.stat_sys_phone_call_ringing;
} else if (!hasActiveCall && hasHoldingCall) {
// There's only one call, and it's on hold.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_on_hold;
} else {
resId = R.drawable.stat_sys_phone_call_on_hold;
}
} else if (mApp.showBluetoothIndication()) {
// Bluetooth is active.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_bluetooth;
} else {
resId = R.drawable.stat_sys_phone_call_bluetooth;
}
} else {
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call;
} else {
resId = R.drawable.stat_sys_phone_call;
}
}
// Note we can't just bail out now if (resId == mInCallResId),
// since even if the status icon hasn't changed, some *other*
// notification-related info may be different from the last time
// we were here (like the caller-id info of the foreground call,
// if the user swapped calls...)
if (DBG) log("- Updating status bar icon: resId = " + resId);
mInCallResId = resId;
// The icon in the expanded view is the same as in the status bar.
int expandedViewIcon = mInCallResId;
// Even if both lines are in use, we only show a single item in
// the expanded Notifications UI. It's labeled "Ongoing call"
// (or "On hold" if there's only one call, and it's on hold.)
// Also, we don't have room to display caller-id info from two
// different calls. So if both lines are in use, display info
// from the foreground call. And if there's a ringing call,
// display that regardless of the state of the other calls.
Call currentCall;
if (hasRingingCall) {
currentCall = mCM.getFirstActiveRingingCall();
} else if (hasActiveCall) {
currentCall = mCM.getActiveFgCall();
} else {
currentCall = mCM.getFirstActiveBgCall();
}
Connection currentConn = currentCall.getEarliestConnection();
Notification notification = new Notification();
notification.icon = mInCallResId;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// PendingIntent that can be used to launch the InCallScreen. The
// system fires off this intent if the user pulls down the windowshade
// and clicks the notification's expanded view. It's also used to
// launch the InCallScreen immediately when when there's an incoming
// call (see the "fullScreenIntent" field below).
PendingIntent inCallPendingIntent =
PendingIntent.getActivity(mContext, 0,
PhoneApp.createInCallIntent(), 0);
notification.contentIntent = inCallPendingIntent;
// When expanded, the "Ongoing call" notification is (visually)
// different from most other Notifications, so we need to use a
// custom view hierarchy.
// Our custom view, which includes an icon (either "ongoing call" or
// "on hold") and 2 lines of text: (1) the label (either "ongoing
// call" with time counter, or "on hold), and (2) the compact name of
// the current Connection.
RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
R.layout.ongoing_call_notification);
contentView.setImageViewResource(R.id.icon, expandedViewIcon);
// if the connection is valid, then build what we need for the
// first line of notification information, and start the chronometer.
// Otherwise, don't bother and just stick with line 2.
if (currentConn != null) {
// Determine the "start time" of the current connection, in terms
// of the SystemClock.elapsedRealtime() timebase (which is what
// the Chronometer widget needs.)
// We can't use currentConn.getConnectTime(), because (1) that's
// in the currentTimeMillis() time base, and (2) it's zero when
// the phone first goes off hook, since the getConnectTime counter
// doesn't start until the DIALING -> ACTIVE transition.
// Instead we start with the current connection's duration,
// and translate that into the elapsedRealtime() timebase.
long callDurationMsec = currentConn.getDurationMillis();
long chronometerBaseTime = SystemClock.elapsedRealtime() - callDurationMsec;
// Line 1 of the expanded view (in bold text):
String expandedViewLine1;
if (hasRingingCall) {
// Incoming call is ringing.
// Note this isn't a format string! (We want "Incoming call"
// here, not "Incoming call (1:23)".) But that's OK; if you
// call String.format() with more arguments than format
// specifiers, the extra arguments are ignored.
expandedViewLine1 = mContext.getString(R.string.notification_incoming_call);
} else if (hasHoldingCall && !hasActiveCall) {
// Only one call, and it's on hold.
// Note this isn't a format string either (see comment above.)
expandedViewLine1 = mContext.getString(R.string.notification_on_hold);
} else {
// Normal ongoing call.
// Format string with a "%s" where the current call time should go.
expandedViewLine1 = mContext.getString(R.string.notification_ongoing_call_format);
}
if (DBG) log("- Updating expanded view: line 1 '" + /*expandedViewLine1*/ "xxxxxxx" + "'");
// Text line #1 is actually a Chronometer, not a plain TextView.
// We format the elapsed time of the current call into a line like
// "Ongoing call (01:23)".
contentView.setChronometer(R.id.text1,
chronometerBaseTime,
expandedViewLine1,
true);
} else if (DBG) {
Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1.");
}
// display conference call string if this call is a conference
// call, otherwise display the connection information.
// Line 2 of the expanded view (smaller text). This is usually a
// contact name or phone number.
String expandedViewLine2 = "";
// TODO: it may not make sense for every point to make separate
// checks for isConferenceCall, so we need to think about
// possibly including this in startGetCallerInfo or some other
// common point.
if (PhoneUtils.isConferenceCall(currentCall)) {
// if this is a conference call, just use that as the caller name.
expandedViewLine2 = mContext.getString(R.string.card_title_conf_call);
} else {
// If necessary, start asynchronous query to do the caller-id lookup.
PhoneUtils.CallerInfoToken cit =
PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this);
expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext);
// Note: For an incoming call, the very first time we get here we
// won't have a contact name yet, since we only just started the
// caller-id query. So expandedViewLine2 will start off as a raw
// phone number, but we'll update it very quickly when the query
// completes (see onQueryComplete() below.)
}
if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'");
contentView.setTextViewText(R.id.text2, expandedViewLine2);
notification.contentView = contentView;
// TODO: We also need to *update* this notification in some cases,
// like when a call ends on one line but the other is still in use
// (ie. make sure the caller info here corresponds to the active
// line), and maybe even when the user swaps calls (ie. if we only
// show info here for the "current active call".)
// Activate a couple of special Notification features if an
// incoming call is ringing:
if (hasRingingCall) {
if (DBG) log("- Using hi-pri notification for ringing call!");
// This is a high-priority event that should be shown even if the
// status bar is hidden or if an immersive activity is running.
notification.flags |= Notification.FLAG_HIGH_PRIORITY;
// If an immersive activity is running, we have room for a single
// line of text in the small notification popup window.
// We use expandedViewLine2 for this (i.e. the name or number of
// the incoming caller), since that's more relevant than
// expandedViewLine1 (which is something generic like "Incoming
// call".)
notification.tickerText = expandedViewLine2;
if (allowFullScreenIntent) {
// Ok, we actually want to launch the incoming call
// UI at this point (in addition to simply posting a notification
// to the status bar). Setting fullScreenIntent will cause
// the InCallScreen to be launched immediately *unless* the
// current foreground activity is marked as "immersive".
if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent);
notification.fullScreenIntent = inCallPendingIntent;
// Ugly hack alert:
//
// The NotificationManager has the (undocumented) behavior
// that it will *ignore* the fullScreenIntent field if you
// post a new Notification that matches the ID of one that's
// already active. Unfortunately this is exactly what happens
// when you get an incoming call-waiting call: the
// "ongoing call" notification is already visible, so the
// InCallScreen won't get launched in this case!
// (The result: if you bail out of the in-call UI while on a
// call and then get a call-waiting call, the incoming call UI
// won't come up automatically.)
//
// The workaround is to just notice this exact case (this is a
// call-waiting call *and* the InCallScreen is not in the
// foreground) and manually cancel the in-call notification
// before (re)posting it.
//
// TODO: there should be a cleaner way of avoiding this
// problem (see discussion in bug 3184149.)
Call ringingCall = mCM.getFirstActiveRingingCall();
if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) {
Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch...");
// Cancel the IN_CALL_NOTIFICATION immediately before
// (re)posting it; this seems to force the
// NotificationManager to launch the fullScreenIntent.
mNotificationManager.cancel(IN_CALL_NOTIFICATION);
}
}
}
if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification);
mNotificationManager.notify(IN_CALL_NOTIFICATION,
notification);
// Finally, refresh the mute and speakerphone notifications (since
// some phone state changes can indirectly affect the mute and/or
// speaker state).
updateSpeakerNotification();
updateMuteNotification();
}
|
private void updateInCallNotification(boolean allowFullScreenIntent) {
int resId;
if (DBG) log("updateInCallNotification(allowFullScreenIntent = "
+ allowFullScreenIntent + ")...");
// Never display the "ongoing call" notification on
// non-voice-capable devices, even if the phone is actually
// offhook (like during a non-interactive OTASP call.)
if (!PhoneApp.sVoiceCapable) {
if (DBG) log("- non-voice-capable device; suppressing notification.");
return;
}
// If the phone is idle, completely clean up all call-related
// notifications.
if (mCM.getState() == Phone.State.IDLE) {
cancelInCall();
cancelMute();
cancelSpeakerphone();
return;
}
final boolean hasRingingCall = mCM.hasActiveRingingCall();
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
if (DBG) {
log(" - hasRingingCall = " + hasRingingCall);
log(" - hasActiveCall = " + hasActiveCall);
log(" - hasHoldingCall = " + hasHoldingCall);
}
// Suppress the in-call notification if the the InCallScreen is the
// foreground activity, since it's already obvious that you're on a
// call. (The status bar icon is needed only if you navigate *away*
// from the in-call UI.)
//
// But *never* do this if there's an incoming ringing call: We need the
// in-call notification to actually launch the incoming call UI in the
// first place (see notification.fullScreenIntent below) and we can't
// safely assume that the InCallScreen will never be in the foreground
// when a new incoming call comes in.
if (mApp.isShowingCallScreen() && !hasRingingCall) {
cancelInCall();
return;
}
// Display the appropriate icon in the status bar,
// based on the current phone and/or bluetooth state.
boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState();
if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy);
if (hasRingingCall) {
// There's an incoming ringing call.
resId = R.drawable.stat_sys_phone_call_ringing;
} else if (!hasActiveCall && hasHoldingCall) {
// There's only one call, and it's on hold.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_on_hold;
} else {
resId = R.drawable.stat_sys_phone_call_on_hold;
}
} else if (mApp.showBluetoothIndication()) {
// Bluetooth is active.
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call_bluetooth;
} else {
resId = R.drawable.stat_sys_phone_call_bluetooth;
}
} else {
if (enhancedVoicePrivacy) {
resId = R.drawable.stat_sys_vp_phone_call;
} else {
resId = R.drawable.stat_sys_phone_call;
}
}
// Note we can't just bail out now if (resId == mInCallResId),
// since even if the status icon hasn't changed, some *other*
// notification-related info may be different from the last time
// we were here (like the caller-id info of the foreground call,
// if the user swapped calls...)
if (DBG) log("- Updating status bar icon: resId = " + resId);
mInCallResId = resId;
// The icon in the expanded view is the same as in the status bar.
int expandedViewIcon = mInCallResId;
// Even if both lines are in use, we only show a single item in
// the expanded Notifications UI. It's labeled "Ongoing call"
// (or "On hold" if there's only one call, and it's on hold.)
// Also, we don't have room to display caller-id info from two
// different calls. So if both lines are in use, display info
// from the foreground call. And if there's a ringing call,
// display that regardless of the state of the other calls.
Call currentCall;
if (hasRingingCall) {
currentCall = mCM.getFirstActiveRingingCall();
} else if (hasActiveCall) {
currentCall = mCM.getActiveFgCall();
} else {
currentCall = mCM.getFirstActiveBgCall();
}
Connection currentConn = currentCall.getEarliestConnection();
Notification notification = new Notification();
notification.icon = mInCallResId;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// PendingIntent that can be used to launch the InCallScreen. The
// system fires off this intent if the user pulls down the windowshade
// and clicks the notification's expanded view. It's also used to
// launch the InCallScreen immediately when when there's an incoming
// call (see the "fullScreenIntent" field below).
PendingIntent inCallPendingIntent =
PendingIntent.getActivity(mContext, 0,
PhoneApp.createInCallIntent(), 0);
notification.contentIntent = inCallPendingIntent;
// When expanded, the "Ongoing call" notification is (visually)
// different from most other Notifications, so we need to use a
// custom view hierarchy.
// Our custom view, which includes an icon (either "ongoing call" or
// "on hold") and 2 lines of text: (1) the label (either "ongoing
// call" with time counter, or "on hold), and (2) the compact name of
// the current Connection.
RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
R.layout.ongoing_call_notification);
contentView.setImageViewResource(R.id.icon, expandedViewIcon);
// if the connection is valid, then build what we need for the
// first line of notification information, and start the chronometer.
// Otherwise, don't bother and just stick with line 2.
if (currentConn != null) {
// Determine the "start time" of the current connection, in terms
// of the SystemClock.elapsedRealtime() timebase (which is what
// the Chronometer widget needs.)
// We can't use currentConn.getConnectTime(), because (1) that's
// in the currentTimeMillis() time base, and (2) it's zero when
// the phone first goes off hook, since the getConnectTime counter
// doesn't start until the DIALING -> ACTIVE transition.
// Instead we start with the current connection's duration,
// and translate that into the elapsedRealtime() timebase.
long callDurationMsec = currentConn.getDurationMillis();
long chronometerBaseTime = SystemClock.elapsedRealtime() - callDurationMsec;
// Line 1 of the expanded view (in bold text):
String expandedViewLine1;
if (hasRingingCall) {
// Incoming call is ringing.
// Note this isn't a format string! (We want "Incoming call"
// here, not "Incoming call (1:23)".) But that's OK; if you
// call String.format() with more arguments than format
// specifiers, the extra arguments are ignored.
expandedViewLine1 = mContext.getString(R.string.notification_incoming_call);
} else if (hasHoldingCall && !hasActiveCall) {
// Only one call, and it's on hold.
// Note this isn't a format string either (see comment above.)
expandedViewLine1 = mContext.getString(R.string.notification_on_hold);
} else {
// Normal ongoing call.
// Format string with a "%s" where the current call time should go.
expandedViewLine1 = mContext.getString(R.string.notification_ongoing_call_format);
}
if (DBG) log("- Updating expanded view: line 1 '" + /*expandedViewLine1*/ "xxxxxxx" + "'");
// Text line #1 is actually a Chronometer, not a plain TextView.
// We format the elapsed time of the current call into a line like
// "Ongoing call (01:23)".
contentView.setChronometer(R.id.text1,
chronometerBaseTime,
expandedViewLine1,
true);
} else if (DBG) {
Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1.");
}
// display conference call string if this call is a conference
// call, otherwise display the connection information.
// Line 2 of the expanded view (smaller text). This is usually a
// contact name or phone number.
String expandedViewLine2 = "";
// TODO: it may not make sense for every point to make separate
// checks for isConferenceCall, so we need to think about
// possibly including this in startGetCallerInfo or some other
// common point.
if (PhoneUtils.isConferenceCall(currentCall)) {
// if this is a conference call, just use that as the caller name.
expandedViewLine2 = mContext.getString(R.string.card_title_conf_call);
} else {
// If necessary, start asynchronous query to do the caller-id lookup.
PhoneUtils.CallerInfoToken cit =
PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this);
expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext);
// Note: For an incoming call, the very first time we get here we
// won't have a contact name yet, since we only just started the
// caller-id query. So expandedViewLine2 will start off as a raw
// phone number, but we'll update it very quickly when the query
// completes (see onQueryComplete() below.)
}
if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'");
contentView.setTextViewText(R.id.title, expandedViewLine2);
notification.contentView = contentView;
// TODO: We also need to *update* this notification in some cases,
// like when a call ends on one line but the other is still in use
// (ie. make sure the caller info here corresponds to the active
// line), and maybe even when the user swaps calls (ie. if we only
// show info here for the "current active call".)
// Activate a couple of special Notification features if an
// incoming call is ringing:
if (hasRingingCall) {
if (DBG) log("- Using hi-pri notification for ringing call!");
// This is a high-priority event that should be shown even if the
// status bar is hidden or if an immersive activity is running.
notification.flags |= Notification.FLAG_HIGH_PRIORITY;
// If an immersive activity is running, we have room for a single
// line of text in the small notification popup window.
// We use expandedViewLine2 for this (i.e. the name or number of
// the incoming caller), since that's more relevant than
// expandedViewLine1 (which is something generic like "Incoming
// call".)
notification.tickerText = expandedViewLine2;
if (allowFullScreenIntent) {
// Ok, we actually want to launch the incoming call
// UI at this point (in addition to simply posting a notification
// to the status bar). Setting fullScreenIntent will cause
// the InCallScreen to be launched immediately *unless* the
// current foreground activity is marked as "immersive".
if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent);
notification.fullScreenIntent = inCallPendingIntent;
// Ugly hack alert:
//
// The NotificationManager has the (undocumented) behavior
// that it will *ignore* the fullScreenIntent field if you
// post a new Notification that matches the ID of one that's
// already active. Unfortunately this is exactly what happens
// when you get an incoming call-waiting call: the
// "ongoing call" notification is already visible, so the
// InCallScreen won't get launched in this case!
// (The result: if you bail out of the in-call UI while on a
// call and then get a call-waiting call, the incoming call UI
// won't come up automatically.)
//
// The workaround is to just notice this exact case (this is a
// call-waiting call *and* the InCallScreen is not in the
// foreground) and manually cancel the in-call notification
// before (re)posting it.
//
// TODO: there should be a cleaner way of avoiding this
// problem (see discussion in bug 3184149.)
Call ringingCall = mCM.getFirstActiveRingingCall();
if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) {
Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch...");
// Cancel the IN_CALL_NOTIFICATION immediately before
// (re)posting it; this seems to force the
// NotificationManager to launch the fullScreenIntent.
mNotificationManager.cancel(IN_CALL_NOTIFICATION);
}
}
}
if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification);
mNotificationManager.notify(IN_CALL_NOTIFICATION,
notification);
// Finally, refresh the mute and speakerphone notifications (since
// some phone state changes can indirectly affect the mute and/or
// speaker state).
updateSpeakerNotification();
updateMuteNotification();
}
|
diff --git a/src/com/android/mms/transaction/MessagingNotification.java b/src/com/android/mms/transaction/MessagingNotification.java
index 985f7bc3..664d5f3f 100644
--- a/src/com/android/mms/transaction/MessagingNotification.java
+++ b/src/com/android/mms/transaction/MessagingNotification.java
@@ -1,1548 +1,1549 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* QuickMessage Copyright (C) 2012 The CyanogenMod Project (DvTonder)
*
* 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.transaction;
import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND;
import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.widget.Toast;
import com.android.mms.LogTag;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.Conversation;
import com.android.mms.data.WorkingMessage;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.quickmessage.QmMarkRead;
import com.android.mms.quickmessage.QuickMessagePopup;
import com.android.mms.ui.ComposeMessageActivity;
import com.android.mms.ui.ConversationList;
import com.android.mms.ui.MessageUtils;
import com.android.mms.ui.MessagingPreferenceActivity;
import com.android.mms.util.AddressUtils;
import com.android.mms.util.DownloadManager;
import com.android.mms.widget.MmsWidgetProvider;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.GenericPdu;
import com.google.android.mms.pdu.MultimediaMessagePdu;
import com.google.android.mms.pdu.PduHeaders;
import com.google.android.mms.pdu.PduPersister;
/**
* This class is used to update the notification indicator. It will check whether
* there are unread messages. If yes, it would show the notification indicator,
* otherwise, hide the indicator.
*/
public class MessagingNotification {
private static final String TAG = LogTag.APP;
private static final boolean DEBUG = false;
public static final int NOTIFICATION_ID = 123;
public static final int MESSAGE_FAILED_NOTIFICATION_ID = 789;
public static final int DOWNLOAD_FAILED_NOTIFICATION_ID = 531;
/**
* This is the volume at which to play the in-conversation notification sound,
* expressed as a fraction of the system notification volume.
*/
private static final float IN_CONVERSATION_NOTIFICATION_VOLUME = 0.25f;
// This must be consistent with the column constants below.
private static final String[] MMS_STATUS_PROJECTION = new String[] {
Mms.THREAD_ID, Mms.DATE, Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET };
// This must be consistent with the column constants below.
private static final String[] SMS_STATUS_PROJECTION = new String[] {
Sms.THREAD_ID, Sms.DATE, Sms.ADDRESS, Sms.SUBJECT, Sms.BODY };
// These must be consistent with MMS_STATUS_PROJECTION and
// SMS_STATUS_PROJECTION.
private static final int COLUMN_THREAD_ID = 0;
private static final int COLUMN_DATE = 1;
private static final int COLUMN_MMS_ID = 2;
private static final int COLUMN_SMS_ADDRESS = 2;
private static final int COLUMN_SUBJECT = 3;
private static final int COLUMN_SUBJECT_CS = 4;
private static final int COLUMN_SMS_BODY = 4;
private static final String[] SMS_THREAD_ID_PROJECTION = new String[] { Sms.THREAD_ID };
private static final String[] MMS_THREAD_ID_PROJECTION = new String[] { Mms.THREAD_ID };
private static final String NEW_INCOMING_SM_CONSTRAINT =
"(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_INBOX
+ " AND " + Sms.SEEN + " = 0)";
private static final String NEW_DELIVERY_SM_CONSTRAINT =
"(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_SENT
+ " AND " + Sms.STATUS + " = "+ Sms.STATUS_COMPLETE +")";
private static final String NEW_INCOMING_MM_CONSTRAINT =
"(" + Mms.MESSAGE_BOX + "=" + Mms.MESSAGE_BOX_INBOX
+ " AND " + Mms.SEEN + "=0"
+ " AND (" + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_NOTIFICATION_IND
+ " OR " + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_RETRIEVE_CONF + "))";
private static final NotificationInfoComparator INFO_COMPARATOR =
new NotificationInfoComparator();
private static final Uri UNDELIVERED_URI = Uri.parse("content://mms-sms/undelivered");
private final static String NOTIFICATION_DELETED_ACTION =
"com.android.mms.NOTIFICATION_DELETED_ACTION";
public static class OnDeletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "[MessagingNotification] clear notification: mark all msgs seen");
}
Conversation.markAllConversationsAsSeen(context);
}
}
public static final long THREAD_ALL = -1;
public static final long THREAD_NONE = -2;
/**
* Keeps track of the thread ID of the conversation that's currently displayed to the user
*/
private static long sCurrentlyDisplayedThreadId;
private static final Object sCurrentlyDisplayedThreadLock = new Object();
private static OnDeletedReceiver sNotificationDeletedReceiver = new OnDeletedReceiver();
private static Intent sNotificationOnDeleteIntent;
private static Handler sHandler = new Handler();
private static PduPersister sPduPersister;
private static final int MAX_BITMAP_DIMEN_DP = 360;
private static float sScreenDensity;
private static final int MAX_MESSAGES_TO_SHOW = 8; // the maximum number of new messages to
// show in a single notification.
private MessagingNotification() {
}
public static void init(Context context) {
// set up the intent filter for notification deleted action
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(NOTIFICATION_DELETED_ACTION);
// TODO: should we unregister when the app gets killed?
context.registerReceiver(sNotificationDeletedReceiver, intentFilter);
sPduPersister = PduPersister.getPduPersister(context);
// initialize the notification deleted action
sNotificationOnDeleteIntent = new Intent(NOTIFICATION_DELETED_ACTION);
sScreenDensity = context.getResources().getDisplayMetrics().density;
}
/**
* Specifies which message thread is currently being viewed by the user. New messages in that
* thread will not generate a notification icon and will play the notification sound at a lower
* volume. Make sure you set this to THREAD_NONE when the UI component that shows the thread is
* no longer visible to the user (e.g. Activity.onPause(), etc.)
* @param threadId The ID of the thread that the user is currently viewing. Pass THREAD_NONE
* if the user is not viewing a thread, or THREAD_ALL if the user is viewing the conversation
* list (note: that latter one has no effect as of this implementation)
*/
public static void setCurrentlyDisplayedThreadId(long threadId) {
synchronized (sCurrentlyDisplayedThreadLock) {
sCurrentlyDisplayedThreadId = threadId;
if (DEBUG) {
Log.d(TAG, "setCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId);
}
}
}
/**
* Checks to see if there are any "unseen" messages or delivery
* reports. Shows the most recent notification if there is one.
* Does its work and query in a worker thread.
*
* @param context the context to use
*/
public static void nonBlockingUpdateNewMessageIndicator(final Context context,
final long newMsgThreadId,
final boolean isStatusMessage) {
if (DEBUG) {
Log.d(TAG, "nonBlockingUpdateNewMessageIndicator: newMsgThreadId: " +
newMsgThreadId +
" sCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId);
}
new Thread(new Runnable() {
@Override
public void run() {
blockingUpdateNewMessageIndicator(context, newMsgThreadId, isStatusMessage);
}
}, "MessagingNotification.nonBlockingUpdateNewMessageIndicator").start();
}
/**
* Checks to see if there are any "unseen" messages or delivery
* reports and builds a sorted (by delivery date) list of unread notifications.
*
* @param context the context to use
* @param newMsgThreadId The thread ID of a new message that we're to notify about; if there's
* no new message, use THREAD_NONE. If we should notify about multiple or unknown thread IDs,
* use THREAD_ALL.
* @param isStatusMessage
*/
public static void blockingUpdateNewMessageIndicator(Context context, long newMsgThreadId,
boolean isStatusMessage) {
if (DEBUG) {
Contact.logWithTrace(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId: " +
newMsgThreadId);
}
// notificationSet is kept sorted by the incoming message delivery time, with the
// most recent message first.
SortedSet<NotificationInfo> notificationSet =
new TreeSet<NotificationInfo>(INFO_COMPARATOR);
Set<Long> threads = new HashSet<Long>(4);
addMmsNotificationInfos(context, threads, notificationSet);
addSmsNotificationInfos(context, threads, notificationSet);
if (notificationSet.isEmpty()) {
if (DEBUG) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: notificationSet is empty, " +
"canceling existing notifications");
}
cancelNotification(context, NOTIFICATION_ID);
} else {
if (DEBUG || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + notificationSet.size() +
", newMsgThreadId=" + newMsgThreadId);
}
synchronized (sCurrentlyDisplayedThreadLock) {
if (newMsgThreadId > 0 && newMsgThreadId == sCurrentlyDisplayedThreadId &&
threads.contains(newMsgThreadId)) {
if (DEBUG) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId == " +
"sCurrentlyDisplayedThreadId so NOT showing notification," +
" but playing soft sound. threadId: " + newMsgThreadId);
}
playInConversationNotificationSound(context);
return;
}
}
updateNotification(context, newMsgThreadId != THREAD_NONE, threads.size(),
notificationSet);
}
// And deals with delivery reports (which use Toasts). It's safe to call in a worker
// thread because the toast will eventually get posted to a handler.
MmsSmsDeliveryInfo delivery = getSmsNewDeliveryInfo(context);
if (delivery != null) {
delivery.deliver(context, isStatusMessage);
}
notificationSet.clear();
threads.clear();
}
/**
* Play the in-conversation notification sound (it's the regular notification sound, but
* played at half-volume
*/
private static void playInConversationNotificationSound(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
if (TextUtils.isEmpty(ringtoneStr)) {
// Nothing to play
return;
}
Uri ringtoneUri = Uri.parse(ringtoneStr);
final NotificationPlayer player = new NotificationPlayer(LogTag.APP);
player.play(context, ringtoneUri, false, AudioManager.STREAM_NOTIFICATION,
IN_CONVERSATION_NOTIFICATION_VOLUME);
// Stop the sound after five seconds to handle continuous ringtones
sHandler.postDelayed(new Runnable() {
@Override
public void run() {
player.stop();
}
}, 5000);
}
/**
* Updates all pending notifications, clearing or updating them as
* necessary.
*/
public static void blockingUpdateAllNotifications(final Context context, long threadId) {
if (DEBUG) {
Contact.logWithTrace(TAG, "blockingUpdateAllNotifications: newMsgThreadId: " +
threadId);
}
nonBlockingUpdateNewMessageIndicator(context, threadId, false);
nonBlockingUpdateSendFailedNotification(context);
updateDownloadFailedNotification(context);
MmsWidgetProvider.notifyDatasetChanged(context);
}
private static final class MmsSmsDeliveryInfo {
public CharSequence mTicker;
public long mTimeMillis;
public MmsSmsDeliveryInfo(CharSequence ticker, long timeMillis) {
mTicker = ticker;
mTimeMillis = timeMillis;
}
public void deliver(Context context, boolean isStatusMessage) {
updateDeliveryNotification(
context, isStatusMessage, mTicker, mTimeMillis);
}
}
public static final class NotificationInfo implements Parcelable {
public final Intent mClickIntent;
public final String mMessage;
public final CharSequence mTicker;
public final long mTimeMillis;
public final String mTitle;
public final Bitmap mAttachmentBitmap;
public final Contact mSender;
public final boolean mIsSms;
public final int mAttachmentType;
public final String mSubject;
public final long mThreadId;
/**
* @param isSms true if sms, false if mms
* @param clickIntent where to go when the user taps the notification
* @param message for a single message, this is the message text
* @param subject text of mms subject
* @param ticker text displayed ticker-style across the notification, typically formatted
* as sender: message
* @param timeMillis date the message was received
* @param title for a single message, this is the sender
* @param attachmentBitmap a bitmap of an attachment, such as a picture or video
* @param sender contact of the sender
* @param attachmentType of the mms attachment
* @param threadId thread this message belongs to
*/
public NotificationInfo(boolean isSms,
Intent clickIntent, String message, String subject,
CharSequence ticker, long timeMillis, String title,
Bitmap attachmentBitmap, Contact sender,
int attachmentType, long threadId) {
mIsSms = isSms;
mClickIntent = clickIntent;
mMessage = message;
mSubject = subject;
mTicker = ticker;
mTimeMillis = timeMillis;
mTitle = title;
mAttachmentBitmap = attachmentBitmap;
mSender = sender;
mAttachmentType = attachmentType;
mThreadId = threadId;
}
public long getTime() {
return mTimeMillis;
}
// This is the message string used in bigText and bigPicture notifications.
public CharSequence formatBigMessage(Context context) {
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (!TextUtils.isEmpty(mSubject)) {
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0);
}
if (mAttachmentType > WorkingMessage.TEXT) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append('\n');
}
spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType));
}
if (mMessage != null) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append('\n');
}
spannableStringBuilder.append(mMessage);
}
return spannableStringBuilder;
}
// This is the message string used in each line of an inboxStyle notification.
public CharSequence formatInboxMessage(Context context) {
final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationSubjectText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
final String sender = mSender.getName();
if (!TextUtils.isEmpty(sender)) {
spannableStringBuilder.append(sender);
spannableStringBuilder.setSpan(notificationSenderSpan, 0, sender.length(), 0);
}
String separator = context.getString(R.string.notification_separator);
if (!mIsSms) {
if (!TextUtils.isEmpty(mSubject)) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
int start = spannableStringBuilder.length();
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, start,
start + mSubject.length(), 0);
}
if (mAttachmentType > WorkingMessage.TEXT) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType));
}
}
if (message.length() > 0) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
int start = spannableStringBuilder.length();
spannableStringBuilder.append(message);
spannableStringBuilder.setSpan(notificationSubjectSpan, start,
start + message.length(), 0);
}
return spannableStringBuilder;
}
// This is the summary string used in bigPicture notifications.
public CharSequence formatPictureMessage(Context context) {
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
// Show the subject or the message (if no subject)
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (!TextUtils.isEmpty(mSubject)) {
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0);
}
if (message.length() > 0 && spannableStringBuilder.length() == 0) {
spannableStringBuilder.append(message);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, message.length(), 0);
}
return spannableStringBuilder;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeByte((byte) (mIsSms ? 1 : 0));
arg0.writeParcelable(mClickIntent, 0);
arg0.writeString(mMessage);
arg0.writeString(mSubject);
arg0.writeCharSequence(mTicker);
arg0.writeLong(mTimeMillis);
arg0.writeString(mTitle);
arg0.writeParcelable(mAttachmentBitmap, 0);
arg0.writeInt(mAttachmentType);
arg0.writeLong(mThreadId);
}
public NotificationInfo(Parcel in) {
mIsSms = in.readByte() == 1;
mClickIntent = in.readParcelable(Intent.class.getClassLoader());
mMessage = in.readString();
mSubject = in.readString();
mTicker = in.readCharSequence();
mTimeMillis = in.readLong();
mTitle = in.readString();
mAttachmentBitmap = in.readParcelable(Bitmap.class.getClassLoader());
mSender = null;
mAttachmentType = in.readInt();
mThreadId = in.readLong();
}
public static final Parcelable.Creator<NotificationInfo> CREATOR = new Parcelable.Creator<NotificationInfo>() {
public NotificationInfo createFromParcel(Parcel in) {
return new NotificationInfo(in);
}
public NotificationInfo[] newArray(int size) {
return new NotificationInfo[size];
}
};
}
// Return a formatted string with all the sender names separated by commas.
private static CharSequence formatSenders(Context context,
ArrayList<NotificationInfo> senders) {
final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
String separator = context.getString(R.string.enumeration_comma); // ", "
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int len = senders.size();
for (int i = 0; i < len; i++) {
if (i > 0) {
spannableStringBuilder.append(separator);
}
spannableStringBuilder.append(senders.get(i).mSender.getName());
}
spannableStringBuilder.setSpan(notificationSenderSpan, 0,
spannableStringBuilder.length(), 0);
return spannableStringBuilder;
}
// Return a formatted string with the attachmentType spelled out as a string. For
// no attachment (or just text), return null.
private static CharSequence getAttachmentTypeString(Context context, int attachmentType) {
final TextAppearanceSpan notificationAttachmentSpan = new TextAppearanceSpan(
context, R.style.NotificationSecondaryText);
int id = 0;
switch (attachmentType) {
case WorkingMessage.AUDIO: id = R.string.attachment_audio; break;
case WorkingMessage.VIDEO: id = R.string.attachment_video; break;
case WorkingMessage.SLIDESHOW: id = R.string.attachment_slideshow; break;
case WorkingMessage.IMAGE: id = R.string.attachment_picture; break;
}
if (id > 0) {
final SpannableString spannableString = new SpannableString(context.getString(id));
spannableString.setSpan(notificationAttachmentSpan,
0, spannableString.length(), 0);
return spannableString;
}
return null;
}
/**
*
* Sorts by the time a notification was received in descending order -- newer first.
*
*/
private static final class NotificationInfoComparator
implements Comparator<NotificationInfo> {
@Override
public int compare(
NotificationInfo info1, NotificationInfo info2) {
return Long.signum(info2.getTime() - info1.getTime());
}
}
private static final void addMmsNotificationInfos(
Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) {
ContentResolver resolver = context.getContentResolver();
// This query looks like this when logged:
// I/Database( 147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/
// mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1
// AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc
Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI,
MMS_STATUS_PROJECTION, NEW_INCOMING_MM_CONSTRAINT,
null, Mms.DATE + " desc");
if (cursor == null) {
return;
}
try {
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_MMS_ID);
Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath(
Long.toString(msgId)).build();
String address = AddressUtils.getFrom(context, msgUri);
Contact contact = Contact.get(address, false);
if (contact.getSendToVoicemail()) {
// don't notify, skip this one
continue;
}
String subject = getMmsSubject(
cursor.getString(COLUMN_SUBJECT), cursor.getInt(COLUMN_SUBJECT_CS));
subject = MessageUtils.cleanseMmsSubject(context, subject);
long threadId = cursor.getLong(COLUMN_THREAD_ID);
long timeMillis = cursor.getLong(COLUMN_DATE) * 1000;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() +
", addr = " + address + ", thread_id=" + threadId);
}
// Extract the message and/or an attached picture from the first slide
Bitmap attachedPicture = null;
String messageBody = null;
int attachmentType = WorkingMessage.TEXT;
try {
GenericPdu pdu = sPduPersister.load(msgUri);
if (pdu != null && pdu instanceof MultimediaMessagePdu) {
SlideshowModel slideshow = SlideshowModel.createFromPduBody(context,
((MultimediaMessagePdu)pdu).getBody());
attachmentType = getAttachmentType(slideshow);
SlideModel firstSlide = slideshow.get(0);
if (firstSlide != null) {
if (firstSlide.hasImage()) {
int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP);
attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim);
}
if (firstSlide.hasText()) {
messageBody = firstSlide.getText().getText();
}
}
}
} catch (final MmsException e) {
Log.e(TAG, "MmsException loading uri: " + msgUri, e);
continue; // skip this bad boy -- don't generate an empty notification
}
NotificationInfo info = getNewMessageNotificationInfo(context,
false /* isSms */,
address,
messageBody, subject,
threadId,
timeMillis,
attachedPicture,
contact,
attachmentType);
notificationSet.add(info);
threads.add(threadId);
}
} finally {
cursor.close();
}
}
// Look at the passed in slideshow and determine what type of attachment it is.
private static int getAttachmentType(SlideshowModel slideshow) {
int slideCount = slideshow.size();
if (slideCount == 0) {
return WorkingMessage.TEXT;
} else if (slideCount > 1) {
return WorkingMessage.SLIDESHOW;
} else {
SlideModel slide = slideshow.get(0);
if (slide.hasImage()) {
return WorkingMessage.IMAGE;
} else if (slide.hasVideo()) {
return WorkingMessage.VIDEO;
} else if (slide.hasAudio()) {
return WorkingMessage.AUDIO;
}
}
return WorkingMessage.TEXT;
}
private static final int dp2Pixels(int dip) {
return (int) (dip * sScreenDensity + 0.5f);
}
private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT,
null, Sms.DATE);
if (cursor == null) {
return null;
}
try {
if (!cursor.moveToLast()) {
return null;
}
String address = cursor.getString(COLUMN_SMS_ADDRESS);
long timeMillis = 3000;
Contact contact = Contact.get(address, false);
String name = contact.getNameAndNumber();
return new MmsSmsDeliveryInfo(context.getString(R.string.delivery_toast_body, name),
timeMillis);
} finally {
cursor.close();
}
}
private static final void addSmsNotificationInfos(
Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_INCOMING_SM_CONSTRAINT,
null, Sms.DATE + " desc");
if (cursor == null) {
return;
}
try {
while (cursor.moveToNext()) {
String address = cursor.getString(COLUMN_SMS_ADDRESS);
Contact contact = Contact.get(address, false);
if (contact.getSendToVoicemail()) {
// don't notify, skip this one
continue;
}
String message = cursor.getString(COLUMN_SMS_BODY);
long threadId = cursor.getLong(COLUMN_THREAD_ID);
long timeMillis = cursor.getLong(COLUMN_DATE);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE))
{
Log.d(TAG, "addSmsNotificationInfos: count=" + cursor.getCount() +
", addr=" + address + ", thread_id=" + threadId);
}
NotificationInfo info = getNewMessageNotificationInfo(context, true /* isSms */,
address, message, null /* subject */,
threadId, timeMillis, null /* attachmentBitmap */,
contact, WorkingMessage.TEXT);
notificationSet.add(info);
threads.add(threadId);
threads.add(cursor.getLong(COLUMN_THREAD_ID));
}
} finally {
cursor.close();
}
}
private static final NotificationInfo getNewMessageNotificationInfo(
Context context,
boolean isSms,
String address,
String message,
String subject,
long threadId,
long timeMillis,
Bitmap attachmentBitmap,
Contact contact,
int attachmentType) {
Intent clickIntent = ComposeMessageActivity.createIntent(context, threadId);
clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
String senderInfo = buildTickerMessage(
context, address, null, null).toString();
String senderInfoName = senderInfo.substring(
0, senderInfo.length() - 2);
CharSequence ticker = buildTickerMessage(
context, address, subject, message);
return new NotificationInfo(isSms,
clickIntent, message, subject, ticker, timeMillis,
senderInfoName, attachmentBitmap, contact, attachmentType, threadId);
}
public static void cancelNotification(Context context, int notificationId) {
NotificationManager nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Log.d(TAG, "cancelNotification");
nm.cancel(notificationId);
}
private static void updateDeliveryNotification(final Context context,
boolean isStatusMessage,
final CharSequence message,
final long timeMillis) {
if (!isStatusMessage) {
return;
}
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
return;
}
sHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, message, (int)timeMillis).show();
}
});
}
/**
* updateNotification is *the* main function for building the actual notification handed to
* the NotificationManager
* @param context
* @param isNew if we've got a new message, show the ticker
* @param uniqueThreadCount
* @param notificationSet the set of notifications to display
*/
private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
- TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
+ PendingIntent pendingIntent = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
- taskStackBuilder.addNextIntent(mainActivityIntent);
+ pendingIntent = PendingIntent.getActivity(context, 0,
+ mainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
- taskStackBuilder.addParentStack(ComposeMessageActivity.class);
- taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
+ pendingIntent = PendingIntent.getActivity(context, 0,
+ mostRecentNotification.mClickIntent,
+ PendingIntent.FLAG_UPDATE_CURRENT);
}
// Always have to set the small icon or the notification is ignored
noti.setSmallIcon(R.drawable.stat_notify_sms);
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
- .setContentIntent(
- taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
+ .setContentIntent(pendingIntent)
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
protected static CharSequence buildTickerMessage(
Context context, String address, String subject, String body) {
String displayAddress = Contact.get(address, true).getName();
StringBuilder buf = new StringBuilder(
displayAddress == null
? ""
: displayAddress.replace('\n', ' ').replace('\r', ' '));
buf.append(':').append(' ');
int offset = buf.length();
if (!TextUtils.isEmpty(subject)) {
subject = subject.replace('\n', ' ').replace('\r', ' ');
buf.append(subject);
buf.append(' ');
}
if (!TextUtils.isEmpty(body)) {
body = body.replace('\n', ' ').replace('\r', ' ');
buf.append(body);
}
SpannableString spanText = new SpannableString(buf.toString());
spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanText;
}
private static String getMmsSubject(String sub, int charset) {
return TextUtils.isEmpty(sub) ? ""
: new EncodedStringValue(charset, PduPersister.getBytes(sub)).getString();
}
public static void notifyDownloadFailed(Context context, long threadId) {
notifyFailed(context, true, threadId, false);
}
public static void notifySendFailed(Context context) {
notifyFailed(context, false, 0, false);
}
public static void notifySendFailed(Context context, boolean noisy) {
notifyFailed(context, false, 0, noisy);
}
private static void notifyFailed(Context context, boolean isDownload, long threadId,
boolean noisy) {
// TODO factor out common code for creating notifications
boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
if (!enabled) {
return;
}
// Strategy:
// a. If there is a single failure notification, tapping on the notification goes
// to the compose view.
// b. If there are two failure it stays in the thread view. Selecting one undelivered
// thread will dismiss one undelivered notification but will still display the
// notification.If you select the 2nd undelivered one it will dismiss the notification.
long[] msgThreadId = {0, 1}; // Dummy initial values, just to initialize the memory
int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId);
if (totalFailedCount == 0 && !isDownload) {
return;
}
// The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all
// failures are from the same thread.
// If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are
// indeed in the same thread since there's only 1.
boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload;
Intent failedIntent;
Notification notification = new Notification();
String title;
String description;
if (totalFailedCount > 1) {
description = context.getString(R.string.notification_failed_multiple,
Integer.toString(totalFailedCount));
title = context.getString(R.string.notification_failed_multiple_title);
} else {
title = isDownload ?
context.getString(R.string.message_download_failed_title) :
context.getString(R.string.message_send_failed_title);
description = context.getString(R.string.message_failed_body);
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
if (allFailedInSameThread) {
failedIntent = new Intent(context, ComposeMessageActivity.class);
if (isDownload) {
// When isDownload is true, the valid threadId is passed into this function.
failedIntent.putExtra("failed_download_flag", true);
} else {
threadId = msgThreadId[0];
failedIntent.putExtra("undelivered_flag", true);
}
failedIntent.putExtra("thread_id", threadId);
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
} else {
failedIntent = new Intent(context, ConversationList.class);
}
taskStackBuilder.addNextIntent(failedIntent);
notification.icon = R.drawable.stat_notify_sms_failed;
notification.tickerText = title;
notification.setLatestEventInfo(context, title, description,
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
if (noisy) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false /* don't vibrate by default */);
if (vibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
}
NotificationManager notificationMgr = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (isDownload) {
notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
} else {
notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
}
}
/**
* Query the DB and return the number of undelivered messages (total for both SMS and MMS)
* @param context The context
* @param threadIdResult A container to put the result in, according to the following rules:
* threadIdResult[0] contains the thread id of the first message.
* threadIdResult[1] is nonzero if the thread ids of all the messages are the same.
* You can pass in null for threadIdResult.
* You can pass in a threadIdResult of size 1 to avoid the comparison of each thread id.
*/
private static int getUndeliveredMessageCount(Context context, long[] threadIdResult) {
Cursor undeliveredCursor = SqliteWrapper.query(context, context.getContentResolver(),
UNDELIVERED_URI, MMS_THREAD_ID_PROJECTION, "read=0", null, null);
if (undeliveredCursor == null) {
return 0;
}
int count = undeliveredCursor.getCount();
try {
if (threadIdResult != null && undeliveredCursor.moveToFirst()) {
threadIdResult[0] = undeliveredCursor.getLong(0);
if (threadIdResult.length >= 2) {
// Test to see if all the undelivered messages belong to the same thread.
long firstId = threadIdResult[0];
while (undeliveredCursor.moveToNext()) {
if (undeliveredCursor.getLong(0) != firstId) {
firstId = 0;
break;
}
}
threadIdResult[1] = firstId; // non-zero if all ids are the same
}
}
} finally {
undeliveredCursor.close();
}
return count;
}
public static void nonBlockingUpdateSendFailedNotification(final Context context) {
new AsyncTask<Void, Void, Integer>() {
protected Integer doInBackground(Void... none) {
return getUndeliveredMessageCount(context, null);
}
protected void onPostExecute(Integer result) {
if (result < 1) {
cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID);
} else {
// rebuild and adjust the message count if necessary.
notifySendFailed(context);
}
}
}.execute();
}
/**
* If all the undelivered messages belong to "threadId", cancel the notification.
*/
public static void updateSendFailedNotificationForThread(Context context, long threadId) {
long[] msgThreadId = {0, 0};
if (getUndeliveredMessageCount(context, msgThreadId) > 0
&& msgThreadId[0] == threadId
&& msgThreadId[1] != 0) {
cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID);
}
}
private static int getDownloadFailedMessageCount(Context context) {
// Look for any messages in the MMS Inbox that are of the type
// NOTIFICATION_IND (i.e. not already downloaded) and in the
// permanent failure state. If there are none, cancel any
// failed download notification.
Cursor c = SqliteWrapper.query(context, context.getContentResolver(),
Mms.Inbox.CONTENT_URI, null,
Mms.MESSAGE_TYPE + "=" +
String.valueOf(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) +
" AND " + Mms.STATUS + "=" +
String.valueOf(DownloadManager.STATE_PERMANENT_FAILURE),
null, null);
if (c == null) {
return 0;
}
int count = c.getCount();
c.close();
return count;
}
public static void updateDownloadFailedNotification(Context context) {
if (getDownloadFailedMessageCount(context) < 1) {
cancelNotification(context, DOWNLOAD_FAILED_NOTIFICATION_ID);
}
}
public static boolean isFailedToDeliver(Intent intent) {
return (intent != null) && intent.getBooleanExtra("undelivered_flag", false);
}
public static boolean isFailedToDownload(Intent intent) {
return (intent != null) && intent.getBooleanExtra("failed_download_flag", false);
}
/**
* Get the thread ID of the SMS message with the given URI
* @param context The context
* @param uri The URI of the SMS message
* @return The thread ID, or THREAD_NONE if the URI contains no entries
*/
public static long getSmsThreadId(Context context, Uri uri) {
Cursor cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
uri,
SMS_THREAD_ID_PROJECTION,
null,
null,
null);
if (cursor == null) {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(Sms.THREAD_ID);
if (columnIndex < 0) {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" Couldn't read row 0, col -1! returning THREAD_NONE");
}
return THREAD_NONE;
}
long threadId = cursor.getLong(columnIndex);
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" returning threadId: " + threadId);
}
return threadId;
} else {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
} finally {
cursor.close();
}
}
/**
* Get the thread ID of the MMS message with the given URI
* @param context The context
* @param uri The URI of the SMS message
* @return The thread ID, or THREAD_NONE if the URI contains no entries
*/
public static long getThreadId(Context context, Uri uri) {
Cursor cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
uri,
MMS_THREAD_ID_PROJECTION,
null,
null,
null);
if (cursor == null) {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(Mms.THREAD_ID);
if (columnIndex < 0) {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" Couldn't read row 0, col -1! returning THREAD_NONE");
}
return THREAD_NONE;
}
long threadId = cursor.getLong(columnIndex);
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" returning threadId: " + threadId);
}
return threadId;
} else {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
} finally {
cursor.close();
}
}
// Parse the user provided custom vibrate pattern into a long[]
private static long[] parseVibratePattern(String pattern) {
String[] splitPattern = pattern.split(",");
long[] result = new long[splitPattern.length];
for (int i = 0; i < splitPattern.length; i++) {
try {
result[i] = Long.parseLong(splitPattern[i]);
} catch (NumberFormatException e) {
return null;
}
}
return result;
}
}
| false | true |
private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
taskStackBuilder.addNextIntent(mainActivityIntent);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
}
// Always have to set the small icon or the notification is ignored
noti.setSmallIcon(R.drawable.stat_notify_sms);
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
.setContentIntent(
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
|
private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
PendingIntent pendingIntent = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
pendingIntent = PendingIntent.getActivity(context, 0,
mainActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
pendingIntent = PendingIntent.getActivity(context, 0,
mostRecentNotification.mClickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// Always have to set the small icon or the notification is ignored
noti.setSmallIcon(R.drawable.stat_notify_sms);
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
.setContentIntent(pendingIntent)
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
index b5768d21..c4045feb 100644
--- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
+++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
@@ -1,189 +1,188 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program 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, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* LockssServerAuth.java
*
* Created on Mar 23, 2007, 3:13 PM
*
*/
package edu.harvard.iq.dvn.core.admin;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal;
import edu.harvard.iq.dvn.core.vdc.LockssServer;
import edu.harvard.iq.dvn.core.vdc.LockssConfig;
import edu.harvard.iq.dvn.core.vdc.LockssConfig.ServerAccess;
import edu.harvard.iq.dvn.core.util.DomainMatchUtil;
import java.util.*;
import java.util.logging.*;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author landreev
*/
@Stateless
public class LockssAuthServiceBean implements LockssAuthServiceLocal {
@EJB
VDCNetworkServiceLocal vdcNetworkService;
private static Logger dbgLog = Logger.getLogger(LockssAuthServiceBean.class.getPackage().getName());
/* constructor: */
public LockssAuthServiceBean() {
}
/*
* isAuthorizedLockssServer method is used to check if the remote LOCKSS
* server is authorized to crawl this set/dv at all; meaning, at this
* point we are not authorizing them to download any particular files,
* just deciding whether to show them the Manifest page.
*/
public Boolean isAuthorizedLockssServer ( VDC vdc,
HttpServletRequest req ) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
lockssConfig = vdc.getLockssConfig();
} else {
lockssConfig = vdcNetworkService.getLockssConfig();
}
if (lockssConfig == null) {
return false;
}
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
return true;
}
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
return false;
}
/*
* isAuthorizedLockssDownload performs authorization on individual files
* that the crawler is trying to download. This authorization depends on
* how this configuration is configured, whether it's open to all lockss
* servers or an IP group, and whether the file in question is restricted.
*/
public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
- } else {
- lockssConfig = vdcNetworkService.getLockssConfig();
- }
+ }
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
- // of public files but not of the restricted ones:
+ // of public files; so if the file is public, we can return true.
+ // We *may* also allow access to restricted ones; but only to
+ // select servers (we'll check for that further below).
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
- if (fileIsRestricted) {
- return false;
+ if (!fileIsRestricted) {
+ return true;
}
- return true;
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
}
| false | true |
public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
} else {
lockssConfig = vdcNetworkService.getLockssConfig();
}
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
// of public files but not of the restricted ones:
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
if (fileIsRestricted) {
return false;
}
return true;
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
|
public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
}
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
// of public files; so if the file is public, we can return true.
// We *may* also allow access to restricted ones; but only to
// select servers (we'll check for that further below).
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
if (!fileIsRestricted) {
return true;
}
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
|
diff --git a/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java b/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java
index 26441c540..b9cc540c6 100644
--- a/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java
+++ b/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java
@@ -1,1036 +1,1036 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.runtime.jobs;
import junit.framework.*;
import org.eclipse.core.internal.jobs.Worker;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.*;
import org.eclipse.core.tests.harness.TestBarrier;
import org.eclipse.core.tests.harness.TestJob;
/**
* Tests the implemented get/set methods of the abstract class Job
*/
public class JobTest extends TestCase {
protected Job longJob;
protected Job shortJob;
public static Test suite() {
return new TestSuite(JobTest.class);
}
//see bug #43591
public void _testDone() {
//calling the done method on a job that is not executing asynchronously should have no effect
shortJob.done(Status.OK_STATUS);
assertTrue("1.0", shortJob.getResult() == null);
shortJob.done(Status.CANCEL_STATUS);
assertTrue("2.0", shortJob.getResult() == null);
//calling the done method after the job is scheduled
shortJob.schedule();
shortJob.done(Status.CANCEL_STATUS);
waitForState(shortJob, Job.NONE);
//the done call should be ignored, and the job should finish execution normally
assertTrue("3.0", shortJob.getResult().getSeverity() == IStatus.OK);
shortJob.done(Status.CANCEL_STATUS);
assertTrue("4.0", shortJob.getResult().getSeverity() == IStatus.OK);
//calling the done method before a job is cancelled
longJob.schedule();
waitForState(longJob, Job.RUNNING);
longJob.done(Status.OK_STATUS);
longJob.cancel();
waitForState(longJob, Job.NONE);
//the done call should be ignored, and the job status should still be cancelled
assertTrue("5.0", longJob.getResult().getSeverity() == IStatus.CANCEL);
longJob.done(Status.OK_STATUS);
assertTrue("6.0", longJob.getResult().getSeverity() == IStatus.CANCEL);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
shortJob = new TestJob("Short Test Job", 100, 10);
longJob = new TestJob("Long Test Job", 1000000, 10);
}
private void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
//ignore
}
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
//see bug #43566
public void testAsynchJob() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START};
//execute a job asynchronously and check the result
AsynchTestJob main = new AsynchTestJob("Test Asynch Finish", status, 0);
assertTrue("1.0", main.getThread() == null);
assertTrue("2.0", main.getResult() == null);
//schedule the job to run
main.schedule();
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_RUNNING);
assertTrue("3.0", main.getState() == Job.RUNNING);
//the asynchronous process that assigns the thread the job is going to run in has not been started yet
//the job is running in the thread provided to it by the manager
assertTrue("3.1" + main.getThread().getName(), main.getThread() instanceof Worker);
status[0] = TestBarrier.STATUS_START;
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_WAIT_FOR_START);
//the asynchronous process has been started, but the set thread method has not been called yet
assertTrue("3.2", main.getThread() instanceof Worker);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
//make sure the job has set the thread it is going to run in
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_RUNNING);
assertTrue("3.3", status[0] == TestBarrier.STATUS_RUNNING);
assertTrue("3.4", main.getThread() instanceof AsynchExecThread);
//let the job run
status[0] = TestBarrier.STATUS_WAIT_FOR_DONE;
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_DONE);
waitForState(main, Job.NONE);
//after the job is finished, the thread should be reset
assertTrue("4.0", main.getState() == Job.NONE);
assertTrue("4.1", main.getResult().getSeverity() == IStatus.OK);
assertTrue("4.2", main.getThread() == null);
//reset status
status[0] = TestBarrier.STATUS_WAIT_FOR_START;
//schedule the job to run again
main.schedule();
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_RUNNING);
assertTrue("5.0", main.getState() == Job.RUNNING);
//the asynchronous process that assigns the thread the job is going to run in has not been started yet
//job is running in the thread provided by the manager
assertTrue("5.1", main.getThread() instanceof Worker);
status[0] = TestBarrier.STATUS_START;
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_WAIT_FOR_START);
//the asynchronous process has been started, but the set thread method has not been called yet
assertTrue("5.2", main.getThread() instanceof Worker);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
//make sure the job has set the thread it is going to run in
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_RUNNING);
assertTrue("5.3", status[0] == TestBarrier.STATUS_RUNNING);
assertTrue("5.4", main.getThread() instanceof AsynchExecThread);
//cancel the job, then let the job get the cancellation request
main.cancel();
status[0] = TestBarrier.STATUS_WAIT_FOR_DONE;
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_DONE);
waitForState(main, Job.NONE);
//thread should be reset to null after cancellation
assertTrue("6.0", main.getState() == Job.NONE);
assertTrue("6.1", main.getResult().getSeverity() == IStatus.CANCEL);
assertTrue("6.2", main.getThread() == null);
}
public void testAsynchJobComplex() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START};
//test the interaction of several asynchronous jobs
AsynchTestJob[] jobs = new AsynchTestJob[5];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new AsynchTestJob("TestJob" + (i + 1), status, i);
assertTrue("1." + i, jobs[i].getThread() == null);
assertTrue("2." + i, jobs[i].getResult() == null);
jobs[i].schedule();
//status[i] = TestBarrier.STATUS_START;
}
//all the jobs should be running at the same time
waitForStart(jobs, status);
//every job should now be waiting for the STATUS_START flag
for (int i = 0; i < status.length; i++) {
assertTrue("3." + i, jobs[i].getState() == Job.RUNNING);
assertTrue("4." + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_START;
}
for (int i = 0; i < status.length; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_WAIT_FOR_START);
//every job should now be waiting for the STATUS_WAIT_FOR_RUN flag
for (int i = 0; i < status.length; i++) {
assertTrue("5. " + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_WAIT_FOR_RUN;
}
//wait until all jobs are in the running state
for (int i = 0; i < status.length; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
//let the jobs execute
for (int i = 0; i < status.length; i++) {
assertTrue("6. " + i, jobs[i].getThread() instanceof AsynchExecThread);
status[i] = TestBarrier.STATUS_WAIT_FOR_DONE;
}
for (int i = 0; i < status.length; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_DONE);
//the status for every job should be STATUS_OK
//the threads should have been reset to null
for (int i = 0; i < status.length; i++) {
assertEquals("7." + i, TestBarrier.STATUS_DONE, status[i]);
assertEquals("8." + i, Job.NONE, jobs[i].getState());
assertEquals("9." + i, IStatus.OK, jobs[i].getResult().getSeverity());
assertNull("10." + i, jobs[i].getThread());
}
}
public void testAsynchJobConflict() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START};
//test the interaction of several asynchronous jobs when a conflicting rule is assigned to some of them
AsynchTestJob[] jobs = new AsynchTestJob[5];
ISchedulingRule rule = new IdentityRule();
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new AsynchTestJob("TestJob" + (i + 1), status, i);
assertTrue("1." + i, jobs[i].getThread() == null);
assertTrue("2." + i, jobs[i].getResult() == null);
if (i < 2) {
jobs[i].schedule();
} else if (i > 2) {
jobs[i].setRule(rule);
} else {
jobs[i].setRule(rule);
jobs[i].schedule();
}
}
//these 3 jobs should be waiting for the STATUS_START flag
for (int i = 0; i < 3; i++) {
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
assertTrue("3." + i, jobs[i].getState() == Job.RUNNING);
assertTrue("4." + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_START;
}
- //all the jobs should be running at the same time
- //by the time the third job changes the status flag, the other jobs should have already done so
- TestBarrier.waitForStatus(status, 2, TestBarrier.STATUS_WAIT_FOR_START);
+ //the first 3 jobs should be running at the same time
+ for (int i = 0; i < 3; i++)
+ TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_WAIT_FOR_START);
//the 3 jobs should now be waiting for the STATUS_WAIT_FOR_RUN flag
for (int i = 0; i < 3; i++) {
assertTrue("5. " + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_WAIT_FOR_RUN;
}
//wait until jobs block on running state
for (int i = 0; i < 3; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
//schedule the 2 remaining jobs
jobs[3].schedule();
jobs[4].schedule();
//the 2 newly scheduled jobs should be waiting since they conflict with the third job
//no threads were assigned to them yet
assertEquals("6.1", Job.WAITING, jobs[3].getState());
assertNull("6.2", jobs[3].getThread());
assertEquals("6.3", Job.WAITING, jobs[4].getState());
assertNull("6.4", jobs[4].getThread());
//let the two non-conflicting jobs execute together
for (int i = 0; i < 2; i++) {
assertTrue("7. " + i, jobs[i].getThread() instanceof AsynchExecThread);
status[i] = TestBarrier.STATUS_WAIT_FOR_DONE;
}
//wait until the non-conflicting jobs are done
TestBarrier.waitForStatus(status, 1, TestBarrier.STATUS_DONE);
//the third job should still be in the running state
assertEquals("8.1", Job.RUNNING, jobs[2].getState());
//the 2 conflicting jobs should still be in the waiting state
assertEquals("8.2", Job.WAITING, jobs[3].getState());
assertEquals("8.3", Job.WAITING, jobs[4].getState());
//let the third job finish execution
assertTrue("8.4", jobs[2].getThread() instanceof AsynchExecThread);
status[2] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the third job is done
TestBarrier.waitForStatus(status, 2, TestBarrier.STATUS_DONE);
//the fourth job should now start running, the fifth job should still be waiting
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.1", Job.RUNNING, jobs[3].getState());
assertEquals("9.2", Job.WAITING, jobs[4].getState());
//let the fourth job run, the fifth job is still waiting
status[3] = TestBarrier.STATUS_START;
assertEquals("9.3", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_WAIT_FOR_START);
status[3] = TestBarrier.STATUS_WAIT_FOR_RUN;
assertEquals("9.4", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.5", Job.WAITING, jobs[4].getState());
//cancel the fifth job, finish the fourth job
jobs[4].cancel();
assertTrue("9.6", jobs[3].getThread() instanceof AsynchExecThread);
status[3] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the fourth job is done
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_DONE);
//the status for the first 4 jobs should be STATUS_OK
//the threads should have been reset to null
for (int i = 0; i < status.length - 1; i++) {
assertEquals("10." + i, TestBarrier.STATUS_DONE, status[i]);
assertEquals("11." + i, Job.NONE, jobs[i].getState());
assertEquals("12." + i, IStatus.OK, jobs[i].getResult().getSeverity());
assertNull("13." + i, jobs[i].getThread());
}
//the fifth job should have null as its status (it never finished running)
//the thread for it should have also been reset
assertEquals("14.1", TestBarrier.STATUS_WAIT_FOR_START, status[4]);
assertEquals("14.2", Job.NONE, jobs[4].getState());
assertNull("14.3", jobs[4].getResult());
assertNull("14.4", jobs[4].getThread());
}
/**
* Tests cancelation of a job from the aboutToRun job event.
* See bug 70434 for details.
*/
public void testCancelFromAboutToRun() {
final int[] doneCount = new int[] {0};
final int[] runningCount = new int[] {0};
TestJob job = new TestJob("testCancelFromAboutToRun", 0, 0);
job.addJobChangeListener(new JobChangeAdapter() {
public void aboutToRun(IJobChangeEvent event) {
event.getJob().cancel();
}
public void done(IJobChangeEvent event) {
doneCount[0]++;
}
public void running(IJobChangeEvent event) {
runningCount[0]++;
}
});
job.schedule();
try {
job.join();
} catch (InterruptedException e) {
e.printStackTrace();
fail("0.99 " + e.getMessage());
}
assertEquals("1.0", 0, job.getRunCount());
assertEquals("1.1", 1, doneCount[0]);
assertEquals("1.2", 0, runningCount[0]);
}
public void testGetName() {
assertTrue("1.0", shortJob.getName().equals("Short Test Job"));
assertTrue("1.1", longJob.getName().equals("Long Test Job"));
//try creating a job with a null name
try {
new TestJob(null);
fail("2.0");
} catch (RuntimeException e) {
//should fail
}
}
public void testGetPriority() {
//set priorities to all allowed options
//check if getPriority() returns proper result
int[] priority = {Job.SHORT, Job.LONG, Job.INTERACTIVE, Job.BUILD, Job.DECORATE};
for (int i = 0; i < priority.length; i++) {
shortJob.setPriority(priority[i]);
assertTrue("1." + i, shortJob.getPriority() == priority[i]);
}
}
public void testGetProperty() {
QualifiedName n1 = new QualifiedName("org.eclipse.core.tests.runtime", "p1");
QualifiedName n2 = new QualifiedName("org.eclipse.core.tests.runtime", "p2");
assertNull("1.0", shortJob.getProperty(n1));
shortJob.setProperty(n1, null);
assertNull("1.1", shortJob.getProperty(n1));
shortJob.setProperty(n1, shortJob);
assertTrue("1.2", shortJob.getProperty(n1) == shortJob);
assertNull("1.3", shortJob.getProperty(n2));
shortJob.setProperty(n1, "hello");
assertEquals("1.4", "hello", shortJob.getProperty(n1));
shortJob.setProperty(n1, null);
assertNull("1.5", shortJob.getProperty(n1));
assertNull("1.6", shortJob.getProperty(n2));
}
public void testGetResult() {
//execute a short job
assertTrue("1.0", shortJob.getResult() == null);
shortJob.schedule();
waitForState(shortJob, Job.NONE);
assertTrue("1.1", shortJob.getResult().getSeverity() == IStatus.OK);
//cancel a long job
longJob.schedule(1000000);
assertTrue("1.3", longJob.sleep());
longJob.wakeUp();
waitForState(longJob, Job.RUNNING);
longJob.cancel();
waitForState(longJob, Job.NONE);
assertTrue("2.0", longJob.getResult().getSeverity() == IStatus.CANCEL);
}
public void testGetRule() {
//set several rules for the job, check if getRule returns the rule that was set
//no rule was set yet
assertTrue("1.0", shortJob.getRule() == null);
shortJob.setRule(new IdentityRule());
assertTrue("1.1", (shortJob.getRule() instanceof IdentityRule));
ISchedulingRule rule = new PathRule("/testGetRule");
shortJob.setRule(rule);
assertTrue("1.2", shortJob.getRule() == rule);
shortJob.setRule(null);
assertTrue("1.3", shortJob.getRule() == null);
}
public void testGetThread() {
//check that getThread returns the thread that was passed in setThread, when the job is not running
//if the job is scheduled, only jobs that return the asynch_exec status will run in the indicated thread
//main is not running now
assertTrue("1.0", shortJob.getThread() == null);
Thread t = new Thread();
shortJob.setThread(t);
assertTrue("1.1", shortJob.getThread() == t);
shortJob.setThread(new Thread());
assertTrue("1.2", shortJob.getThread() != t);
shortJob.setThread(null);
assertTrue("1.3", shortJob.getThread() == null);
}
public void testIsSystem() {
//reset the system parameter several times
shortJob.setUser(false);
shortJob.setSystem(false);
assertTrue("1.0", !shortJob.isUser());
assertTrue("1.1", !shortJob.isSystem());
shortJob.setSystem(true);
assertTrue("1.2", !shortJob.isUser());
assertTrue("1.3", shortJob.isSystem());
shortJob.setSystem(false);
assertTrue("1.4", !shortJob.isUser());
assertTrue("1.5", !shortJob.isSystem());
}
public void testIsUser() {
//reset the user parameter several times
shortJob.setUser(false);
shortJob.setSystem(false);
assertTrue("1.0", !shortJob.isUser());
assertTrue("1.1", !shortJob.isSystem());
shortJob.setUser(true);
assertTrue("1.2", shortJob.isUser());
assertTrue("1.3", !shortJob.isSystem());
shortJob.setUser(false);
assertTrue("1.4", !shortJob.isUser());
assertTrue("1.5", !shortJob.isSystem());
}
public void testJoin() {
longJob.schedule(100000);
//create a thread that will join the test job
final int[] status = new int[1];
status[0] = TestBarrier.STATUS_WAIT_FOR_START;
Thread t = new Thread(new Runnable() {
public void run() {
status[0] = TestBarrier.STATUS_START;
try {
longJob.join();
} catch (InterruptedException e) {
Assert.fail("0.99");
}
status[0] = TestBarrier.STATUS_DONE;
}
});
t.start();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_START);
assertEquals("1.0", TestBarrier.STATUS_START, status[0]);
//putting the job to sleep should not affect the join call
longJob.sleep();
//give a chance for the sleep to take effect
sleep(100);
assertEquals("1.0", TestBarrier.STATUS_START, status[0]);
//similarly waking the job up should not affect the join
longJob.wakeUp(100000);
sleep(100);
assertEquals("1.0", TestBarrier.STATUS_START, status[0]);
//finally canceling the job will cause the join to return
longJob.cancel();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_DONE);
}
/**
* Tests a job change listener that throws an exception.
* This would previously cause join attempts on that job to
* hang indefinitely because they would miss the notification
* required to end the join.
*/
public void testJoinFailingListener() {
shortJob.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
throw new RuntimeException("This exception thrown on purpose as part of a test");
}
});
final int[] status = new int[1];
//create a thread that will join the job
Thread t = new Thread(new Runnable() {
public void run() {
status[0] = TestBarrier.STATUS_START;
try {
shortJob.join();
} catch (InterruptedException e) {
Assert.fail("0.99");
}
status[0] = TestBarrier.STATUS_DONE;
}
});
//schedule the job and then fork the thread to join it
shortJob.schedule();
t.start();
//wait until the join succeeds
TestBarrier.waitForStatus(status, TestBarrier.STATUS_DONE);
}
/**
* This is a regression test for bug 60323. If a job change listener
* removed itself from the listener list during the done() change event,
* then anyone joining on that job would hang forever.
*/
public void testJoinRemoveListener() {
final IJobChangeListener listener = new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
shortJob.removeJobChangeListener(this);
}
};
shortJob.addJobChangeListener(listener);
final int[] status = new int[1];
//create a thread that will join the job
Thread t = new Thread(new Runnable() {
public void run() {
status[0] = TestBarrier.STATUS_START;
try {
shortJob.join();
} catch (InterruptedException e) {
Assert.fail("0.99");
}
status[0] = TestBarrier.STATUS_DONE;
}
});
//schedule the job and then fork the thread to join it
shortJob.schedule();
t.start();
//wait until the join succeeds
TestBarrier.waitForStatus(status, TestBarrier.STATUS_DONE);
}
/*
* Test that a cancelled job is rescheduled
*/
public void testRescheduleCancel() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START};
Job job = new Job("Testing") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
};
//schedule the job, cancel it, then reschedule
job.schedule();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
job.cancel();
job.schedule();
//let the first iteration of the job finish
status[0] = TestBarrier.STATUS_RUNNING;
//wait until the job runs again
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
//let the job finish
status[0] = TestBarrier.STATUS_RUNNING;
waitForState(job, Job.NONE);
}
/*
* Test that multiple reschedules of the same job while it is running
* only remembers the last reschedule request
*/
public void testRescheduleComplex() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START};
final int[] runCount = new int[] {0};
Job job = new Job("Testing") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
runCount[0]++;
monitor.done();
}
return Status.OK_STATUS;
}
};
//schedule the job, reschedule when it is running
job.schedule();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
//the last schedule value should win
job.schedule(1000000);
job.schedule(3000);
job.schedule(200000000);
job.schedule();
status[0] = TestBarrier.STATUS_RUNNING;
//wait until the job runs again
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
assertEquals("1.0", 1, runCount[0]);
//let the job finish
status[0] = TestBarrier.STATUS_RUNNING;
waitForState(job, Job.NONE);
assertEquals("1.0", 2, runCount[0]);
}
/*
* Reschedule a running job with a delay
*/
public void testRescheduleDelay() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START};
final int[] runCount = new int[] {0};
Job job = new Job("Testing") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
runCount[0]++;
monitor.done();
}
return Status.OK_STATUS;
}
};
//schedule the job, reschedule when it is running
job.schedule();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
job.schedule(1000000);
status[0] = TestBarrier.STATUS_RUNNING;
//now wait until the job is scheduled again and put to sleep
waitForState(job, Job.SLEEPING);
assertEquals("1.0", 1, runCount[0]);
//reschedule the job while it is sleeping
job.schedule();
//wake up the currently sleeping job
job.wakeUp();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
status[0] = TestBarrier.STATUS_RUNNING;
//make sure the job was not rescheduled while the executing job was sleeping
waitForState(job, Job.NONE);
assertTrue("1.0", job.getState() == Job.NONE);
assertEquals("1.0", 2, runCount[0]);
}
/*
* Schedule a simple job that repeats several times from within the run method.
*/
public void testRescheduleRepeat() {
final int[] count = new int[] {0};
final int REPEATS = 10;
Job job = new Job("testRescheduleRepeat") {
protected IStatus run(IProgressMonitor monitor) {
count[0]++;
schedule();
return Status.OK_STATUS;
}
public boolean shouldSchedule() {
return count[0] < REPEATS;
}
};
job.schedule();
int timeout = 0;
while (timeout++ < 100 && count[0] < REPEATS) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//ignore
}
}
assertTrue("1.0", timeout < 100);
assertEquals("1.1", REPEATS, count[0]);
} /*
* Schedule a simple job that repeats several times from within the run method.
*/
public void testRescheduleRepeatWithDelay() {
final int[] count = new int[] {0};
final int REPEATS = 10;
Job job = new Job("testRescheduleRepeat") {
protected IStatus run(IProgressMonitor monitor) {
count[0]++;
schedule(10);
return Status.OK_STATUS;
}
public boolean shouldSchedule() {
return count[0] < REPEATS;
}
};
job.schedule();
int timeout = 0;
while (timeout++ < 100 && count[0] < REPEATS) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//ignore
}
}
assertTrue("1.0", timeout < 100);
assertEquals("1.1", REPEATS, count[0]);
}
/*
* Schedule a job to run, and then reschedule it
*/
public void testRescheduleSimple() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START};
Job job = new Job("testRescheduleSimple") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
};
//schedule the job, reschedule when it is running
job.schedule();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
job.schedule();
status[0] = TestBarrier.STATUS_RUNNING;
//wait until the job runs again
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
//let the job finish
status[0] = TestBarrier.STATUS_RUNNING;
waitForState(job, Job.NONE);
//the job should only run once the second time around
job.schedule();
TestBarrier.waitForStatus(status, TestBarrier.STATUS_WAIT_FOR_RUN);
//let the job finish
status[0] = TestBarrier.STATUS_RUNNING;
//wait until the job truly finishes and has a chance to be rescheduled (it shouldn't reschedule)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//ignore
}
waitForState(job, Job.NONE);
}
/*
* Reschedule a waiting job.
*/
public void testRescheduleWaiting() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START};
final int[] runCount = new int[] {0};
final ISchedulingRule rule = new IdentityRule();
Job first = new Job("Testing1") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[0] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
};
Job second = new Job("Testing2") {
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Testing", 1);
status[1] = TestBarrier.STATUS_WAIT_FOR_RUN;
TestBarrier.waitForStatus(status, 1, TestBarrier.STATUS_RUNNING);
monitor.worked(1);
} finally {
runCount[0]++;
monitor.done();
}
return Status.OK_STATUS;
}
};
//set the same rule for both jobs so that the second job would have to wait
first.setRule(rule);
first.schedule();
second.setRule(rule);
TestBarrier.waitForStatus(status, 0, TestBarrier.STATUS_WAIT_FOR_RUN);
second.schedule();
waitForState(second, Job.WAITING);
//reschedule the second job while it is waiting
second.schedule();
//let the first job finish
status[0] = TestBarrier.STATUS_RUNNING;
//the second job will start
TestBarrier.waitForStatus(status, 1, TestBarrier.STATUS_WAIT_FOR_RUN);
//let the second job finish
status[1] = TestBarrier.STATUS_RUNNING;
//make sure the second job was not rescheduled
waitForState(second, Job.NONE);
assertEquals("2.0", Job.NONE, second.getState());
assertEquals("2.1", 1, runCount[0]);
}
/*
* see bug #43458
*/
public void testSetPriority() {
int[] wrongPriority = {1000, -Job.DECORATE, 25, 0, 5, Job.INTERACTIVE - Job.BUILD};
for (int i = 0; i < wrongPriority.length; i++) {
//set priority to non-existent type
try {
shortJob.setPriority(wrongPriority[i]);
fail("1." + (i + 1));
} catch (RuntimeException e) {
//should fail
}
}
}
/**
* Tests the API methods Job.setProgressGroup
*/
public void testSetProgressGroup() {
//null group
try {
longJob.setProgressGroup(null, 5);
fail("1.0");
} catch (RuntimeException e) {
//should fail
}
IProgressMonitor group = Platform.getJobManager().createProgressGroup();
group.beginTask("Group task name", 10);
longJob.setProgressGroup(group, 5);
//ignore changes to group while waiting or running
longJob.schedule(100);
longJob.setProgressGroup(group, 0);
waitForState(longJob, Job.RUNNING);
longJob.setProgressGroup(group, 0);
//ensure cancelation still works
longJob.cancel();
waitForState(longJob, Job.NONE);
group.done();
}
/*
* see bug #43459
*/
public void testSetRule() {
//setting a scheduling rule for a job after it was already scheduled should throw an exception
shortJob.setRule(new IdentityRule());
assertTrue("1.0", shortJob.getRule() instanceof IdentityRule);
shortJob.schedule(1000000);
try {
shortJob.setRule(new PathRule("/testSetRule"));
fail("1.1");
} catch (RuntimeException e) {
//should fail
}
//wake up the sleeping job
shortJob.wakeUp();
//setting the rule while running should fail
try {
shortJob.setRule(new PathRule("/testSetRule/B"));
fail("2.0");
} catch (RuntimeException e1) {
//should fail
}
try {
//wait for the job to complete
shortJob.join();
} catch (InterruptedException e2) {
//ignore
}
//after the job has finished executing, the scheduling rule for it can once again be reset
shortJob.setRule(new PathRule("/testSetRule/B/C/D"));
assertTrue("1.2", shortJob.getRule() instanceof PathRule);
shortJob.setRule(null);
assertTrue("1.3", shortJob.getRule() == null);
}
public void testSetThread() {
//setting the thread of a job that is not an asynchronous job should not affect the actual thread the job will run in
assertTrue("0.0", longJob.getThread() == null);
longJob.setThread(Thread.currentThread());
assertTrue("1.0", longJob.getThread() == Thread.currentThread());
longJob.schedule();
waitForState(longJob, Job.RUNNING);
//the setThread method should have no effect on jobs that execute normally
assertTrue("2.0", longJob.getThread() != Thread.currentThread());
longJob.cancel();
waitForState(longJob, Job.NONE);
//the thread should reset to null when the job finishes execution
assertTrue("3.0", longJob.getThread() == null);
longJob.setThread(null);
assertTrue("4.0", longJob.getThread() == null);
longJob.schedule();
waitForState(longJob, Job.RUNNING);
//the thread that the job is executing in is not the one that was set
assertTrue("5.0", longJob.getThread() != null);
longJob.cancel();
waitForState(longJob, Job.NONE);
//thread should reset to null after execution of job
assertTrue("6.0", longJob.getThread() == null);
Thread t = new Thread();
longJob.setThread(t);
assertTrue("7.0", longJob.getThread() == t);
longJob.schedule();
waitForState(longJob, Job.RUNNING);
//the thread that the job is executing in is not the one that it was set to
assertTrue("8.0", longJob.getThread() != t);
longJob.cancel();
waitForState(longJob, Job.NONE);
//execution thread should reset to null after job is finished
assertTrue("9.0", longJob.getThread() == null);
}
/**
* Several jobs were scheduled to run.
* Pause this thread until all the jobs start running.
*/
private void waitForStart(Job[] jobs, int[] status) {
for (int i = 0; i < jobs.length; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
}
/**
* A job has been scheduled. Pause this thread so that a worker thread
* has a chance to pick up the new job.
*/
private void waitForState(Job job, int state) {
int i = 0;
while (job.getState() != state) {
try {
Thread.yield();
Thread.sleep(100);
Thread.yield();
} catch (InterruptedException e) {
//ignore
}
//sanity test to avoid hanging tests
assertTrue("Timeout waiting for job to change state.", i++ < 100);
}
}
/**
* A job was scheduled to run. Pause this thread so that a worker thread
* has a chance to finish the job
*/
// private void waitForEnd(Job job) {
// int i = 0;
// while(job.getState() != Job.NONE) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
//
// }
//
// //sanity test to avoid hanging tests
// assertTrue("Timeout waiting for job to end", i++ < 1000);
// }
// }
}
| true | true |
public void testAsynchJobConflict() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START};
//test the interaction of several asynchronous jobs when a conflicting rule is assigned to some of them
AsynchTestJob[] jobs = new AsynchTestJob[5];
ISchedulingRule rule = new IdentityRule();
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new AsynchTestJob("TestJob" + (i + 1), status, i);
assertTrue("1." + i, jobs[i].getThread() == null);
assertTrue("2." + i, jobs[i].getResult() == null);
if (i < 2) {
jobs[i].schedule();
} else if (i > 2) {
jobs[i].setRule(rule);
} else {
jobs[i].setRule(rule);
jobs[i].schedule();
}
}
//these 3 jobs should be waiting for the STATUS_START flag
for (int i = 0; i < 3; i++) {
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
assertTrue("3." + i, jobs[i].getState() == Job.RUNNING);
assertTrue("4." + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_START;
}
//all the jobs should be running at the same time
//by the time the third job changes the status flag, the other jobs should have already done so
TestBarrier.waitForStatus(status, 2, TestBarrier.STATUS_WAIT_FOR_START);
//the 3 jobs should now be waiting for the STATUS_WAIT_FOR_RUN flag
for (int i = 0; i < 3; i++) {
assertTrue("5. " + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_WAIT_FOR_RUN;
}
//wait until jobs block on running state
for (int i = 0; i < 3; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
//schedule the 2 remaining jobs
jobs[3].schedule();
jobs[4].schedule();
//the 2 newly scheduled jobs should be waiting since they conflict with the third job
//no threads were assigned to them yet
assertEquals("6.1", Job.WAITING, jobs[3].getState());
assertNull("6.2", jobs[3].getThread());
assertEquals("6.3", Job.WAITING, jobs[4].getState());
assertNull("6.4", jobs[4].getThread());
//let the two non-conflicting jobs execute together
for (int i = 0; i < 2; i++) {
assertTrue("7. " + i, jobs[i].getThread() instanceof AsynchExecThread);
status[i] = TestBarrier.STATUS_WAIT_FOR_DONE;
}
//wait until the non-conflicting jobs are done
TestBarrier.waitForStatus(status, 1, TestBarrier.STATUS_DONE);
//the third job should still be in the running state
assertEquals("8.1", Job.RUNNING, jobs[2].getState());
//the 2 conflicting jobs should still be in the waiting state
assertEquals("8.2", Job.WAITING, jobs[3].getState());
assertEquals("8.3", Job.WAITING, jobs[4].getState());
//let the third job finish execution
assertTrue("8.4", jobs[2].getThread() instanceof AsynchExecThread);
status[2] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the third job is done
TestBarrier.waitForStatus(status, 2, TestBarrier.STATUS_DONE);
//the fourth job should now start running, the fifth job should still be waiting
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.1", Job.RUNNING, jobs[3].getState());
assertEquals("9.2", Job.WAITING, jobs[4].getState());
//let the fourth job run, the fifth job is still waiting
status[3] = TestBarrier.STATUS_START;
assertEquals("9.3", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_WAIT_FOR_START);
status[3] = TestBarrier.STATUS_WAIT_FOR_RUN;
assertEquals("9.4", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.5", Job.WAITING, jobs[4].getState());
//cancel the fifth job, finish the fourth job
jobs[4].cancel();
assertTrue("9.6", jobs[3].getThread() instanceof AsynchExecThread);
status[3] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the fourth job is done
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_DONE);
//the status for the first 4 jobs should be STATUS_OK
//the threads should have been reset to null
for (int i = 0; i < status.length - 1; i++) {
assertEquals("10." + i, TestBarrier.STATUS_DONE, status[i]);
assertEquals("11." + i, Job.NONE, jobs[i].getState());
assertEquals("12." + i, IStatus.OK, jobs[i].getResult().getSeverity());
assertNull("13." + i, jobs[i].getThread());
}
//the fifth job should have null as its status (it never finished running)
//the thread for it should have also been reset
assertEquals("14.1", TestBarrier.STATUS_WAIT_FOR_START, status[4]);
assertEquals("14.2", Job.NONE, jobs[4].getState());
assertNull("14.3", jobs[4].getResult());
assertNull("14.4", jobs[4].getThread());
}
|
public void testAsynchJobConflict() {
final int[] status = {TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START, TestBarrier.STATUS_WAIT_FOR_START};
//test the interaction of several asynchronous jobs when a conflicting rule is assigned to some of them
AsynchTestJob[] jobs = new AsynchTestJob[5];
ISchedulingRule rule = new IdentityRule();
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new AsynchTestJob("TestJob" + (i + 1), status, i);
assertTrue("1." + i, jobs[i].getThread() == null);
assertTrue("2." + i, jobs[i].getResult() == null);
if (i < 2) {
jobs[i].schedule();
} else if (i > 2) {
jobs[i].setRule(rule);
} else {
jobs[i].setRule(rule);
jobs[i].schedule();
}
}
//these 3 jobs should be waiting for the STATUS_START flag
for (int i = 0; i < 3; i++) {
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
assertTrue("3." + i, jobs[i].getState() == Job.RUNNING);
assertTrue("4." + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_START;
}
//the first 3 jobs should be running at the same time
for (int i = 0; i < 3; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_WAIT_FOR_START);
//the 3 jobs should now be waiting for the STATUS_WAIT_FOR_RUN flag
for (int i = 0; i < 3; i++) {
assertTrue("5. " + i, jobs[i].getThread() instanceof Worker);
status[i] = TestBarrier.STATUS_WAIT_FOR_RUN;
}
//wait until jobs block on running state
for (int i = 0; i < 3; i++)
TestBarrier.waitForStatus(status, i, TestBarrier.STATUS_RUNNING);
//schedule the 2 remaining jobs
jobs[3].schedule();
jobs[4].schedule();
//the 2 newly scheduled jobs should be waiting since they conflict with the third job
//no threads were assigned to them yet
assertEquals("6.1", Job.WAITING, jobs[3].getState());
assertNull("6.2", jobs[3].getThread());
assertEquals("6.3", Job.WAITING, jobs[4].getState());
assertNull("6.4", jobs[4].getThread());
//let the two non-conflicting jobs execute together
for (int i = 0; i < 2; i++) {
assertTrue("7. " + i, jobs[i].getThread() instanceof AsynchExecThread);
status[i] = TestBarrier.STATUS_WAIT_FOR_DONE;
}
//wait until the non-conflicting jobs are done
TestBarrier.waitForStatus(status, 1, TestBarrier.STATUS_DONE);
//the third job should still be in the running state
assertEquals("8.1", Job.RUNNING, jobs[2].getState());
//the 2 conflicting jobs should still be in the waiting state
assertEquals("8.2", Job.WAITING, jobs[3].getState());
assertEquals("8.3", Job.WAITING, jobs[4].getState());
//let the third job finish execution
assertTrue("8.4", jobs[2].getThread() instanceof AsynchExecThread);
status[2] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the third job is done
TestBarrier.waitForStatus(status, 2, TestBarrier.STATUS_DONE);
//the fourth job should now start running, the fifth job should still be waiting
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.1", Job.RUNNING, jobs[3].getState());
assertEquals("9.2", Job.WAITING, jobs[4].getState());
//let the fourth job run, the fifth job is still waiting
status[3] = TestBarrier.STATUS_START;
assertEquals("9.3", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_WAIT_FOR_START);
status[3] = TestBarrier.STATUS_WAIT_FOR_RUN;
assertEquals("9.4", Job.WAITING, jobs[4].getState());
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_RUNNING);
assertEquals("9.5", Job.WAITING, jobs[4].getState());
//cancel the fifth job, finish the fourth job
jobs[4].cancel();
assertTrue("9.6", jobs[3].getThread() instanceof AsynchExecThread);
status[3] = TestBarrier.STATUS_WAIT_FOR_DONE;
//wait until the fourth job is done
TestBarrier.waitForStatus(status, 3, TestBarrier.STATUS_DONE);
//the status for the first 4 jobs should be STATUS_OK
//the threads should have been reset to null
for (int i = 0; i < status.length - 1; i++) {
assertEquals("10." + i, TestBarrier.STATUS_DONE, status[i]);
assertEquals("11." + i, Job.NONE, jobs[i].getState());
assertEquals("12." + i, IStatus.OK, jobs[i].getResult().getSeverity());
assertNull("13." + i, jobs[i].getThread());
}
//the fifth job should have null as its status (it never finished running)
//the thread for it should have also been reset
assertEquals("14.1", TestBarrier.STATUS_WAIT_FOR_START, status[4]);
assertEquals("14.2", Job.NONE, jobs[4].getState());
assertNull("14.3", jobs[4].getResult());
assertNull("14.4", jobs[4].getThread());
}
|
diff --git a/src/main/java/org/couchbase/mock/http/Authenticator.java b/src/main/java/org/couchbase/mock/http/Authenticator.java
index 0c1798e..392487f 100644
--- a/src/main/java/org/couchbase/mock/http/Authenticator.java
+++ b/src/main/java/org/couchbase/mock/http/Authenticator.java
@@ -1,114 +1,115 @@
/**
* Copyright 2011 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.couchbase.mock.http;
import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal;
import java.io.IOException;
import java.util.Map;
import org.couchbase.mock.Bucket;
/**
* @author Sergey Avseyev
*/
public class Authenticator extends BasicAuthenticator {
private final String adminName;
private final String adminPass;
private String currentBucketName;
private final Map<String, Bucket> buckets;
public Authenticator(String username, String password, Map<String, Bucket> buckets) {
super("Couchbase Mock");
this.adminName = username;
this.adminPass = password;
this.buckets = buckets;
}
@SuppressWarnings("SimplifiableIfStatement")
@Override
public boolean checkCredentials(String username, String password) {
// Always allow admin
if (adminName.equals(username) && adminPass.equals(password)) {
return true;
}
Bucket bucket = buckets.get(username);
if (bucket == null) {
// No such bucket
return false;
}
// No credentials
if (username.isEmpty()) {
return bucket.getPassword().isEmpty();
}
if (!currentBucketName.equals(username)) {
return false;
}
String bucketPassword = bucket.getPassword();
return bucketPassword.isEmpty() || bucketPassword.equals(password);
}
@Override
public Result authenticate(HttpExchange exchange) {
String path = exchange.getRequestURI().normalize().getPath();
path = path.replaceAll("^/", "");
String[] components = path.split("/");
exchange.setAttribute(realm, this);
// pools, default, buckets(Streaming)/ bucket
currentBucketName = null;
if (components.length > 3 && components[2].startsWith("buckets")) {
currentBucketName = components[3];
}
AuthContext context = null;
String auth = exchange.getRequestHeaders().getFirst("Authorization");
if (auth != null) {
try {
context = new AuthContext(auth);
} catch (IOException e) {
return new Failure(400);
}
}
// For now, if we don't have a bucket name, just continue
if (currentBucketName == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
Bucket bucket = buckets.get(currentBucketName);
- if (bucket != null) {
- // Have a bucket
+ if (bucket == null) {
+ return new Failure(404);
+ } else {
if ((bucket.getPassword() == null || bucket.getPassword().isEmpty()) && context == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
}
return super.authenticate(exchange);
}
public String getAdminName() {
return adminName;
}
}
| true | true |
public Result authenticate(HttpExchange exchange) {
String path = exchange.getRequestURI().normalize().getPath();
path = path.replaceAll("^/", "");
String[] components = path.split("/");
exchange.setAttribute(realm, this);
// pools, default, buckets(Streaming)/ bucket
currentBucketName = null;
if (components.length > 3 && components[2].startsWith("buckets")) {
currentBucketName = components[3];
}
AuthContext context = null;
String auth = exchange.getRequestHeaders().getFirst("Authorization");
if (auth != null) {
try {
context = new AuthContext(auth);
} catch (IOException e) {
return new Failure(400);
}
}
// For now, if we don't have a bucket name, just continue
if (currentBucketName == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
Bucket bucket = buckets.get(currentBucketName);
if (bucket != null) {
// Have a bucket
if ((bucket.getPassword() == null || bucket.getPassword().isEmpty()) && context == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
}
return super.authenticate(exchange);
}
|
public Result authenticate(HttpExchange exchange) {
String path = exchange.getRequestURI().normalize().getPath();
path = path.replaceAll("^/", "");
String[] components = path.split("/");
exchange.setAttribute(realm, this);
// pools, default, buckets(Streaming)/ bucket
currentBucketName = null;
if (components.length > 3 && components[2].startsWith("buckets")) {
currentBucketName = components[3];
}
AuthContext context = null;
String auth = exchange.getRequestHeaders().getFirst("Authorization");
if (auth != null) {
try {
context = new AuthContext(auth);
} catch (IOException e) {
return new Failure(400);
}
}
// For now, if we don't have a bucket name, just continue
if (currentBucketName == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
Bucket bucket = buckets.get(currentBucketName);
if (bucket == null) {
return new Failure(404);
} else {
if ((bucket.getPassword() == null || bucket.getPassword().isEmpty()) && context == null) {
return new Authenticator.Success(new HttpPrincipal("", realm));
}
}
return super.authenticate(exchange);
}
|
diff --git a/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java b/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
index a4846ba..09b58b0 100644
--- a/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
+++ b/src/main/java/in/mDev/MiracleM4n/mChatSuite/commands/MECommandSender.java
@@ -1,278 +1,280 @@
package in.mDev.MiracleM4n.mChatSuite.commands;
import in.mDev.MiracleM4n.mChatSuite.mChatSuite;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.player.SpoutPlayer;
public class MECommandSender implements CommandExecutor {
mChatSuite plugin;
public MECommandSender(mChatSuite plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
- if (plugin.isAFK.get(player.getName()))
+ if (plugin.isAFK.get(player.getName())) {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
+ return true;
+ }
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
- players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
+ players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
- sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
+ sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget.getName()));
} else
- plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
+ plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
- if (plugin.getAPI().ParseTabbedList(afkTarget).length() > 15) {
- String pLName = plugin.getAPI().ParseTabbedList(afkTarget);
+ if (plugin.getAPI().ParseTabbedList(afkTarget.getName()).length() > 15) {
+ String pLName = plugin.getAPI().ParseTabbedList(afkTarget.getName());
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
- afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget));
+ afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget.getName()));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
- players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
+ players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
- sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
+ sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget.getName()));
} else
- plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
+ plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
- if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget)).length() > 15) {
- String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget);
+ if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName())).length() > 15) {
+ String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName());
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
- afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget));
+ afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName()));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
void formatList(CommandSender sender) {
String msg = "";
String[] msgS;
for (Player players : plugin.getServer().getOnlinePlayers()) {
String iVar = plugin.getInfoReader().getInfo(players, plugin.listVar);
String mName = plugin.getAPI().ParseListCmd(players.getName());
if (iVar.isEmpty())
continue;
if (plugin.isAFK.get(players.getName())) {
if (msg.contains(iVar + ": &f")) {
msg = msg.replace(iVar + ": &f", iVar + ": &f&4[" + plugin.getLocale().getOption("AFK") + "]" + mName + "&f, &f");
} else {
msg += (iVar + ": &f&4[" + plugin.getLocale().getOption("AFK") + "]" + mName + "&f, &f" + '\n');
}
} else {
if (msg.contains(iVar + ": &f")) {
msg = msg.replace(iVar + ": &f", iVar + ": &f" + mName + "&f, &f");
} else {
msg += (iVar + ": &f" + mName + "&f, &f" + '\n');
}
}
if (!msg.contains("" + '\n'))
msg += '\n';
}
if (msg.contains("" + '\n')) {
msgS = msg.split("" + '\n');
for (String arg : msgS) {
sender.sendMessage(plugin.getAPI().addColour(arg));
}
sender.sendMessage(plugin.getAPI().addColour("&6-------------------------"));
return;
}
sender.sendMessage(plugin.getAPI().addColour(msg));
}
void formatWho(CommandSender sender, Player recipient) {
String recipientName = plugin.getAPI().ParsePlayerName(recipient);
Integer locX = (int) recipient.getLocation().getX();
Integer locY = (int) recipient.getLocation().getY();
Integer locZ = (int) recipient.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
String world = recipient.getWorld().getName();
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + " Name: " + recipient.getName()));
sender.sendMessage(plugin.getAPI().addColour("Display Name: " + recipient.getDisplayName()));
sender.sendMessage(plugin.getAPI().addColour("Formatted Name: " + recipientName));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s Location: [ " + loc + " ]"));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s World: " + world));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s Health: " + plugin.getAPI().healthBar(recipient) + " " + recipient.getHealth() + "/20"));
sender.sendMessage(plugin.getAPI().addColour(plugin.getLocale().getOption("player") + "'s IP: " + recipient.getAddress().toString().replace("/", "")));
sender.sendMessage(plugin.getAPI().addColour("Current Item: " + recipient.getItemInHand().getType().name()));
sender.sendMessage(plugin.getAPI().addColour("Entity ID: #" + recipient.getEntityId()));
}
String formatMessage(String message) {
return (plugin.getAPI().addColour("&4[" + (plugin.pdfFile.getName()) + "] " + message));
}
String formatPNF(String playerNotFound) {
return (plugin.getAPI().addColour(formatMessage("") + " " + plugin.getLocale().getOption("player") + " &e" + playerNotFound + " &4" + plugin.getLocale().getOption("notFound")));
}
}
| false | true |
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
if (plugin.isAFK.get(player.getName()))
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
if (plugin.getAPI().ParseTabbedList(afkTarget).length() > 15) {
String pLName = plugin.getAPI().ParseTabbedList(afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget)).length() > 15) {
String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget);
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
|
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String commandName = command.getName();
if (!plugin.mChatEB) {
sender.sendMessage(formatMessage(plugin.getAPI().addColour("mChatEssentials' functions are currently disabled.")));
return true;
}
if (commandName.equalsIgnoreCase("mchatme")) {
if (args.length > 0) {
String message = "";
for (String arg : args)
message += " " + arg;
message = message.trim();
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.getAPI().checkPermissions(player, "mchat.me"))
plugin.getServer().broadcastMessage(plugin.getAPI().ParseMe(player, message));
else
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
} else {
String senderName = "Console";
plugin.getServer().broadcastMessage("* " + senderName + " " + message);
plugin.getAPI().log("* " + senderName + " " + message);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatwho")) {
if (args.length > 0) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.who")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
} else {
Player receiver = plugin.getServer().getPlayer(args[0]);
formatWho(sender, receiver);
return true;
}
}
} else if (commandName.equalsIgnoreCase("mchatafk")) {
String message = " Away From Keyboard";
if (args.length > 0) {
message = "";
for (String arg : args)
message += " " + arg;
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (plugin.isAFK.get(player.getName()) != null)
if (plugin.isAFK.get(player.getName())) {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + player.getName());
return true;
}
if (!plugin.getAPI().checkPermissions(player, "mchat.afk")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "mchatafkother " + sender.getName() + message);
return true;
} else {
plugin.getAPI().log(formatMessage("Console's can't be AFK."));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatafkother")) {
String message = " Away From Keyboard";
if (args.length > 1) {
message = "";
for (int i = 1; i < args.length; ++i)
message += " " + args[i];
}
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.afkother")) {
sender.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
if (plugin.getServer().getPlayer(args[0]) == null) {
sender.sendMessage(formatPNF(args[0]));
return true;
}
Player afkTarget = plugin.getServer().getPlayer(args[0]);
if (plugin.isAFK.get(afkTarget.getName()) != null &&
plugin.isAFK.get(afkTarget.getName())) {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("noLongerAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("notAFK"));
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget.getName()));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("notAFK"));
afkTarget.setSleepingIgnored(false);
plugin.isAFK.put(afkTarget.getName(), false);
if (plugin.useAFKList)
if (plugin.getAPI().ParseTabbedList(afkTarget.getName()).length() > 15) {
String pLName = plugin.getAPI().ParseTabbedList(afkTarget.getName());
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().ParseTabbedList(afkTarget.getName()));
return true;
} else {
if (plugin.spoutB) {
for (Player players : plugin.getServer().getOnlinePlayers()) {
SpoutPlayer sPlayers = (SpoutPlayer) players;
if (sPlayers.isSpoutCraftEnabled())
sPlayers.sendNotification(afkTarget.getName(), plugin.getLocale().getOption("isAFK"), Material.PAPER);
else
players.sendMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
}
SpoutPlayer sPlayer = (SpoutPlayer) afkTarget;
sPlayer.setTitle(ChatColor.valueOf(plugin.getLocale().getOption("spoutChatColour").toUpperCase()) + "- " + plugin.getLocale().getOption("AFK") + " -" + '\n' + plugin.getAPI().ParsePlayerName(afkTarget.getName()));
} else
plugin.getServer().broadcastMessage(plugin.getAPI().ParsePlayerName(afkTarget.getName()) + " " + plugin.getLocale().getOption("isAFK") + " [" + message + " ]");
afkTarget.setSleepingIgnored(true);
plugin.isAFK.put(afkTarget.getName(), true);
plugin.AFKLoc.put(afkTarget.getName(), afkTarget.getLocation());
if (plugin.useAFKList)
if ((plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName())).length() > 15) {
String pLName = plugin.getAPI().addColour("[<gold>" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName());
pLName = pLName.substring(0, 16);
afkTarget.setPlayerListName(pLName);
} else
afkTarget.setPlayerListName(plugin.getAPI().addColour("<gold>[" + plugin.getLocale().getOption("AFK") + "] " + afkTarget.getName()));
return true;
}
} else if (commandName.equalsIgnoreCase("mchatlist")) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (!plugin.getAPI().checkPermissions(player, "mchat.list")) {
player.sendMessage(formatMessage(plugin.getLocale().getOption("noPermissions") + " " + commandName + "."));
return true;
}
}
// My Way
// sender.sendMessage(plugin.getAPI().addColour("&4" + plugin.getLocale().pOffline + ": &8" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers()));
// Waxdt's Way
sender.sendMessage(plugin.getAPI().addColour("&6-- There are &8" + plugin.getServer().getOnlinePlayers().length + "&6 out of the maximum of &8" + plugin.getServer().getMaxPlayers() + "&6 Players online. --"));
formatList(sender);
return true;
}
return false;
}
|
diff --git a/LabBook/source/LObjMinimizedView.java b/LabBook/source/LObjMinimizedView.java
index 602b702..a416913 100644
--- a/LabBook/source/LObjMinimizedView.java
+++ b/LabBook/source/LObjMinimizedView.java
@@ -1,65 +1,65 @@
package org.concord.LabBook;
import waba.ui.*;
import waba.util.*;
import waba.fx.*;
import org.concord.waba.extra.ui.*;
import org.concord.waba.extra.event.*;
import org.concord.waba.extra.probware.probs.*;
import org.concord.waba.extra.probware.*;
import extra.ui.*;
import extra.util.*;
public class LObjMinimizedView extends LabObjectView
{
public int rColor = 0;
public int gColor = 0;
public int bColor = 255;
LabObject minObj;
public LObjMinimizedView(LabObject obj)
{
super(null, obj, null);
minObj = obj;
}
public void layout(boolean sDone)
{
}
public void onPaint(Graphics g)
{
if(minObj != null && minObj.getName() != null){
g.setColor(rColor,gColor,bColor);
g.drawText(minObj.getName(), 0, 0);
FontMetrics fm = getFontMetrics(MainWindow.defaultFont);
int lineY = fm.getHeight();
g.setColor(rColor,gColor,bColor);
- g.drawLine(0,lineY, width, lineY);
+ g.drawLine(0,lineY, fm.getTextWidth(minObj.getName()), lineY);
}
}
public void close()
{
}
public int getPreferredWidth()
{
if(minObj != null && minObj.getName() != null){
FontMetrics fm = getFontMetrics(MainWindow.defaultFont);
return fm.getTextWidth(minObj.getName());
}
return -1;
}
public int getPreferredHeight()
{
if(minObj != null && minObj.getName() != null){
FontMetrics fm = getFontMetrics(MainWindow.defaultFont);
return fm.getHeight()+2;
}
return -1;
}
}
| true | true |
public void onPaint(Graphics g)
{
if(minObj != null && minObj.getName() != null){
g.setColor(rColor,gColor,bColor);
g.drawText(minObj.getName(), 0, 0);
FontMetrics fm = getFontMetrics(MainWindow.defaultFont);
int lineY = fm.getHeight();
g.setColor(rColor,gColor,bColor);
g.drawLine(0,lineY, width, lineY);
}
}
|
public void onPaint(Graphics g)
{
if(minObj != null && minObj.getName() != null){
g.setColor(rColor,gColor,bColor);
g.drawText(minObj.getName(), 0, 0);
FontMetrics fm = getFontMetrics(MainWindow.defaultFont);
int lineY = fm.getHeight();
g.setColor(rColor,gColor,bColor);
g.drawLine(0,lineY, fm.getTextWidth(minObj.getName()), lineY);
}
}
|
diff --git a/Test.java b/Test.java
index b585fe6..2862052 100644
--- a/Test.java
+++ b/Test.java
@@ -1,12 +1,12 @@
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
- System.Out.println("hello world");
+ System.out.println("hello world");
}
}
| true | true |
public static void main(String[] args) {
System.Out.println("hello world");
}
|
public static void main(String[] args) {
System.out.println("hello world");
}
|
diff --git a/src/com/id/file/Graveyard.java b/src/com/id/file/Graveyard.java
index 34204d8..8aba258 100644
--- a/src/com/id/file/Graveyard.java
+++ b/src/com/id/file/Graveyard.java
@@ -1,136 +1,136 @@
package com.id.file;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import com.id.git.FileDelta;
public class Graveyard implements File.Listener {
private final List<Tombstone> tombstones = new ArrayList<Tombstone>();
private final List<Grave> graves = new ArrayList<Grave>();
private Grave otherGrave;
public Graveyard(List<String> lines) {
for (String line : lines) {
tombstones.add(new Tombstone(line, line));
graves.add(new Grave());
}
reset();
}
public void reset() {
resetRange(0, tombstones.size() - 1);
otherGrave = new Grave();
}
public void resetRange(int from, int to) {
for (int i = from; i <= to; i++) {
tombstones.get(i).reset();
graves.set(i, new Grave());
}
}
@Override
public void onLineInserted(int y, String line) {
Pair splitResult = null;
Grave previousGrave = getGrave(y - 1);
splitResult = previousGrave.split(line);
if (splitResult == null) {
splitResult = new Pair(new Tombstone(line, null), new Grave());
}
tombstones.add(y, splitResult.getTombstone());
graves.add(y, splitResult.getGrave());
}
@Override
public void onLineRemoved(int y, String line) {
Tombstone tombstone = tombstones.remove(y);
Grave grave = graves.remove(y);
if (!tombstone.getCurrent().equals(line)) {
throw new IllegalStateException();
}
if (tombstone.getStatus() == Tombstone.Status.NEW && grave.isEmpty()) {
// Deleting a new line with an empty grave yields nothing to inherit.
return;
}
Grave previousGrave = getGrave(y - 1);
previousGrave.inherit(tombstone, grave);
}
@Override
public void onLineChanged(int y, String oldLine, String newLine) {
tombstones.get(y).setCurrent(newLine);
}
public void debug(int y) {
System.out.println(tombstones.get(y));
System.out.println(getGrave(y));
}
public Tombstone.Status getStatus(int y) {
return tombstones.get(y).getStatus();
}
public Grave getGrave(int y) {
if (y == -1) {
return otherGrave;
}
return graves.get(y);
}
public Tombstone getTombstone(int y) {
return tombstones.get(y);
}
public int size() {
return tombstones.size();
}
public boolean isAllGravesEmpty() {
for (Grave grave : graves) {
if (!grave.isEmpty()) {
return false;
}
}
return true;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
for (int i = 0; i < graves.size(); i++) {
result.append(i)
.append(": ")
.append(tombstones.get(i))
.append(" / ")
.append(getGrave(i))
.append("\n");
}
return result.toString();
}
public void setDiffMarkers(FileDelta delta) {
reset();
for (Entry<Integer, String> addition : delta.getAdditions().entrySet()) {
int y = addition.getKey();
tombstones.set(y, new Tombstone(addition.getValue(), null));
}
for (Entry<Integer, List<String>> deletion : delta.getDeletions().entrySet()) {
int y = deletion.getKey();
for (Tombstone tombstone : Tombstone.deletionsFromLines(deletion.getValue())) {
- graves.get(y).inherit(tombstone, new Grave());
+ getGrave(y).inherit(tombstone, new Grave());
}
}
}
public boolean isAllStatusNormal() {
for (Tombstone tombstone : tombstones) {
if (tombstone.getStatus() != Tombstone.Status.NORMAL) {
return false;
}
}
return true;
}
}
| true | true |
public void setDiffMarkers(FileDelta delta) {
reset();
for (Entry<Integer, String> addition : delta.getAdditions().entrySet()) {
int y = addition.getKey();
tombstones.set(y, new Tombstone(addition.getValue(), null));
}
for (Entry<Integer, List<String>> deletion : delta.getDeletions().entrySet()) {
int y = deletion.getKey();
for (Tombstone tombstone : Tombstone.deletionsFromLines(deletion.getValue())) {
graves.get(y).inherit(tombstone, new Grave());
}
}
}
|
public void setDiffMarkers(FileDelta delta) {
reset();
for (Entry<Integer, String> addition : delta.getAdditions().entrySet()) {
int y = addition.getKey();
tombstones.set(y, new Tombstone(addition.getValue(), null));
}
for (Entry<Integer, List<String>> deletion : delta.getDeletions().entrySet()) {
int y = deletion.getKey();
for (Tombstone tombstone : Tombstone.deletionsFromLines(deletion.getValue())) {
getGrave(y).inherit(tombstone, new Grave());
}
}
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java b/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java
index 68824ad3..12021862 100644
--- a/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java
+++ b/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java
@@ -1,537 +1,541 @@
/*
* Copyright (C) 2006 Steve Ratcliffe
*
* 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.
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 07-Dec-2006
*/
package uk.me.parabola.imgfmt.app.trergn;
import java.util.ArrayList;
import java.util.List;
import uk.me.parabola.imgfmt.app.Area;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.imgfmt.app.ImgFileWriter;
import uk.me.parabola.imgfmt.app.Label;
import uk.me.parabola.imgfmt.app.lbl.LBLFile;
import uk.me.parabola.log.Logger;
/**
* The map is divided into areas, depending on the zoom level. These are
* known as subdivisions.
*
* A subdivision 'belongs' to a zoom level and cannot be interpreted correctly
* without knowing the <i>bitsPerCoord</i> of the associated zoom level.
*
* Subdivisions also form a tree as subdivisions are further divided at
* lower levels. The subdivisions need to know their child divisions
* because this information is represented in the map.
*
* @author Steve Ratcliffe
*/
public class Subdivision {
private static final Logger log = Logger.getLogger(Subdivision.class);
private static final int MAP_POINT = 0;
private static final int MAP_INDEXED_POINT = 1;
private static final int MAP_LINE = 2;
private static final int MAP_SHAPE = 3;
private final LBLFile lblFile;
private final RGNFile rgnFile;
// The start pointer is set for read and write. The end pointer is only
// set for subdivisions that are read from a file.
private int startRgnPointer;
private int endRgnPointer;
private int lastMapElement;
// The zoom level contains the number of bits per coordinate which is
// critical for scaling quantities by.
private final Zoom zoomLevel;
private boolean hasPoints;
private boolean hasIndPoints;
private boolean hasPolylines;
private boolean hasPolygons;
private int numPolylines;
// The location of the central point, not scaled AFAIK
private final int longitude;
private final int latitude;
// The width and the height in map units scaled by the bits-per-coordinate
// that applies at the map level.
private final int width;
private final int height;
private int number;
// Set if this is the last one.
private boolean last;
private final List<Subdivision> divisions = new ArrayList<Subdivision>();
private int extTypeAreasOffset;
private int extTypeLinesOffset;
private int extTypePointsOffset;
private int extTypeAreasSize;
private int extTypeLinesSize;
private int extTypePointsSize;
/**
* Subdivisions can not be created directly, use either the
* {@link #topLevelSubdivision} or {@link #createSubdivision} factory
* methods.
*
* @param ifiles The internal files.
* @param area The area this subdivision should cover.
* @param z The zoom level.
*/
private Subdivision(InternalFiles ifiles, Area area, Zoom z) {
this.lblFile = ifiles.getLblFile();
this.rgnFile = ifiles.getRgnFile();
this.zoomLevel = z;
int shift = getShift();
int mask = getMask();
this.latitude = (area.getMinLat() + area.getMaxLat())/2;
this.longitude = (area.getMinLong() + area.getMaxLong())/2;
int w = ((area.getWidth() + 1)/2 + mask) >> shift;
- if (w > 0x7fff)
+ if (w > 0x7fff) {
+ log.warn("Subdivision width is " + w + " at " + new Coord(latitude, longitude));
w = 0x7fff;
+ }
int h = ((area.getHeight() + 1)/2 + mask) >> shift;
- if (h > 0xffff)
+ if (h > 0xffff) {
+ log.warn("Subdivision height is " + h + " at " + new Coord(latitude, longitude));
h = 0xffff;
+ }
this.width = w;
this.height = h;
}
private Subdivision(Zoom z, SubdivData data) {
lblFile = null;
rgnFile = null;
zoomLevel = z;
latitude = data.getLat();
longitude = data.getLon();
this.width = data.getWidth();
this.height = data.getHeight();
startRgnPointer = data.getRgnPointer();
endRgnPointer = data.getEndRgnOffset();
int elem = data.getFlags();
if ((elem & 0x10) != 0)
setHasPoints(true);
if ((elem & 0x20) != 0)
setHasIndPoints(true);
if ((elem & 0x40) != 0)
setHasPolylines(true);
if ((elem & 0x80) != 0)
setHasPolygons(true);
}
/**
* Create a subdivision at a given zoom level.
*
* @param ifiles The RGN and LBL ifiles.
* @param area The (unshifted) area that the subdivision covers.
* @param zoom The zoom level that this division occupies.
*
* @return A new subdivision.
*/
public Subdivision createSubdivision(InternalFiles ifiles,
Area area, Zoom zoom)
{
Subdivision div = new Subdivision(ifiles, area, zoom);
zoom.addSubdivision(div);
addSubdivision(div);
return div;
}
/**
* This should be called only once per map to create the top level
* subdivision. The top level subdivision covers the whole map and it
* must be empty.
*
* @param ifiles The LBL and RGN ifiles.
* @param area The area bounded by the map.
* @param zoom The zoom level which must be the highest (least detailed)
* zoom in the map.
*
* @return The new subdivision.
*/
public static Subdivision topLevelSubdivision(InternalFiles ifiles,
Area area, Zoom zoom)
{
Subdivision div = new Subdivision(ifiles, area, zoom);
zoom.addSubdivision(div);
return div;
}
/**
* Create a subdivision that only contains the number. This is only
* used when reading cities and similar such usages that do not really
* require the full subdivision to be present.
* @param number The subdivision number.
* @return An empty subdivision. Any operation other than getting the
* subdiv number is likely to fail.
*/
public static Subdivision createEmptySubdivision(int number) {
Subdivision sd = new Subdivision(null, new SubdivData(0,0,0,0,0,0,0));
sd.setNumber(number);
return sd;
}
public static Subdivision readSubdivision(Zoom zoom, SubdivData subdivData) {
return new Subdivision(zoom, subdivData);
}
public Zoom getZoom() {
return zoomLevel;
}
/**
* Get the shift value, that is the number of bits to left shift by for
* values that need to be saved shifted in the file. Related to the
* resolution.
*
* @return The shift value. It is 24 minus the number of bits per coord.
* @see #getResolution()
*/
public final int getShift() {
return 24 - zoomLevel.getResolution();
}
/**
* Get the shift mask. The bits that will be lost due to the resolution
* shift level.
*
* @return A bit mask with the lower <i>shift</i> bits set.
*/
public int getMask() {
return (1 << getShift()) - 1;
}
/**
* Get the resolution of this division. Resolution goes from 1 to 24
* and the higher the number the more detail there is.
*
* @return The resolution.
*/
public final int getResolution() {
return zoomLevel.getResolution();
}
/**
* Format this record to the file.
*
* @param file The file to write to.
*/
public void write(ImgFileWriter file) {
log.debug("write subdiv", latitude, longitude);
file.put3(startRgnPointer);
file.put(getType());
file.put3(longitude);
file.put3(latitude);
assert width <= 0x7fff;
assert height <= 0xffff;
file.putChar((char) (width | ((last) ? 0x8000 : 0)));
file.putChar((char) height);
if (!divisions.isEmpty()) {
file.putChar((char) getNextLevel());
}
}
public Point createPoint(String name) {
Point p = new Point(this);
Label label = lblFile.newLabel(name);
p.setLabel(label);
return p;
}
public Polyline createLine(String name, String ref) {
Label label = lblFile.newLabel(name);
Polyline pl = new Polyline(this);
pl.setLabel(label);
if(ref != null) {
// ref may contain multiple ids separated by ";"
for(String r : ref.split(";")) {
String tr = r.trim();
if(tr.length() > 0) {
//System.err.println("Adding ref " + tr + " to road " + name);
pl.addRefLabel(lblFile.newLabel(tr));
}
}
}
return pl;
}
public void setPolylineNumber(Polyline pl) {
pl.setNumber(++numPolylines);
}
public Polygon createPolygon(String name) {
Label label = lblFile.newLabel(name);
Polygon pg = new Polygon(this);
pg.setLabel(label);
return pg;
}
public void setNumber(int n) {
number = n;
}
public void setLast(boolean last) {
this.last = last;
}
public void setStartRgnPointer(int startRgnPointer) {
this.startRgnPointer = startRgnPointer;
}
public int getStartRgnPointer() {
return startRgnPointer;
}
public int getEndRgnPointer() {
return endRgnPointer;
}
public int getLongitude() {
return longitude;
}
public int getLatitude() {
return latitude;
}
public void setHasPoints(boolean hasPoints) {
this.hasPoints = hasPoints;
}
public void setHasIndPoints(boolean hasIndPoints) {
this.hasIndPoints = hasIndPoints;
}
public void setHasPolylines(boolean hasPolylines) {
this.hasPolylines = hasPolylines;
}
public void setHasPolygons(boolean hasPolygons) {
this.hasPolygons = hasPolygons;
}
public boolean hasPoints() {
return hasPoints;
}
public boolean hasIndPoints() {
return hasIndPoints;
}
public boolean hasPolylines() {
return hasPolylines;
}
public boolean hasPolygons() {
return hasPolygons;
}
/**
* Needed if it exists and is not first, ie there is a points
* section.
* @return true if pointer needed
*/
public boolean needsIndPointPtr() {
return hasIndPoints && hasPoints;
}
/**
* Needed if it exists and is not first, ie there is a points or
* indexed points section.
* @return true if pointer needed.
*/
public boolean needsPolylinePtr() {
return hasPolylines && (hasPoints || hasIndPoints);
}
/**
* As this is last in the list it is needed if it exists and there
* is another section.
* @return true if pointer needed.
*/
public boolean needsPolygonPtr() {
return hasPolygons && (hasPoints || hasIndPoints || hasPolylines);
}
public String toString() {
return "Sub" + zoomLevel + '(' + new Coord(latitude, longitude).toOSMURL() + ')';
}
/**
* Get a type that shows if this area has lines, points etc.
*
* @return A code showing what kinds of element are in this subdivision.
*/
private byte getType() {
byte b = 0;
if (hasPoints)
b |= 0x10;
if (hasIndPoints)
b |= 0x20;
if (hasPolylines)
b |= 0x40;
if (hasPolygons)
b |= 0x80;
return b;
}
/**
* Get the number of the first subdivision at the next level.
* @return The first subdivision at the next level.
*/
private int getNextLevel() {
return divisions.get(0).getNumber();
}
public boolean hasNextLevel() {
return !divisions.isEmpty();
}
public void startDivision() {
rgnFile.startDivision(this);
extTypeAreasOffset = rgnFile.getExtTypeAreasSize();
extTypeLinesOffset = rgnFile.getExtTypeLinesSize();
extTypePointsOffset = rgnFile.getExtTypePointsSize();
}
public void endDivision() {
extTypeAreasSize = rgnFile.getExtTypeAreasSize() - extTypeAreasOffset;
extTypeLinesSize = rgnFile.getExtTypeLinesSize() - extTypeLinesOffset;
extTypePointsSize = rgnFile.getExtTypePointsSize() - extTypePointsOffset;
}
public void writeExtTypeOffsetsRecord(ImgFileWriter file) {
file.putInt(extTypeAreasOffset);
file.putInt(extTypeLinesOffset);
file.putInt(extTypePointsOffset);
int kinds = 0;
if(extTypeAreasSize != 0)
++kinds;
if(extTypeLinesSize != 0)
++kinds;
if(extTypePointsSize != 0)
++kinds;
file.put((byte)kinds);
}
public void writeLastExtTypeOffsetsRecord(ImgFileWriter file) {
file.putInt(rgnFile.getExtTypeAreasSize());
file.putInt(rgnFile.getExtTypeLinesSize());
file.putInt(rgnFile.getExtTypePointsSize());
file.put((byte)0);
}
/**
* Add this subdivision as our child at the next level. Each subdivision
* can be further divided into smaller divisions. They form a tree like
* arrangement.
*
* @param sd One of our subdivisions.
*/
private void addSubdivision(Subdivision sd) {
divisions.add(sd);
}
public int getNumber() {
return number;
}
/**
* We are starting to draw the points. These must be done first.
*/
public void startPoints() {
if (lastMapElement > MAP_POINT)
throw new IllegalStateException("Points must be drawn first");
lastMapElement = MAP_POINT;
}
/**
* We are starting to draw the lines. These must be done before
* polygons.
*/
public void startIndPoints() {
if (lastMapElement > MAP_INDEXED_POINT)
throw new IllegalStateException("Indexed points must be done before lines and polygons");
lastMapElement = MAP_INDEXED_POINT;
rgnFile.setIndPointPtr();
}
/**
* We are starting to draw the lines. These must be done before
* polygons.
*/
public void startLines() {
if (lastMapElement > MAP_LINE)
throw new IllegalStateException("Lines must be done before polygons");
lastMapElement = MAP_LINE;
rgnFile.setPolylinePtr();
}
/**
* We are starting to draw the shapes. This is done last.
*/
public void startShapes() {
lastMapElement = MAP_SHAPE;
rgnFile.setPolygonPtr();
}
/**
* Convert an absolute Lat to a local, shifted value
*/
public int roundLatToLocalShifted(int absval) {
int shift = getShift();
int val = absval - getLatitude();
val += ((1 << shift) / 2);
return (val >> shift);
}
/**
* Convert an absolute Lon to a local, shifted value
*/
public int roundLonToLocalShifted(int absval) {
int shift = getShift();
int val = absval - getLongitude();
val += ((1 << shift) / 2);
return (val >> shift);
}
}
| false | true |
private Subdivision(InternalFiles ifiles, Area area, Zoom z) {
this.lblFile = ifiles.getLblFile();
this.rgnFile = ifiles.getRgnFile();
this.zoomLevel = z;
int shift = getShift();
int mask = getMask();
this.latitude = (area.getMinLat() + area.getMaxLat())/2;
this.longitude = (area.getMinLong() + area.getMaxLong())/2;
int w = ((area.getWidth() + 1)/2 + mask) >> shift;
if (w > 0x7fff)
w = 0x7fff;
int h = ((area.getHeight() + 1)/2 + mask) >> shift;
if (h > 0xffff)
h = 0xffff;
this.width = w;
this.height = h;
}
|
private Subdivision(InternalFiles ifiles, Area area, Zoom z) {
this.lblFile = ifiles.getLblFile();
this.rgnFile = ifiles.getRgnFile();
this.zoomLevel = z;
int shift = getShift();
int mask = getMask();
this.latitude = (area.getMinLat() + area.getMaxLat())/2;
this.longitude = (area.getMinLong() + area.getMaxLong())/2;
int w = ((area.getWidth() + 1)/2 + mask) >> shift;
if (w > 0x7fff) {
log.warn("Subdivision width is " + w + " at " + new Coord(latitude, longitude));
w = 0x7fff;
}
int h = ((area.getHeight() + 1)/2 + mask) >> shift;
if (h > 0xffff) {
log.warn("Subdivision height is " + h + " at " + new Coord(latitude, longitude));
h = 0xffff;
}
this.width = w;
this.height = h;
}
|
diff --git a/esmska/src/esmska/Main.java b/esmska/src/esmska/Main.java
index e5219c7c..a6f05e0a 100644
--- a/esmska/src/esmska/Main.java
+++ b/esmska/src/esmska/Main.java
@@ -1,114 +1,114 @@
/*
* Main.java
*
* Created on 24. srpen 2007, 22:20
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package esmska;
import esmska.gui.MainFrame;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import esmska.persistence.PersistenceManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jvnet.lafwidget.LafWidget;
/** Starter class for the whole program
*
* @author ripper
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
private static String configPath; //path to config files
/** Program starter method
* @param args the command line arguments
*/
public static void main(String[] args) {
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args))
System.exit(1);
configPath = clp.getConfigPath();
//portable mode
if (clp.isPortable() && configPath == null) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText("Vybrat");
chooser.setDialogTitle("Zvolte umístění konfiguračních souborů");
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
configPath = chooser.getSelectedFile().getPath();
}
//load user files
try {
if (configPath != null)
PersistenceManager.setProgramDir(configPath);
PersistenceManager pm = PersistenceManager.getInstance();
try {
pm.loadConfig();
- } catch (IOException ex) {
+ } catch (Exception ex) {
logger.log(Level.WARNING, "Could not load config file", ex);
}
try {
pm.loadOperators();
- } catch (IOException ex) {
+ } catch (Exception ex) {
logger.log(Level.WARNING, "Could not load operators", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load history file", ex);
}
- } catch (IOException ex) {
+ } catch (Exception ex) {
logger.log(Level.WARNING, "Could not create program dir or read config files", ex);
JOptionPane.showMessageDialog(null, "Nepodařilo se vytvořit adresář " +
"nebo číst z adresáře s konfigurací!",
"Chyba spouštění", JOptionPane.ERROR_MESSAGE);
}
//set L&F
try {
ThemeManager.setLaF();
- } catch (Throwable ex) {
+ } catch (Exception ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
//set Substance specific addons
UIManager.put(LafWidget.TEXT_EDIT_CONTEXT_MENU, Boolean.TRUE);
//start main frame
java.awt.EventQueue.invokeLater(new java.lang.Runnable() {
public void run() {
MainFrame.getInstance().setVisible(true);
}
});
}
}
| false | true |
public static void main(String[] args) {
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args))
System.exit(1);
configPath = clp.getConfigPath();
//portable mode
if (clp.isPortable() && configPath == null) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText("Vybrat");
chooser.setDialogTitle("Zvolte umístění konfiguračních souborů");
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
configPath = chooser.getSelectedFile().getPath();
}
//load user files
try {
if (configPath != null)
PersistenceManager.setProgramDir(configPath);
PersistenceManager pm = PersistenceManager.getInstance();
try {
pm.loadConfig();
} catch (IOException ex) {
logger.log(Level.WARNING, "Could not load config file", ex);
}
try {
pm.loadOperators();
} catch (IOException ex) {
logger.log(Level.WARNING, "Could not load operators", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load history file", ex);
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Could not create program dir or read config files", ex);
JOptionPane.showMessageDialog(null, "Nepodařilo se vytvořit adresář " +
"nebo číst z adresáře s konfigurací!",
"Chyba spouštění", JOptionPane.ERROR_MESSAGE);
}
//set L&F
try {
ThemeManager.setLaF();
} catch (Throwable ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
//set Substance specific addons
UIManager.put(LafWidget.TEXT_EDIT_CONTEXT_MENU, Boolean.TRUE);
//start main frame
java.awt.EventQueue.invokeLater(new java.lang.Runnable() {
public void run() {
MainFrame.getInstance().setVisible(true);
}
});
}
|
public static void main(String[] args) {
//parse commandline arguments
CommandLineParser clp = new CommandLineParser();
if (! clp.parseArgs(args))
System.exit(1);
configPath = clp.getConfigPath();
//portable mode
if (clp.isPortable() && configPath == null) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set system Look and Feel", ex);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText("Vybrat");
chooser.setDialogTitle("Zvolte umístění konfiguračních souborů");
chooser.setFileHidingEnabled(false);
chooser.setMultiSelectionEnabled(false);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
configPath = chooser.getSelectedFile().getPath();
}
//load user files
try {
if (configPath != null)
PersistenceManager.setProgramDir(configPath);
PersistenceManager pm = PersistenceManager.getInstance();
try {
pm.loadConfig();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load config file", ex);
}
try {
pm.loadOperators();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load operators", ex);
}
try {
pm.loadContacts();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load contacts file", ex);
}
try {
pm.loadQueue();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load queue file", ex);
}
try {
pm.loadHistory();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not load history file", ex);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not create program dir or read config files", ex);
JOptionPane.showMessageDialog(null, "Nepodařilo se vytvořit adresář " +
"nebo číst z adresáře s konfigurací!",
"Chyba spouštění", JOptionPane.ERROR_MESSAGE);
}
//set L&F
try {
ThemeManager.setLaF();
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not set Look and Feel", ex);
}
//set Substance specific addons
UIManager.put(LafWidget.TEXT_EDIT_CONTEXT_MENU, Boolean.TRUE);
//start main frame
java.awt.EventQueue.invokeLater(new java.lang.Runnable() {
public void run() {
MainFrame.getInstance().setVisible(true);
}
});
}
|
diff --git a/Extrasfeld.java b/Extrasfeld.java
index 70f5e6d..f177ce1 100644
--- a/Extrasfeld.java
+++ b/Extrasfeld.java
@@ -1,69 +1,66 @@
/**
* Klasse fuer Extrasfelder
* @author philip
*
*/
public class Extrasfeld extends Feld
{
/**
* Gibt an, welche Art von Extrafeld betreten wurde.
*/
public int art;
/**
* Wird veraendert, wenn Extra freigelegt wurde. Startzustand: Wahr
*/
private boolean covered=true;
/**
* Konstruktor zur Klasse Extrasfeld
* @param art: Art des Extras
*/
public Extrasfeld(int art){
this.art = art;
}
/**
* Zeichnet die Grafik des Extras
*/
public void draw(int x, int y){
if (covered==true){
Renderer.Tile_Break.draw(x*size, y*size);
Renderer.print(x*size, y*size, ""+art, 0.5f);
} else {
Renderer.Tile_Empty.draw(x*size, y*size);
switch(art)
{
case 1: Renderer.Tile_Health.draw(x*size, y*size); break; //Dieses Feld generiert ein zusaetzliches Leben, um einen Bombentreffer zu ueberleben}
case 2: Renderer.Tile_addbomb.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, um die Anzahl der Bomben, die man gleichzeitig legen kann, um 1 zu erhoehen
case 3: Renderer.Tile_kick.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, wodurch der Spieler dazu befaehigt wird, die Bomben linear zu treten
- case 4: //Dieses Feld generiert ein Upgrade um (fuer die naechste Bombe) eine Super-Bombe anstatt einer normalen Bombe zu legen. Die Super-Bombe hat <spezifikation>
- case 5: Renderer.Tile_confuse.draw(x*size, y*size); break;//Dieses Feld generiert eine temporaere Steuerungsbehinderung fuer alle feindlichen/anderen Spieler. Alle ausser der Spieler, der das Feld betritt, unterliegen einer umgekehrten Steuerung (Ausnahme: Bombe legen)
+ case 4: break;//Dieses Feld generiert die einmalige Befähigung, sich für 3 Sekunden unsichtbar zu machen.
+ case 5: Renderer.Tile_slow.draw(x*size, y*size); break;//Dieses Feld generiert eine temporaere Steuerungsbehinderung fuer alle feindlichen/anderen Spieler. Alle ausser der Spieler, der das Feld betritt, unterliegen einer umgekehrten Steuerung (Ausnahme: Bombe legen)
case 6: Renderer.Tile_teleport.draw(x*size, y*size); break;//Dieses Feld generiert ein Teleportationsfeld. Der Spieler der auf dieses Feld tritt wird mit sofortiger Wirkung zum entsprechenden Feld teleportiert
case 7: Renderer.Tile_speed.draw(x*size, y*size); break;//Dieses Feld generiert ein Upgrade, welches einen temporaeren Geschwindigkeitsbonus fuer den Spieler gibt, der es aufsammelt
- case 8: Renderer.Tile_slow.draw(x*size, y*size); break;//Dieses Feld generiert ein temporaere Spielerbehinderung. Alle gegnerischen/anderen Spieler sind nur noch 50-75% so schnell
- case 9: //Dieses Feld generiert bei Kontakt auf dem gesamten Spielfeld Bomben (5-10 Bomben? [Abhaengig davon, wie viele freie Felder es gibt]
- case 10: //Dieses Feld generiert ein Loch. Der Spieler, der dieses Loch betritt faellt darin hinein und stirbt (egal wie viele Leben dieser noch hatte = Instant Death). Weitere Spieler koennen dieses Feld gefahrlos ueberqueren
- case 11: //Dieses Feld generiert ein Uprade, welches temporaere Unverwundbarkeit verleiht. Dem Spieler wird kein Bombentreffer angerechnet. Fraglich: Wuerde er bei ART == 10 sterben?
- case 12: //Dieses Feld generiert einen FROST-SCHOCK. Der Spieler der es aufsammelt, darf sich temporaer nicht bewegen. Wenn der Frost-Schock vorbei ist, erhaelt der Spieler seine komplette Bewegungsfreiheit.
- case 13: //Dieses Feld generiert ein Upgrade zur Verbesserung der Bombenreichweite.
+ case 8: Renderer.Tile_confuse.draw(x*size, y*size); break;//Dieses Feld generiert eine temporäre Steuerungsbehinderung für alle feindlichen/anderen Spieler, in Form einer legbaren Falle.
+ case 9: //Dieses Feld generiert einen auslösbaren Schild.
+ case 10: //Dieses Feld generiert ein Upgrade zur Verbesserung der Bombenreichweite. case 12: //Dieses Feld generiert einen FROST-SCHOCK. Der Spieler der es aufsammelt, darf sich temporaer nicht bewegen. Wenn der Frost-Schock vorbei ist, erhaelt der Spieler seine komplette Bewegungsfreiheit.
}
}
}
/**
* Setzt covered auf false, wenn freigelegt wurde
*/
public void setUncovered(){
covered=false;
}
/**
* Abfrage, ob Extra versteckt ist
* @return: Status von covered. True, wenn versteckt; false, wenn sichtbar
*/
public boolean isCovered(){
return covered;
}
/*
* Variable fuer das jeweilige Extra; Aufruf einer getter
* Renderer.Tile_ .draw(x * 128 * 0.33f, y * 128 * 0.33f);
*/
}
| false | true |
public void draw(int x, int y){
if (covered==true){
Renderer.Tile_Break.draw(x*size, y*size);
Renderer.print(x*size, y*size, ""+art, 0.5f);
} else {
Renderer.Tile_Empty.draw(x*size, y*size);
switch(art)
{
case 1: Renderer.Tile_Health.draw(x*size, y*size); break; //Dieses Feld generiert ein zusaetzliches Leben, um einen Bombentreffer zu ueberleben}
case 2: Renderer.Tile_addbomb.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, um die Anzahl der Bomben, die man gleichzeitig legen kann, um 1 zu erhoehen
case 3: Renderer.Tile_kick.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, wodurch der Spieler dazu befaehigt wird, die Bomben linear zu treten
case 4: //Dieses Feld generiert ein Upgrade um (fuer die naechste Bombe) eine Super-Bombe anstatt einer normalen Bombe zu legen. Die Super-Bombe hat <spezifikation>
case 5: Renderer.Tile_confuse.draw(x*size, y*size); break;//Dieses Feld generiert eine temporaere Steuerungsbehinderung fuer alle feindlichen/anderen Spieler. Alle ausser der Spieler, der das Feld betritt, unterliegen einer umgekehrten Steuerung (Ausnahme: Bombe legen)
case 6: Renderer.Tile_teleport.draw(x*size, y*size); break;//Dieses Feld generiert ein Teleportationsfeld. Der Spieler der auf dieses Feld tritt wird mit sofortiger Wirkung zum entsprechenden Feld teleportiert
case 7: Renderer.Tile_speed.draw(x*size, y*size); break;//Dieses Feld generiert ein Upgrade, welches einen temporaeren Geschwindigkeitsbonus fuer den Spieler gibt, der es aufsammelt
case 8: Renderer.Tile_slow.draw(x*size, y*size); break;//Dieses Feld generiert ein temporaere Spielerbehinderung. Alle gegnerischen/anderen Spieler sind nur noch 50-75% so schnell
case 9: //Dieses Feld generiert bei Kontakt auf dem gesamten Spielfeld Bomben (5-10 Bomben? [Abhaengig davon, wie viele freie Felder es gibt]
case 10: //Dieses Feld generiert ein Loch. Der Spieler, der dieses Loch betritt faellt darin hinein und stirbt (egal wie viele Leben dieser noch hatte = Instant Death). Weitere Spieler koennen dieses Feld gefahrlos ueberqueren
case 11: //Dieses Feld generiert ein Uprade, welches temporaere Unverwundbarkeit verleiht. Dem Spieler wird kein Bombentreffer angerechnet. Fraglich: Wuerde er bei ART == 10 sterben?
case 12: //Dieses Feld generiert einen FROST-SCHOCK. Der Spieler der es aufsammelt, darf sich temporaer nicht bewegen. Wenn der Frost-Schock vorbei ist, erhaelt der Spieler seine komplette Bewegungsfreiheit.
case 13: //Dieses Feld generiert ein Upgrade zur Verbesserung der Bombenreichweite.
}
}
|
public void draw(int x, int y){
if (covered==true){
Renderer.Tile_Break.draw(x*size, y*size);
Renderer.print(x*size, y*size, ""+art, 0.5f);
} else {
Renderer.Tile_Empty.draw(x*size, y*size);
switch(art)
{
case 1: Renderer.Tile_Health.draw(x*size, y*size); break; //Dieses Feld generiert ein zusaetzliches Leben, um einen Bombentreffer zu ueberleben}
case 2: Renderer.Tile_addbomb.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, um die Anzahl der Bomben, die man gleichzeitig legen kann, um 1 zu erhoehen
case 3: Renderer.Tile_kick.draw(x*size, y*size); break; //Dieses Feld generiert ein Upgrade, wodurch der Spieler dazu befaehigt wird, die Bomben linear zu treten
case 4: break;//Dieses Feld generiert die einmalige Befähigung, sich für 3 Sekunden unsichtbar zu machen.
case 5: Renderer.Tile_slow.draw(x*size, y*size); break;//Dieses Feld generiert eine temporaere Steuerungsbehinderung fuer alle feindlichen/anderen Spieler. Alle ausser der Spieler, der das Feld betritt, unterliegen einer umgekehrten Steuerung (Ausnahme: Bombe legen)
case 6: Renderer.Tile_teleport.draw(x*size, y*size); break;//Dieses Feld generiert ein Teleportationsfeld. Der Spieler der auf dieses Feld tritt wird mit sofortiger Wirkung zum entsprechenden Feld teleportiert
case 7: Renderer.Tile_speed.draw(x*size, y*size); break;//Dieses Feld generiert ein Upgrade, welches einen temporaeren Geschwindigkeitsbonus fuer den Spieler gibt, der es aufsammelt
case 8: Renderer.Tile_confuse.draw(x*size, y*size); break;//Dieses Feld generiert eine temporäre Steuerungsbehinderung für alle feindlichen/anderen Spieler, in Form einer legbaren Falle.
case 9: //Dieses Feld generiert einen auslösbaren Schild.
case 10: //Dieses Feld generiert ein Upgrade zur Verbesserung der Bombenreichweite. case 12: //Dieses Feld generiert einen FROST-SCHOCK. Der Spieler der es aufsammelt, darf sich temporaer nicht bewegen. Wenn der Frost-Schock vorbei ist, erhaelt der Spieler seine komplette Bewegungsfreiheit.
}
}
|
diff --git a/src/ufly/frs/CustomerFlightbookings.java b/src/ufly/frs/CustomerFlightbookings.java
index 32aa88d..9f660a4 100644
--- a/src/ufly/frs/CustomerFlightbookings.java
+++ b/src/ufly/frs/CustomerFlightbookings.java
@@ -1,127 +1,130 @@
package ufly.frs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import ufly.entities.Customer;
import ufly.entities.FlightBooking;
import ufly.entities.Meal;
@SuppressWarnings("serial")
public class CustomerFlightbookings extends UflyServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
String pageToInclude= getServletConfig().getInitParameter("action");
String confirmationNumberStr = (String) req.getParameter("confirmationNumber");
- Long confirmNumber = Long.valueOf(confirmationNumberStr);
+ Long confirmNumber=null;
+ if(confirmationNumberStr!= null){
+ confirmNumber= Long.valueOf(confirmationNumberStr);
+ }
FlightBooking editFlightbooking=null;
if(confirmNumber != null){
editFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
}
if(pageToInclude.equals("index") )
{
Customer loggedInCustomer=null;
try {
loggedInCustomer = Customer.getCustomer(getLoggedInUser(req.getSession()).getEmailAddr());
} catch (UserInactivityTimeout e) {
resp.sendRedirect("/?errorMsg=Sorry, you have been logged out because you have been inactive too long");
}
Vector<Key> allFlightbookings = loggedInCustomer.getFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}else if (pageToInclude.equals("edit") )
{
if(editFlightbooking != null){
req.setAttribute("editFlightbooking", editFlightbooking.getHashMap());
req.setAttribute("meals", editFlightbooking.getBookedFlight().getAllowableMeals());
req.setAttribute("flight",editFlightbooking.getBookedFlight().getHashMap());
req.getRequestDispatcher("/customerFlightbookings_edit.jsp")
.forward(req,resp);
}
}else if (pageToInclude.equals("delete") )
{
if(confirmNumber != null){
FlightBooking deleteFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(deleteFlightbooking != null){
deleteFlightbooking.deleteFlightBooking();
req.getRequestDispatcher("/customerFlightbookings")
.forward(req,resp);
}
}
}
else if (pageToInclude.equals("show") )
{
if(confirmNumber != null){
FlightBooking showFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(showFlightbooking != null){
req.setAttribute("showFlightbooking", showFlightbooking);
req.getRequestDispatcher("/customerFlightbookings_show.jsp")
.forward(req,resp);
}
}
}
else{
List<FlightBooking> allFlightbookings = FlightBooking.getAllFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}
//}
//else{
// resp.sendRedirect("/");
//}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
resp.setContentType("text/plain");
String pageToInclude= getServletConfig().getInitParameter("action");
if (pageToInclude.equals("check-in") )
{
String confirmationNumber = (String) req.getParameter("confirmationNumber");
Long confirmNumber = Long.valueOf(confirmationNumber);
if(confirmNumber != null){
FlightBooking showFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(showFlightbooking != null){
showFlightbooking.checkIn();
req.setAttribute("showFlightbooking", showFlightbooking);
req.getRequestDispatcher("/customerFlightbookings_show.jsp")
.forward(req,resp);
}
}
}else if (pageToInclude.equals("edit") )
{
String confirmationNumber = (String) req.getParameter("confirmationNumber");
Long confirmNumber = Long.valueOf(confirmationNumber);
if(confirmNumber != null){
FlightBooking editFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(editFlightbooking != null){
Meal newMeal = Meal.valueOf(req.getParameter("meal"));
editFlightbooking.changeMealChoice(newMeal);
req.setAttribute("editFlightbooking", editFlightbooking);
req.getRequestDispatcher("/customerFlightbookings_edit.jsp")
.forward(req,resp);
}
}
}
}
}
| true | true |
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
String pageToInclude= getServletConfig().getInitParameter("action");
String confirmationNumberStr = (String) req.getParameter("confirmationNumber");
Long confirmNumber = Long.valueOf(confirmationNumberStr);
FlightBooking editFlightbooking=null;
if(confirmNumber != null){
editFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
}
if(pageToInclude.equals("index") )
{
Customer loggedInCustomer=null;
try {
loggedInCustomer = Customer.getCustomer(getLoggedInUser(req.getSession()).getEmailAddr());
} catch (UserInactivityTimeout e) {
resp.sendRedirect("/?errorMsg=Sorry, you have been logged out because you have been inactive too long");
}
Vector<Key> allFlightbookings = loggedInCustomer.getFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}else if (pageToInclude.equals("edit") )
{
if(editFlightbooking != null){
req.setAttribute("editFlightbooking", editFlightbooking.getHashMap());
req.setAttribute("meals", editFlightbooking.getBookedFlight().getAllowableMeals());
req.setAttribute("flight",editFlightbooking.getBookedFlight().getHashMap());
req.getRequestDispatcher("/customerFlightbookings_edit.jsp")
.forward(req,resp);
}
}else if (pageToInclude.equals("delete") )
{
if(confirmNumber != null){
FlightBooking deleteFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(deleteFlightbooking != null){
deleteFlightbooking.deleteFlightBooking();
req.getRequestDispatcher("/customerFlightbookings")
.forward(req,resp);
}
}
}
else if (pageToInclude.equals("show") )
{
if(confirmNumber != null){
FlightBooking showFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(showFlightbooking != null){
req.setAttribute("showFlightbooking", showFlightbooking);
req.getRequestDispatcher("/customerFlightbookings_show.jsp")
.forward(req,resp);
}
}
}
else{
List<FlightBooking> allFlightbookings = FlightBooking.getAllFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}
//}
//else{
// resp.sendRedirect("/");
//}
}
|
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException,ServletException
{
String pageToInclude= getServletConfig().getInitParameter("action");
String confirmationNumberStr = (String) req.getParameter("confirmationNumber");
Long confirmNumber=null;
if(confirmationNumberStr!= null){
confirmNumber= Long.valueOf(confirmationNumberStr);
}
FlightBooking editFlightbooking=null;
if(confirmNumber != null){
editFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
}
if(pageToInclude.equals("index") )
{
Customer loggedInCustomer=null;
try {
loggedInCustomer = Customer.getCustomer(getLoggedInUser(req.getSession()).getEmailAddr());
} catch (UserInactivityTimeout e) {
resp.sendRedirect("/?errorMsg=Sorry, you have been logged out because you have been inactive too long");
}
Vector<Key> allFlightbookings = loggedInCustomer.getFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}else if (pageToInclude.equals("edit") )
{
if(editFlightbooking != null){
req.setAttribute("editFlightbooking", editFlightbooking.getHashMap());
req.setAttribute("meals", editFlightbooking.getBookedFlight().getAllowableMeals());
req.setAttribute("flight",editFlightbooking.getBookedFlight().getHashMap());
req.getRequestDispatcher("/customerFlightbookings_edit.jsp")
.forward(req,resp);
}
}else if (pageToInclude.equals("delete") )
{
if(confirmNumber != null){
FlightBooking deleteFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(deleteFlightbooking != null){
deleteFlightbooking.deleteFlightBooking();
req.getRequestDispatcher("/customerFlightbookings")
.forward(req,resp);
}
}
}
else if (pageToInclude.equals("show") )
{
if(confirmNumber != null){
FlightBooking showFlightbooking = FlightBooking.getFlightBooking(confirmNumber);
if(showFlightbooking != null){
req.setAttribute("showFlightbooking", showFlightbooking);
req.getRequestDispatcher("/customerFlightbookings_show.jsp")
.forward(req,resp);
}
}
}
else{
List<FlightBooking> allFlightbookings = FlightBooking.getAllFlightBookings();
req.setAttribute("allFlightbookings", allFlightbookings);
req.getRequestDispatcher("/customerFlightbookings.jsp")
.forward(req,resp);
}
//}
//else{
// resp.sendRedirect("/");
//}
}
|
diff --git a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/wizards/HerokuAppCreate.java b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/wizards/HerokuAppCreate.java
index d4f9bef..8de0eb4 100644
--- a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/wizards/HerokuAppCreate.java
+++ b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/wizards/HerokuAppCreate.java
@@ -1,158 +1,158 @@
package com.heroku.eclipse.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import org.osgi.service.log.LogService;
import com.heroku.api.App;
import com.heroku.eclipse.core.services.HerokuProperties;
import com.heroku.eclipse.core.services.HerokuServices;
import com.heroku.eclipse.core.services.HerokuServices.IMPORT_TYPES;
import com.heroku.eclipse.core.services.exceptions.HerokuServiceException;
import com.heroku.eclipse.core.services.model.AppTemplate;
import com.heroku.eclipse.ui.Activator;
import com.heroku.eclipse.ui.git.HerokuCredentialsProvider;
import com.heroku.eclipse.ui.messages.Messages;
import com.heroku.eclipse.ui.utils.HerokuUtils;
/**
* Wizard allowing to create a new Heroku App
* @author [email protected]
*
*/
public class HerokuAppCreate extends Wizard implements IImportWizard {
private HerokuAppCreatePage createPage;
private HerokuServices service;
/**
*
*/
public HerokuAppCreate() {
service = Activator.getDefault().getService();
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
}
@Override
public void addPages() {
setNeedsProgressMonitor(true);
Shell shell = Display.getCurrent().getActiveShell();
if (HerokuUtils.verifyPreferences(new NullProgressMonitor(), service, shell)) {
try {
createPage = new HerokuAppCreatePage();
addPage(createPage);
}
catch (Exception e) {
HerokuUtils.internalError(Display.getCurrent().getActiveShell(), e);
}
}
else {
shell.close();
}
}
@Override
public boolean performFinish() {
final String appName = createPage.getAppName().toLowerCase();
try {
// ensure that the name is available
if (HerokuUtils.isNotEmpty(appName) && (!service.isAppNameBasicallyValid(appName) || service.appNameExists(new NullProgressMonitor(), appName))) {
createPage.displayInvalidNameWarning();
return false;
}
final AppTemplate template = createPage.getAppTemplate();
final String destinationDir = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getString(UIPreferences.DEFAULT_REPO_DIR)+
- System.getProperty("file.separator")+HerokuProperties.getString("defaultRepo"); //$NON-NLS-1$ //$NON-NLS-2$
+ System.getProperty("file.separator")+HerokuProperties.getString("heroku.eclipse.git.defaultRepo"); //$NON-NLS-1$ //$NON-NLS-2$
final int timeout = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
final HerokuCredentialsProvider cred = new HerokuCredentialsProvider(HerokuProperties.getString("heroku.eclipse.git.defaultUser"), ""); //$NON-NLS-1$ //$NON-NLS-2$
try {
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if ( HerokuUtils.isNotEmpty(appName)) {
monitor.beginTask(Messages.getFormattedString("HerokuAppCreate_CreatingApp", appName), 2); //$NON-NLS-1$
}
else {
monitor.beginTask(Messages.getString("HerokuAppCreate_CreatingArbitraryApp"), 2); //$NON-NLS-1$
}
monitor.subTask(Messages.getString("HerokuAppCreate_CloningTemplate")); //$NON-NLS-1$
monitor.worked(1);
// then materialize
try {
// first clone
App app = service.createAppFromTemplate(monitor, appName, template.getTemplateName());
if (app != null) {
String transportErrorMessage = Messages.getFormattedString("Heroku_Common_Error_JGitTransportException", app.getName()); //$NON-NLS-1$
monitor.subTask(Messages.getString("HerokuAppCreate_FetchingApp")); //$NON-NLS-1$
service.materializeGitApp(monitor, app, IMPORT_TYPES.AUTODETECT, null, destinationDir, timeout,
Messages.getFormattedString("HerokuAppCreate_CreatingApp", app.getName()), cred, transportErrorMessage); //$NON-NLS-1$
monitor.worked(1);
monitor.done();
}
}
catch (HerokuServiceException e) {
throw new InvocationTargetException(e);
}
}
});
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof HerokuServiceException) {
HerokuServiceException e1 = (HerokuServiceException) e.getCause();
if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) {
Activator.getDefault().getLogger().log(LogService.LOG_WARNING, "Application '" + appName + "' already exists, denying creation", e); //$NON-NLS-1$ //$NON-NLS-2$
createPage.displayInvalidNameWarning();
}
else if (e1.getErrorCode() == HerokuServiceException.INVALID_LOCAL_GIT_LOCATION) {
HerokuUtils
.userError(
getShell(),
Messages.getString("HerokuAppCreateNamePage_Error_GitLocationInvalid_Title"), Messages.getFormattedString("HerokuAppCreateNamePage_Error_GitLocationInvalid", destinationDir + System.getProperty("file.separator") + appName)); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
}
else if ( e1.getErrorCode() != HerokuServiceException.OPERATION_CANCELLED ) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e);
}
}
else {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
}
return false;
}
catch (InterruptedException e) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
return false;
}
}
catch (HerokuServiceException e1) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e1); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e1);
return false;
}
return true;
}
}
| true | true |
public boolean performFinish() {
final String appName = createPage.getAppName().toLowerCase();
try {
// ensure that the name is available
if (HerokuUtils.isNotEmpty(appName) && (!service.isAppNameBasicallyValid(appName) || service.appNameExists(new NullProgressMonitor(), appName))) {
createPage.displayInvalidNameWarning();
return false;
}
final AppTemplate template = createPage.getAppTemplate();
final String destinationDir = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getString(UIPreferences.DEFAULT_REPO_DIR)+
System.getProperty("file.separator")+HerokuProperties.getString("defaultRepo"); //$NON-NLS-1$ //$NON-NLS-2$
final int timeout = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
final HerokuCredentialsProvider cred = new HerokuCredentialsProvider(HerokuProperties.getString("heroku.eclipse.git.defaultUser"), ""); //$NON-NLS-1$ //$NON-NLS-2$
try {
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if ( HerokuUtils.isNotEmpty(appName)) {
monitor.beginTask(Messages.getFormattedString("HerokuAppCreate_CreatingApp", appName), 2); //$NON-NLS-1$
}
else {
monitor.beginTask(Messages.getString("HerokuAppCreate_CreatingArbitraryApp"), 2); //$NON-NLS-1$
}
monitor.subTask(Messages.getString("HerokuAppCreate_CloningTemplate")); //$NON-NLS-1$
monitor.worked(1);
// then materialize
try {
// first clone
App app = service.createAppFromTemplate(monitor, appName, template.getTemplateName());
if (app != null) {
String transportErrorMessage = Messages.getFormattedString("Heroku_Common_Error_JGitTransportException", app.getName()); //$NON-NLS-1$
monitor.subTask(Messages.getString("HerokuAppCreate_FetchingApp")); //$NON-NLS-1$
service.materializeGitApp(monitor, app, IMPORT_TYPES.AUTODETECT, null, destinationDir, timeout,
Messages.getFormattedString("HerokuAppCreate_CreatingApp", app.getName()), cred, transportErrorMessage); //$NON-NLS-1$
monitor.worked(1);
monitor.done();
}
}
catch (HerokuServiceException e) {
throw new InvocationTargetException(e);
}
}
});
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof HerokuServiceException) {
HerokuServiceException e1 = (HerokuServiceException) e.getCause();
if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) {
Activator.getDefault().getLogger().log(LogService.LOG_WARNING, "Application '" + appName + "' already exists, denying creation", e); //$NON-NLS-1$ //$NON-NLS-2$
createPage.displayInvalidNameWarning();
}
else if (e1.getErrorCode() == HerokuServiceException.INVALID_LOCAL_GIT_LOCATION) {
HerokuUtils
.userError(
getShell(),
Messages.getString("HerokuAppCreateNamePage_Error_GitLocationInvalid_Title"), Messages.getFormattedString("HerokuAppCreateNamePage_Error_GitLocationInvalid", destinationDir + System.getProperty("file.separator") + appName)); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
}
else if ( e1.getErrorCode() != HerokuServiceException.OPERATION_CANCELLED ) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e);
}
}
else {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
}
return false;
}
catch (InterruptedException e) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
return false;
}
}
catch (HerokuServiceException e1) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e1); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e1);
return false;
}
return true;
}
|
public boolean performFinish() {
final String appName = createPage.getAppName().toLowerCase();
try {
// ensure that the name is available
if (HerokuUtils.isNotEmpty(appName) && (!service.isAppNameBasicallyValid(appName) || service.appNameExists(new NullProgressMonitor(), appName))) {
createPage.displayInvalidNameWarning();
return false;
}
final AppTemplate template = createPage.getAppTemplate();
final String destinationDir = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getString(UIPreferences.DEFAULT_REPO_DIR)+
System.getProperty("file.separator")+HerokuProperties.getString("heroku.eclipse.git.defaultRepo"); //$NON-NLS-1$ //$NON-NLS-2$
final int timeout = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
final HerokuCredentialsProvider cred = new HerokuCredentialsProvider(HerokuProperties.getString("heroku.eclipse.git.defaultUser"), ""); //$NON-NLS-1$ //$NON-NLS-2$
try {
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if ( HerokuUtils.isNotEmpty(appName)) {
monitor.beginTask(Messages.getFormattedString("HerokuAppCreate_CreatingApp", appName), 2); //$NON-NLS-1$
}
else {
monitor.beginTask(Messages.getString("HerokuAppCreate_CreatingArbitraryApp"), 2); //$NON-NLS-1$
}
monitor.subTask(Messages.getString("HerokuAppCreate_CloningTemplate")); //$NON-NLS-1$
monitor.worked(1);
// then materialize
try {
// first clone
App app = service.createAppFromTemplate(monitor, appName, template.getTemplateName());
if (app != null) {
String transportErrorMessage = Messages.getFormattedString("Heroku_Common_Error_JGitTransportException", app.getName()); //$NON-NLS-1$
monitor.subTask(Messages.getString("HerokuAppCreate_FetchingApp")); //$NON-NLS-1$
service.materializeGitApp(monitor, app, IMPORT_TYPES.AUTODETECT, null, destinationDir, timeout,
Messages.getFormattedString("HerokuAppCreate_CreatingApp", app.getName()), cred, transportErrorMessage); //$NON-NLS-1$
monitor.worked(1);
monitor.done();
}
}
catch (HerokuServiceException e) {
throw new InvocationTargetException(e);
}
}
});
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof HerokuServiceException) {
HerokuServiceException e1 = (HerokuServiceException) e.getCause();
if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) {
Activator.getDefault().getLogger().log(LogService.LOG_WARNING, "Application '" + appName + "' already exists, denying creation", e); //$NON-NLS-1$ //$NON-NLS-2$
createPage.displayInvalidNameWarning();
}
else if (e1.getErrorCode() == HerokuServiceException.INVALID_LOCAL_GIT_LOCATION) {
HerokuUtils
.userError(
getShell(),
Messages.getString("HerokuAppCreateNamePage_Error_GitLocationInvalid_Title"), Messages.getFormattedString("HerokuAppCreateNamePage_Error_GitLocationInvalid", destinationDir + System.getProperty("file.separator") + appName)); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
}
else if ( e1.getErrorCode() != HerokuServiceException.OPERATION_CANCELLED ) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e);
}
}
else {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
}
return false;
}
catch (InterruptedException e) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e); //$NON-NLS-1$
HerokuUtils.internalError(getShell(), e);
return false;
}
}
catch (HerokuServiceException e1) {
Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error, aborting ...", e1); //$NON-NLS-1$
HerokuUtils.herokuError(getShell(), e1);
return false;
}
return true;
}
|
diff --git a/src/taberystwyth/allocation/Allocator.java b/src/taberystwyth/allocation/Allocator.java
index 6f07cf9..3efb78a 100644
--- a/src/taberystwyth/allocation/Allocator.java
+++ b/src/taberystwyth/allocation/Allocator.java
@@ -1,270 +1,271 @@
package taberystwyth.allocation;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.TreeMap;
import taberystwyth.allocation.options.JudgeAllocation;
import taberystwyth.allocation.options.LocationAllocation;
import taberystwyth.allocation.options.TeamAllocation;
import taberystwyth.allocation.exceptions.*;
import taberystwyth.db.SQLConnection;
public class Allocator {
Random randomGenerator = new Random(0L);
SQLConnection conn = SQLConnection.getInstance();
ResultSet rs;
String query;
private static Allocator instance = new Allocator();
public static Allocator getInstance() {
return instance;
}
private Allocator() {/* VOID */
};
/**
* Allocate the matches
*
* @param teamAlgo
* @param judgeAlgo
* @param locationAlgo
* @throws SQLException
* @throws SwingTeamsRequiredException
* @throws LocationsRequiredException
* @throws JudgesRequiredException
*/
public void allocate(TeamAllocation teamAlgo, JudgeAllocation judgeAlgo,
LocationAllocation locationAlgo) throws SQLException,
SwingTeamsRequiredException, LocationsRequiredException,
JudgesRequiredException {
/*
* Figure out the current round
*/
int round = 0; // FIXME
/*
* Generate matches
*/
query = "select count(*) / 4 from teams;";
rs = conn.executeQuery(query);
rs.next();
int nMatches = rs.getInt(1);
ArrayList<Match> matches = new ArrayList<Match>();
int rank = 0;
while (matches.size() > nMatches) {
matches.add(new Match(rank));
++rank;
}
rs.close();
/*
* Allocate teams
*/
if (teamAlgo == TeamAllocation.WUDC) {
TreeMap<Integer, ArrayList<String>> pools = getLeveledPools();
int highestTeamScore = pools.lastKey();
rank = 0;
+ // FIXME: What if highest team score is zero? (Initial round)
for (int treeIndex = highestTeamScore; treeIndex > 0; --treeIndex) {
if (pools.containsKey(treeIndex)) {
ArrayList<String> pool = pools.get(treeIndex);
for (int i = 0; i < (pools.get(i).size() / 4); ++i) {
Match match = matches.get(rank);
match.setFirstProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setFirstOp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondOp(pool.remove(randomGenerator
.nextInt(pool.size())));
rank++;
}
}
}
}
/*
* Allocate Judges
*/
if (judgeAlgo == JudgeAllocation.BALANCED) {
}
/*
* Allocate locations
*/
if (locationAlgo == LocationAllocation.RANDOM) {
} else if (locationAlgo == LocationAllocation.BEST_TO_BEST) {
}
for (Match m : matches) {
String insert = "insert into rooms first_prop, second_prop,"
+ "first_op, second_prop, location, round values("
+ m.getFirstProp() + ", " + m.getSecondProp() + ", "
+ m.getFirstOp() + ", " + m.getSecondOp() + ", "
+ m.getLocation() + ", " + round;
}
}
private TreeMap<Integer, ArrayList<String>> getLeveledPools()
throws SQLException {
TreeMap<Integer, ArrayList<String>> pools = getPools();
/*
* For each pool, starting at the top (highest ranked pool) and working
* down...
*/
for (int i = pools.lastKey(); i > 0; --i) {
/*
* if the pool exists...
*/
if (pools.containsKey(i)) {
/*
* and the pools size is not a multiple of 4...
*/
while (!((pools.get(i).size() % 4) == 0)) {
/*
* then pull up (randomly) a member from the pool directly
* below this one
*/
for (int j = (i - 1); j > 0; --j) {
if (pools.containsKey(j)) {
ArrayList<String> lowerPool = pools.get(j);
int randomElementIndex = randomGenerator
.nextInt(lowerPool.size());
pools.get(i).add(
pools.get(j).remove(randomElementIndex));
/*
* If the arraylist is empty then delete it
*/
if (lowerPool.size() == 0) {
pools.remove(j);
}
break;
}
}
}
}
}
return pools;
}
private TreeMap<Integer, ArrayList<String>> getPools() throws SQLException {
/*
* Construct the map of points to teams (pools)
*/
TreeMap<Integer, ArrayList<String>> pools = new TreeMap<Integer, ArrayList<String>>();
/*
* Get the map of team names to points
*/
HashMap<String, Integer> points = getTeamPoints();
/*
* For each team, add it to map of pools
*/
for (String team : points.keySet()) {
int innerPoints = points.get(team);
/*
* If the pool does not exist, create it
*/
if (!pools.containsKey(innerPoints)) {
pools.put(innerPoints, new ArrayList<String>());
}
pools.get(innerPoints).add(team);
}
return pools;
}
/**
* Get a list of teams mapped to team points
*
* @return A HashMap of Team names and Team points
* @throws SQLException
*/
protected HashMap<String, Integer> getTeamPoints() throws SQLException {
HashMap<String, Integer> teamScores = new HashMap<String, Integer>();
String query;
ResultSet rs;
/*
* Check if any rounds have happened yet, if not set all scores to 0
*/
query = "select count (*) from team_results;";
rs = SQLConnection.getInstance().executeQuery(query);
rs.next();
if (rs.getInt(1) == 0) {
for (String t : getTeamNames()) {
teamScores.put(t, 0);
}
return teamScores;
}
/*
* Otherwise, calculate the total team score for each team, and add the
* team to the map
*/
for (String name : getTeamNames()) {
int teamPoints = 0;
query = "select position from team_results where team = '" + name
+ "';";
rs = SQLConnection.getInstance().executeQuery(query);
/*
* Sum the team points according to positions taken in rounds
*/
boolean scoreCalculated = false;
while (rs.next()) {
int position = rs.getInt("position");
if (position == 1) {
teamPoints += 3;
} else if (position == 2) {
teamPoints += 2;
} else if (position == 3) {
teamPoints += 1;
} else {
// VOID
}
scoreCalculated = true;
}
}
return teamScores;
}
/**
* Gets an unordered list of team names
*
* @return List of teams
* @throws SQLException
*/
protected ArrayList<String> getTeamNames() throws SQLException {
ArrayList<String> teamNames = new ArrayList<String>();
String query = "select name from teams;";
ResultSet rs = SQLConnection.getInstance().executeQuery(query);
while (rs.next()) {
teamNames.add(rs.getString("name"));
}
return teamNames;
}
}
| true | true |
public void allocate(TeamAllocation teamAlgo, JudgeAllocation judgeAlgo,
LocationAllocation locationAlgo) throws SQLException,
SwingTeamsRequiredException, LocationsRequiredException,
JudgesRequiredException {
/*
* Figure out the current round
*/
int round = 0; // FIXME
/*
* Generate matches
*/
query = "select count(*) / 4 from teams;";
rs = conn.executeQuery(query);
rs.next();
int nMatches = rs.getInt(1);
ArrayList<Match> matches = new ArrayList<Match>();
int rank = 0;
while (matches.size() > nMatches) {
matches.add(new Match(rank));
++rank;
}
rs.close();
/*
* Allocate teams
*/
if (teamAlgo == TeamAllocation.WUDC) {
TreeMap<Integer, ArrayList<String>> pools = getLeveledPools();
int highestTeamScore = pools.lastKey();
rank = 0;
for (int treeIndex = highestTeamScore; treeIndex > 0; --treeIndex) {
if (pools.containsKey(treeIndex)) {
ArrayList<String> pool = pools.get(treeIndex);
for (int i = 0; i < (pools.get(i).size() / 4); ++i) {
Match match = matches.get(rank);
match.setFirstProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setFirstOp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondOp(pool.remove(randomGenerator
.nextInt(pool.size())));
rank++;
}
}
}
}
/*
* Allocate Judges
*/
if (judgeAlgo == JudgeAllocation.BALANCED) {
}
/*
* Allocate locations
*/
if (locationAlgo == LocationAllocation.RANDOM) {
} else if (locationAlgo == LocationAllocation.BEST_TO_BEST) {
}
for (Match m : matches) {
String insert = "insert into rooms first_prop, second_prop,"
+ "first_op, second_prop, location, round values("
+ m.getFirstProp() + ", " + m.getSecondProp() + ", "
+ m.getFirstOp() + ", " + m.getSecondOp() + ", "
+ m.getLocation() + ", " + round;
}
}
|
public void allocate(TeamAllocation teamAlgo, JudgeAllocation judgeAlgo,
LocationAllocation locationAlgo) throws SQLException,
SwingTeamsRequiredException, LocationsRequiredException,
JudgesRequiredException {
/*
* Figure out the current round
*/
int round = 0; // FIXME
/*
* Generate matches
*/
query = "select count(*) / 4 from teams;";
rs = conn.executeQuery(query);
rs.next();
int nMatches = rs.getInt(1);
ArrayList<Match> matches = new ArrayList<Match>();
int rank = 0;
while (matches.size() > nMatches) {
matches.add(new Match(rank));
++rank;
}
rs.close();
/*
* Allocate teams
*/
if (teamAlgo == TeamAllocation.WUDC) {
TreeMap<Integer, ArrayList<String>> pools = getLeveledPools();
int highestTeamScore = pools.lastKey();
rank = 0;
// FIXME: What if highest team score is zero? (Initial round)
for (int treeIndex = highestTeamScore; treeIndex > 0; --treeIndex) {
if (pools.containsKey(treeIndex)) {
ArrayList<String> pool = pools.get(treeIndex);
for (int i = 0; i < (pools.get(i).size() / 4); ++i) {
Match match = matches.get(rank);
match.setFirstProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setFirstOp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondProp(pool.remove(randomGenerator
.nextInt(pool.size())));
match.setSecondOp(pool.remove(randomGenerator
.nextInt(pool.size())));
rank++;
}
}
}
}
/*
* Allocate Judges
*/
if (judgeAlgo == JudgeAllocation.BALANCED) {
}
/*
* Allocate locations
*/
if (locationAlgo == LocationAllocation.RANDOM) {
} else if (locationAlgo == LocationAllocation.BEST_TO_BEST) {
}
for (Match m : matches) {
String insert = "insert into rooms first_prop, second_prop,"
+ "first_op, second_prop, location, round values("
+ m.getFirstProp() + ", " + m.getSecondProp() + ", "
+ m.getFirstOp() + ", " + m.getSecondOp() + ", "
+ m.getLocation() + ", " + round;
}
}
|
diff --git a/src/com/wolvencraft/prison/mines/events/ButtonPressListener.java b/src/com/wolvencraft/prison/mines/events/ButtonPressListener.java
index 5baa978..2405097 100644
--- a/src/com/wolvencraft/prison/mines/events/ButtonPressListener.java
+++ b/src/com/wolvencraft/prison/mines/events/ButtonPressListener.java
@@ -1,76 +1,76 @@
package com.wolvencraft.prison.mines.events;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import com.wolvencraft.prison.hooks.EconomyHook;
import com.wolvencraft.prison.mines.CommandHandler;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.DisplaySign;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
public class ButtonPressListener implements Listener {
public ButtonPressListener(PrisonMine plugin) {
Message.debug("Initiating ButtonPressListener");
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onButtonPress(PlayerInteractEvent event) {
if(event.isCancelled()) return;
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block block = event.getClickedBlock();
if(block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON) {
Message.debug("ButtonPressEvent passed");
Location locationAbove = block.getLocation();
locationAbove.setY(block.getLocation().getBlockY() + 1);
Block blockAbove = block.getWorld().getBlockAt(locationAbove);
if(blockAbove.getType() == Material.WALL_SIGN) {
DisplaySign sign = DisplaySign.get(locationAbove);
if(sign != null && sign.getReset()) {
Mine curMine = Mine.get(sign.getParent());
Player player = event.getPlayer();
if(!player.hasPermission("prison.mine.reset.sign." + curMine.getId()) && !player.hasPermission("prison.mine.reset.sign")) {
Message.sendError(player, PrisonMine.getLanguage().ERROR_ACCESS);
return;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !player.hasPermission("prison.mine.bypass.cooldown")) {
- Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
+ Message.sendError(player, Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
return;
}
if(EconomyHook.usingVault() && sign.getPaid() && sign.getPrice() != -1) {
Message.debug("Withdrawing " + sign.getPrice() + " from " + player.getName());
if(!EconomyHook.withdraw(player, sign.getPrice())) {
- Message.sendError(Util.parseColors(PrisonMine.getLanguage().SIGN_FUNDS.replaceAll("<PRICE>", sign.getPrice() + "")));
+ Message.sendError(player, Util.parseColors(PrisonMine.getLanguage().SIGN_FUNDS.replaceAll("<PRICE>", sign.getPrice() + "")));
return;
}
Message.debug("Successfully withdrawn the money. New balance: " + EconomyHook.getBalance(player));
Message.sendSuccess(player, Util.parseColors(PrisonMine.getLanguage().SIGN_WITHDRAW.replaceAll("<PRICE>", sign.getPrice() + "")));
} else Message.debug("Vault not found");
CommandHandler.RESET.run(curMine.getName());
}
}
}
}
return;
}
}
| false | true |
public void onButtonPress(PlayerInteractEvent event) {
if(event.isCancelled()) return;
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block block = event.getClickedBlock();
if(block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON) {
Message.debug("ButtonPressEvent passed");
Location locationAbove = block.getLocation();
locationAbove.setY(block.getLocation().getBlockY() + 1);
Block blockAbove = block.getWorld().getBlockAt(locationAbove);
if(blockAbove.getType() == Material.WALL_SIGN) {
DisplaySign sign = DisplaySign.get(locationAbove);
if(sign != null && sign.getReset()) {
Mine curMine = Mine.get(sign.getParent());
Player player = event.getPlayer();
if(!player.hasPermission("prison.mine.reset.sign." + curMine.getId()) && !player.hasPermission("prison.mine.reset.sign")) {
Message.sendError(player, PrisonMine.getLanguage().ERROR_ACCESS);
return;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !player.hasPermission("prison.mine.bypass.cooldown")) {
Message.sendError(Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
return;
}
if(EconomyHook.usingVault() && sign.getPaid() && sign.getPrice() != -1) {
Message.debug("Withdrawing " + sign.getPrice() + " from " + player.getName());
if(!EconomyHook.withdraw(player, sign.getPrice())) {
Message.sendError(Util.parseColors(PrisonMine.getLanguage().SIGN_FUNDS.replaceAll("<PRICE>", sign.getPrice() + "")));
return;
}
Message.debug("Successfully withdrawn the money. New balance: " + EconomyHook.getBalance(player));
Message.sendSuccess(player, Util.parseColors(PrisonMine.getLanguage().SIGN_WITHDRAW.replaceAll("<PRICE>", sign.getPrice() + "")));
} else Message.debug("Vault not found");
CommandHandler.RESET.run(curMine.getName());
}
}
}
}
return;
}
|
public void onButtonPress(PlayerInteractEvent event) {
if(event.isCancelled()) return;
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block block = event.getClickedBlock();
if(block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON) {
Message.debug("ButtonPressEvent passed");
Location locationAbove = block.getLocation();
locationAbove.setY(block.getLocation().getBlockY() + 1);
Block blockAbove = block.getWorld().getBlockAt(locationAbove);
if(blockAbove.getType() == Material.WALL_SIGN) {
DisplaySign sign = DisplaySign.get(locationAbove);
if(sign != null && sign.getReset()) {
Mine curMine = Mine.get(sign.getParent());
Player player = event.getPlayer();
if(!player.hasPermission("prison.mine.reset.sign." + curMine.getId()) && !player.hasPermission("prison.mine.reset.sign")) {
Message.sendError(player, PrisonMine.getLanguage().ERROR_ACCESS);
return;
}
if(curMine.getCooldown() && curMine.getCooldownEndsIn() > 0 && !player.hasPermission("prison.mine.bypass.cooldown")) {
Message.sendError(player, Util.parseVars(PrisonMine.getLanguage().RESET_COOLDOWN, curMine));
return;
}
if(EconomyHook.usingVault() && sign.getPaid() && sign.getPrice() != -1) {
Message.debug("Withdrawing " + sign.getPrice() + " from " + player.getName());
if(!EconomyHook.withdraw(player, sign.getPrice())) {
Message.sendError(player, Util.parseColors(PrisonMine.getLanguage().SIGN_FUNDS.replaceAll("<PRICE>", sign.getPrice() + "")));
return;
}
Message.debug("Successfully withdrawn the money. New balance: " + EconomyHook.getBalance(player));
Message.sendSuccess(player, Util.parseColors(PrisonMine.getLanguage().SIGN_WITHDRAW.replaceAll("<PRICE>", sign.getPrice() + "")));
} else Message.debug("Vault not found");
CommandHandler.RESET.run(curMine.getName());
}
}
}
}
return;
}
|
diff --git a/src/main/java/Command.java b/src/main/java/Command.java
index 3250151..0e071c1 100644
--- a/src/main/java/Command.java
+++ b/src/main/java/Command.java
@@ -1,68 +1,75 @@
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* User: Ivan Lyutov
* Date: 11/15/12
* Time: 3:06 PM
*/
public class Command implements Runnable {
private int id;
private String name;
public Status status;
public Command(int id, String name, Status status) {
this.id = id;
this.name = name;
this.status = status;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Status getStatus() {
return status;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setStatus(Status status) {
this.status = status;
}
public void run() {
ComboPooledDataSource dataSource = DataPool.getDataSource();
+ Connection connection = null;
try {
- System.out.println("executing " + name);
- Connection connection = dataSource.getConnection();
- Statement statement = connection.createStatement();
- statement.executeUpdate("update commands set status='" + Status.DONE + "' where id=" + id);
+ try{
+ System.out.println("executing " + name);
+ connection = dataSource.getConnection();
+ Statement statement = connection.createStatement();
+ statement.executeUpdate("update commands set status='" + Status.DONE + "' where id=" + id);
+ } finally {
+ if (connection != null) {
+ connection.close();
+ }
+ }
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static enum Status {
NEW("NEW"), IN_PROGRESS("IN_PROGRESS"), DONE("DONE");
private String value;
private Status(final String value) {
this.value = value;
}
}
}
| false | true |
public void run() {
ComboPooledDataSource dataSource = DataPool.getDataSource();
try {
System.out.println("executing " + name);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate("update commands set status='" + Status.DONE + "' where id=" + id);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
|
public void run() {
ComboPooledDataSource dataSource = DataPool.getDataSource();
Connection connection = null;
try {
try{
System.out.println("executing " + name);
connection = dataSource.getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate("update commands set status='" + Status.DONE + "' where id=" + id);
} finally {
if (connection != null) {
connection.close();
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
|
diff --git a/src/main/java/com/epimorphics/registry/core/Command.java b/src/main/java/com/epimorphics/registry/core/Command.java
index dbcce42..a467613 100644
--- a/src/main/java/com/epimorphics/registry/core/Command.java
+++ b/src/main/java/com/epimorphics/registry/core/Command.java
@@ -1,428 +1,428 @@
/******************************************************************
* File: Command.java
* Created by: Dave Reynolds
* Created on: 21 Jan 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
*****************************************************************/
package com.epimorphics.registry.core;
import static com.epimorphics.registry.webapi.Parameters.FIRST_PAGE;
import static com.epimorphics.registry.webapi.Parameters.PAGE_NUMBER;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.epimorphics.rdfutil.RDFUtil;
import com.epimorphics.registry.security.RegAction;
import com.epimorphics.registry.security.RegPermission;
import com.epimorphics.registry.store.StoreAPI;
import com.epimorphics.registry.util.Prefixes;
import com.epimorphics.registry.vocab.Ldbp;
import com.epimorphics.registry.vocab.RegistryVocab;
import com.epimorphics.server.webapi.WebApiException;
import com.epimorphics.util.EpiException;
import com.epimorphics.util.NameUtils;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
/**
* Wraps up a registry request as a command object to modularize
* processing such as authorization and audit trails.
*
* @author <a href="mailto:[email protected]">Dave Reynolds</a>
*/
public abstract class Command {
static final Logger log = LoggerFactory.getLogger( Command.class );
public enum Operation {
Read,
Register(RegAction.Register),
Delete(RegAction.StatusUpdate),
Update(RegAction.Update),
StatusUpdate(RegAction.StatusUpdate),
Validate,
Search;
protected RegAction action;
private Operation(RegAction action) {
this.action = action;
}
private Operation() {
this.action = null;
}
public RegAction getAuthorizationAction() {
return action;
}
};
protected Operation operation;
protected String target;
protected String path;
protected MultivaluedMap<String, String> parameters;
protected Model payload;
protected String requestor;
protected String parent;
protected String lastSegment;
protected boolean paged;
protected int length = -1;
protected int pagenum = 0;
protected Registry registry;
protected StoreAPI store;
protected ForwardingRecord delegation;
/**
* Constructor
* @param operation operation request, as determined by HTTP verb
* @param targetType type of thing to act on, may be amended or set later after more analysis
* @param target the URI to which the operation was targeted, omits the assumed base URI
* @param parameters the query parameters
*/
public Command(Operation operation, String target, MultivaluedMap<String, String> parameters, Registry registry) {
this.operation = operation;
this.target = registry.getBaseURI() + (target.isEmpty() ? "/" : "/" + target);
this.path = target;
this.parameters = parameters;
this.registry = registry;
this.store = registry.getStore();
Matcher segmatch = LAST_SEGMENT.matcher(this.target);
if (segmatch.matches()) {
this.lastSegment = segmatch.group(2);
this.parent = segmatch.group(1);
} else {
// Root register
this.lastSegment = "";
this.parent = registry.getBaseURI();
}
// Extract paging parameters, if any
if (parameters.containsKey(FIRST_PAGE)) {
paged = true;
length = registry.getPageSize();
} else if (parameters.containsKey(PAGE_NUMBER)) {
paged = true;
length = registry.getPageSize();
try {
pagenum = Integer.parseInt( parameters.getFirst(PAGE_NUMBER) );
} catch (NumberFormatException e) {
throw new WebApiException(javax.ws.rs.core.Response.Status.BAD_REQUEST, "Illegal page number");
}
}
}
static final Pattern LAST_SEGMENT = Pattern.compile("(^.*)/([^/]+)$");
public Model getPayload() {
return payload;
}
public void setPayload(Model payload) {
this.payload = payload;
}
public Operation getOperation() {
return operation;
}
public String getTarget() {
return target;
}
public MultivaluedMap<String, String> getParameters() {
return parameters;
}
public String getRequestor() {
return requestor;
}
public void setRequestor(String requestor) {
this.requestor = requestor;
}
public ForwardingRecord getDelegation() {
return delegation;
}
public void setDelegation(ForwardingRecord delegation) {
this.delegation = delegation;
}
@Override
public String toString() {
return String.format("Command: %s on %s", operation, target);
}
public abstract Response doExecute() ;
/**
* Test that the request is legal. Subclasses should provide
* an appropriate implementation.
*/
public ValidationResponse validate() {
return ValidationResponse.OK;
}
public Response authorizedExecute() {
performValidate();
return performExecute();
}
public Response execute() {
performValidate();
if (!isAuthorized()) {
throw new WebApiException(Response.Status.UNAUTHORIZED, "Either not logged in or not authorized for this action");
}
return authorizedExecute();
}
protected void performValidate() {
ValidationResponse validity = validate();
if (!validity.isOk()) {
throw new WebApiException(validity.getStatus(), validity.getMessage());
}
}
// Called after validation and authorization
protected Response performExecute() {
Response response = null;
try {
response = doExecute();
} catch (WebApplicationException wae) {
response = wae.getResponse();
} catch (Exception e) {
log.error("Internal error", e);
response = Response.serverError().entity(e.getMessage()).build();
}
// TODO - logging notification
Date now = new Date(System.currentTimeMillis());
log.info(String.format("%s [%s] %s \"%s?%s\"%s %d",
- NameUtils.decodeSafeName(requestor),
+ requestor == null ? null : NameUtils.decodeSafeName(requestor),
new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").format(now),
operation.toString(),
target,
makeParamString(parameters),
(response.getStatus() == 201) ? " -> " + response.getMetadata().get("Location") : "",
response.getStatus()));
if (payload != null && registry.getLogDir() != null) {
String logfile = registry.getLogDir() + File.separator + String.format("on-%s-%s-%s.ttl",
new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(now),
operation.toString(),
NameUtils.encodeSafeName( target + "?" + makeParamString(parameters))
);
try {
FileOutputStream out = new FileOutputStream(logfile);
payload.write(out, "Turtle");
out.close();
} catch (IOException e) {
log.error("Failed to write log of payload", e);
}
}
return response;
}
/**
* Returns the permissions that will be required to authorize this
* operation or null if no permissions are needed.
*/
public RegPermission permissionRequried() {
RegAction action = operation.getAuthorizationAction();
if (action == null) {
return null;
} else {
return new RegPermission(action, "/" + path);
}
}
/**
* Test if the user of authorized to execute this command
*/
public boolean isAuthorized() {
RegPermission required = permissionRequried();
if (required != null) {
try {
Subject subject = SecurityUtils.getSubject();
if (subject.isPermitted(required)) {
return true;
} else {
log.warn("Authorization failure for " + subject.getPrincipal() + ", requested permission " + required);
return false;
}
} catch (UnavailableSecurityManagerException e) {
log.warn("Security is not configured, assuming test mode");
return true;
}
} else {
return true;
}
}
protected boolean hasParamValue(String param, String value) {
List<String> values = parameters.get(param);
if (values != null) {
return values.contains(value);
}
return false;
}
protected String notation() {
if (lastSegment.startsWith("_")) {
return lastSegment.substring(0, lastSegment.length() - 1);
} else {
return lastSegment;
}
}
protected String entityURI() {
if (lastSegment.startsWith("_")) {
return parent + "/" + notation();
} else {
return target;
}
}
protected String itemURI() {
if (lastSegment.startsWith("_")) {
return target;
} else {
return parent + "/_" + lastSegment;
}
}
protected Resource findSingletonRoot() {
List<Resource> roots = RDFUtil.findRoots(payload);
if (roots.size() == 1) {
// Single tree root, use that
return roots.get(0);
}
if (roots.size() == 0) {
// Might be a a circular graph, so check for single non-anony typed resource
roots = payload.listSubjectsWithProperty(RDF.type).toList();
for (Iterator<Resource> i = roots.iterator(); i.hasNext();) {
Resource root = i.next();
if (root.isAnon()) {
i.remove();
}
}
if (roots.size() == 1) {
return roots.get(0);
}
}
throw new WebApiException(Response.Status.BAD_REQUEST, "Could not find unique entity root to register");
}
protected String makeParamString(MultivaluedMap<String, String> parameters, String...omit) {
StringBuffer params = new StringBuffer();
boolean startedParams = false;
for (String p : parameters.keySet()) {
boolean skip = false;
for (String o : omit) {
if (p.equals(o)) {
skip = true;
break;
}
}
if (skip) continue;
if (startedParams) {
params.append("&");
} else {
startedParams = true;
}
List<String> values = parameters.get(p);
params.append(p);
if (values == null || values.isEmpty()) continue;
if (values.size() == 1 && values.get(0) == null) continue;
params.append("=");
boolean started = false;
for (String value: values) {
if (started) {
params.append(",");
} else {
started = true;
}
// params.append( value );
try {
params.append( URLEncoder.encode(value, "UTF-8") );
} catch (UnsupportedEncodingException e) {
throw new EpiException(e); // Can't happen :)
}
}
}
return params.toString();
}
protected Response returnModel(Model m, String location) {
m.setNsPrefixes(Prefixes.get());
URI uri;
try {
uri = new URI( location );
} catch (URISyntaxException e) {
throw new WebApplicationException(e);
}
return Response.ok().location(uri).entity( m ).build();
}
protected Resource injectPagingInformation(Model m, Resource root, boolean more) {
String url = target + "?" + makeParamString(parameters);
Resource page = m.createResource(url)
.addProperty(RDF.type, Ldbp.Page)
.addProperty(Ldbp.pageOf, root);
if (more) {
String pageParams = "?" + PAGE_NUMBER + "=" + (pagenum+1);
String otherParams = makeParamString(parameters, FIRST_PAGE, PAGE_NUMBER);
if (!otherParams.isEmpty()) {
pageParams += "&" + otherParams;
}
page.addProperty(Ldbp.nextPage, m.createResource( target + pageParams ));
}
return page;
}
protected void checkDelegation(RegisterItem item) {
if (item.getRoot().hasProperty(RegistryVocab.itemClass, RegistryVocab.Delegated)) {
if (item.getEntity() == null) {
store.getEntity(item);
}
ForwardingService fs = Registry.get().getForwarder();
if (fs != null) {
fs.update(item);
} else {
log.error("No forwarder configured, delegation request for " + item.getRoot() + " can't be honoured");
}
}
}
}
| true | true |
protected Response performExecute() {
Response response = null;
try {
response = doExecute();
} catch (WebApplicationException wae) {
response = wae.getResponse();
} catch (Exception e) {
log.error("Internal error", e);
response = Response.serverError().entity(e.getMessage()).build();
}
// TODO - logging notification
Date now = new Date(System.currentTimeMillis());
log.info(String.format("%s [%s] %s \"%s?%s\"%s %d",
NameUtils.decodeSafeName(requestor),
new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").format(now),
operation.toString(),
target,
makeParamString(parameters),
(response.getStatus() == 201) ? " -> " + response.getMetadata().get("Location") : "",
response.getStatus()));
if (payload != null && registry.getLogDir() != null) {
String logfile = registry.getLogDir() + File.separator + String.format("on-%s-%s-%s.ttl",
new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(now),
operation.toString(),
NameUtils.encodeSafeName( target + "?" + makeParamString(parameters))
);
try {
FileOutputStream out = new FileOutputStream(logfile);
payload.write(out, "Turtle");
out.close();
} catch (IOException e) {
log.error("Failed to write log of payload", e);
}
}
return response;
}
|
protected Response performExecute() {
Response response = null;
try {
response = doExecute();
} catch (WebApplicationException wae) {
response = wae.getResponse();
} catch (Exception e) {
log.error("Internal error", e);
response = Response.serverError().entity(e.getMessage()).build();
}
// TODO - logging notification
Date now = new Date(System.currentTimeMillis());
log.info(String.format("%s [%s] %s \"%s?%s\"%s %d",
requestor == null ? null : NameUtils.decodeSafeName(requestor),
new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").format(now),
operation.toString(),
target,
makeParamString(parameters),
(response.getStatus() == 201) ? " -> " + response.getMetadata().get("Location") : "",
response.getStatus()));
if (payload != null && registry.getLogDir() != null) {
String logfile = registry.getLogDir() + File.separator + String.format("on-%s-%s-%s.ttl",
new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss").format(now),
operation.toString(),
NameUtils.encodeSafeName( target + "?" + makeParamString(parameters))
);
try {
FileOutputStream out = new FileOutputStream(logfile);
payload.write(out, "Turtle");
out.close();
} catch (IOException e) {
log.error("Failed to write log of payload", e);
}
}
return response;
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/handler/ConnectableToolbarCommandHandler.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/handler/ConnectableToolbarCommandHandler.java
index 68239a278..ce82dfe25 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/handler/ConnectableToolbarCommandHandler.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.ui/src/org/eclipse/tcf/te/tcf/ui/handler/ConnectableToolbarCommandHandler.java
@@ -1,66 +1,64 @@
/*******************************************************************************
* Copyright (c) 2014 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.ui.handler;
import java.util.Map;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.tcf.te.core.interfaces.IConnectable;
import org.eclipse.tcf.te.runtime.services.ServiceManager;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerNode;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.IDefaultContextService;
import org.eclipse.tcf.te.tcf.ui.nls.Messages;
import org.eclipse.tcf.te.ui.handler.ConnectableCommandHandler;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.menus.UIElement;
/**
* ConnectableToolbarCommandHandler
*/
public class ConnectableToolbarCommandHandler extends ConnectableCommandHandler implements IElementUpdater {
/* (non-Javadoc)
* @see org.eclipse.tcf.te.ui.handler.AbstractCommandHandler#getSelection(org.eclipse.core.commands.ExecutionEvent)
*/
@Override
protected IStructuredSelection getSelection(ExecutionEvent event) {
IPeerNode defaultContext = ServiceManager.getInstance().getService(IDefaultContextService.class).getDefaultContext(null);
return defaultContext != null ? new StructuredSelection(defaultContext) : new StructuredSelection();
}
/* (non-Javadoc)
* @see org.eclipse.ui.commands.IElementUpdater#updateElement(org.eclipse.ui.menus.UIElement, java.util.Map)
*/
@Override
public void updateElement(final UIElement element, Map parameters) {
final IPeerNode defaultContext = ServiceManager.getInstance().getService(IDefaultContextService.class).getDefaultContext(null);
- if (defaultContext != null) {
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (getAction() == IConnectable.ACTION_CONNECT) {
- element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_connect, defaultContext.getName()));
- }
- else if (getAction() == IConnectable.ACTION_DISCONNECT) {
- element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_disconnect, defaultContext.getName()));
- }
- else {
- element.setTooltip(null);
- }
- }
- });
- }
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (defaultContext != null && getAction() == IConnectable.ACTION_CONNECT) {
+ element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_connect, defaultContext.getName()));
+ }
+ else if (defaultContext != null && getAction() == IConnectable.ACTION_DISCONNECT) {
+ element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_disconnect, defaultContext.getName()));
+ }
+ else {
+ element.setTooltip(null);
+ }
+ }
+ });
}
}
| true | true |
public void updateElement(final UIElement element, Map parameters) {
final IPeerNode defaultContext = ServiceManager.getInstance().getService(IDefaultContextService.class).getDefaultContext(null);
if (defaultContext != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (getAction() == IConnectable.ACTION_CONNECT) {
element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_connect, defaultContext.getName()));
}
else if (getAction() == IConnectable.ACTION_DISCONNECT) {
element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_disconnect, defaultContext.getName()));
}
else {
element.setTooltip(null);
}
}
});
}
}
|
public void updateElement(final UIElement element, Map parameters) {
final IPeerNode defaultContext = ServiceManager.getInstance().getService(IDefaultContextService.class).getDefaultContext(null);
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (defaultContext != null && getAction() == IConnectable.ACTION_CONNECT) {
element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_connect, defaultContext.getName()));
}
else if (defaultContext != null && getAction() == IConnectable.ACTION_DISCONNECT) {
element.setTooltip(NLS.bind(Messages.ConnectableToolbarCommandHandler_tooltip_disconnect, defaultContext.getName()));
}
else {
element.setTooltip(null);
}
}
});
}
|
diff --git a/src/com/google/javascript/jscomp/ant/CompileTask.java b/src/com/google/javascript/jscomp/ant/CompileTask.java
index 4e636a39b..38741720a 100644
--- a/src/com/google/javascript/jscomp/ant/CompileTask.java
+++ b/src/com/google/javascript/jscomp/ant/CompileTask.java
@@ -1,279 +1,281 @@
/*
* 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.javascript.jscomp.ant;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.CommandLineRunner;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.MessageFormatter;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.WarningLevel;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileList;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Level;
/**
* This class implements a simple Ant task to do almost the same as
* CommandLineRunner.
*
* Most of the public methods of this class are entry points for the
* Ant code to hook into.
*
*
*/
public final class CompileTask
extends Task {
private WarningLevel warningLevel;
private boolean debugOptions;
private String encoding = "UTF-8";
private String outputEncoding = "UTF-8";
private CompilationLevel compilationLevel;
private boolean customExternsOnly;
private boolean manageDependencies;
private File outputFile;
private final List<FileList> externFileLists;
private final List<FileList> sourceFileLists;
public CompileTask() {
this.warningLevel = WarningLevel.DEFAULT;
this.debugOptions = false;
this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
this.customExternsOnly = false;
this.manageDependencies = false;
this.externFileLists = Lists.newLinkedList();
this.sourceFileLists = Lists.newLinkedList();
}
/**
* Set the warning level.
* @param value The warning level by string name. (default, quiet, verbose).
*/
public void setWarning(String value) {
if ("default".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.DEFAULT;
} else if ("quiet".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.QUIET;
} else if ("verbose".equalsIgnoreCase(value)) {
this.warningLevel = WarningLevel.VERBOSE;
} else {
throw new BuildException(
"Unrecognized 'warning' option value (" + value + ")");
}
}
/**
* Enable debugging options.
* @param value True if debug mode is enabled.
*/
public void setDebug(boolean value) {
this.debugOptions = value;
}
/**
* Set the compilation level.
* @param value The optimization level by string name.
* (whitespace, simple, advanced).
*/
public void setCompilationLevel(String value) {
if ("simple".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
} else if ("advanced".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS;
} else if ("whitespace".equalsIgnoreCase(value)) {
this.compilationLevel = CompilationLevel.WHITESPACE_ONLY;
} else {
throw new BuildException(
"Unrecognized 'compilation' option value (" + value + ")");
}
}
public void setManageDependencies(boolean value) {
this.manageDependencies = value;
}
/**
* Use only custom externs.
*/
public void setCustomExternsOnly(boolean value) {
this.customExternsOnly = value;
}
/**
* Set output file.
*/
public void setOutput(File value) {
this.outputFile = value;
}
/**
* Set input file encoding
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Set output file encoding
*/
public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}
/**
* Sets the externs file.
*/
public void addExterns(FileList list) {
this.externFileLists.add(list);
}
/**
* Sets the source files.
*/
public void addSources(FileList list) {
this.sourceFileLists.add(list);
}
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
+ } else {
+ throw new BuildException("Compilation failed.");
}
}
private CompilerOptions createCompilerOptions() {
CompilerOptions options = new CompilerOptions();
if (this.debugOptions) {
this.compilationLevel.setDebugOptionsForCompilationLevel(options);
} else {
this.compilationLevel.setOptionsForCompilationLevel(options);
}
this.warningLevel.setOptionsForWarningLevel(options);
options.setManageClosureDependencies(manageDependencies);
return options;
}
private Compiler createCompiler(CompilerOptions options) {
Compiler compiler = new Compiler();
MessageFormatter formatter =
options.errorFormat.toFormatter(compiler, false);
AntErrorManager errorManager = new AntErrorManager(formatter, this);
compiler.setErrorManager(errorManager);
return compiler;
}
private JSSourceFile[] findExternFiles() {
List<JSSourceFile> files = Lists.newLinkedList();
if (!this.customExternsOnly) {
files.addAll(getDefaultExterns());
}
for (FileList list : this.externFileLists) {
files.addAll(findJavaScriptFiles(list));
}
return files.toArray(new JSSourceFile[files.size()]);
}
private JSSourceFile[] findSourceFiles() {
List<JSSourceFile> files = Lists.newLinkedList();
for (FileList list : this.sourceFileLists) {
files.addAll(findJavaScriptFiles(list));
}
return files.toArray(new JSSourceFile[files.size()]);
}
/**
* Translates an Ant file list into the file format that the compiler
* expects.
*/
private List<JSSourceFile> findJavaScriptFiles(FileList fileList) {
List<JSSourceFile> files = Lists.newLinkedList();
File baseDir = fileList.getDir(getProject());
for (String included : fileList.getFiles(getProject())) {
files.add(JSSourceFile.fromFile(new File(baseDir, included),
Charset.forName(encoding)));
}
return files;
}
/**
* Gets the default externs set.
*
* Adapted from {@link CommandLineRunner}.
*/
private List<JSSourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
private void writeResult(String source) {
if (this.outputFile.getParentFile().mkdirs()) {
log("Created missing parent directory " +
this.outputFile.getParentFile(), Project.MSG_DEBUG);
}
try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(this.outputFile), outputEncoding);
out.append(source);
out.flush();
out.close();
} catch (IOException e) {
throw new BuildException(e);
}
log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
Project.MSG_DEBUG);
}
}
| true | true |
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
}
}
|
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
JSSourceFile[] externs = findExternFiles();
JSSourceFile[] sources = findSourceFiles();
log("Compiling " + sources.length + " file(s) with " +
externs.length + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
writeResult(compiler.toSource());
} else {
throw new BuildException("Compilation failed.");
}
}
|
diff --git a/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/CodeCompletionHelperGenerator.java b/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/CodeCompletionHelperGenerator.java
index c193cea82..b3bc396fe 100644
--- a/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/CodeCompletionHelperGenerator.java
+++ b/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/CodeCompletionHelperGenerator.java
@@ -1,515 +1,517 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.resource.ui.generators.ui;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ARRAYS;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ARRAY_LIST;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.BYTE_ARRAY_INPUT_STREAM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.COLLECTION;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.COLLECTIONS;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ATTRIBUTE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_CLASS;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_CLASSIFIER;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ENUM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_ENUM_LITERAL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_REFERENCE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_STRUCTURAL_FEATURE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ITERATOR;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LINKED_HASH_SET;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LIST;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.PLATFORM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET_IMPL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.STRING;
import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.ADAPTER_FACTORY_LABEL_PROVIDER;
import static org.emftext.sdk.codegen.resource.ui.IUIClassNameConstants.IMAGE;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.codegen.parameters.ArtifactParameter;
import org.emftext.sdk.codegen.resource.GenerationContext;
import org.emftext.sdk.codegen.resource.ui.UIGeneratorUtil;
import org.emftext.sdk.codegen.resource.ui.generators.UIJavaBaseGenerator;
public class CodeCompletionHelperGenerator extends UIJavaBaseGenerator<ArtifactParameter<GenerationContext>> {
/**
* This is a temporary flag which can be used to enable the
* generation of debug output. This flag must be removed once
* all code completion issues have been resolved.
*/
public static final boolean INSERT_DEBUG_OUTPUT_CODE = false;
private final UIGeneratorUtil generatorUtil = new UIGeneratorUtil();
@Override
public void generateJavaContents(JavaComposite sc) {
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.addJavadoc(
"A CodeCompletionHelper can be used to derive completion proposals for partial " +
"documents. It runs the parser generated by EMFText in a special mode (i.e., the " +
"rememberExpectedElements mode). Based on the elements that are expected by the " +
"parser for different regions in the document, valid proposals are computed.");
sc.add("public class " + getResourceClassName() + " {");
sc.addLineBreak();
addFields(sc);
addMethods(sc);
sc.add("}");
}
private void addFields(StringComposite sc) {
sc.add("private " + attributeValueProviderClassName + " attributeValueProvider = new " + attributeValueProviderClassName + "();");
sc.addLineBreak();
}
private void addMethods(JavaComposite sc) {
addComputeCompletionProposalsMethod(sc);
addParseToExpectedElementsMethod(sc);
addRemoveDuplicateEntriesMethod(sc);
addRemoveInvalidEntriesAtEndMethod(sc);
addShouldRemoveMethod(sc);
addFindPrefixMethod(sc);
addDeriveProposalsMethod1(sc);
addDeriveProposalsMethod2(sc);
addHandleEnumAttributeMethod(sc);
addHandleNCReferenceMethod(sc);
addHandleAttributeMethod(sc);
addDeriveProposalMethod1(sc);
addSetPrefixesMethod(sc);
addGetExpectedElementsAtMethod(sc);
addGetEndMethod(sc);
addMatchesMethod(sc);
addGetImageMethod(sc);
}
private void addGetImageMethod(StringComposite sc) {
sc.add("public " + IMAGE + " getImage(" + E_OBJECT + " element) {");
sc.add("if (!" + PLATFORM + ".isRunning()) {");
sc.add("return null;");
sc.add("}");
generatorUtil.addCreateAdapterFactoryCode(sc);
sc.add(ADAPTER_FACTORY_LABEL_PROVIDER + " labelProvider = new " + ADAPTER_FACTORY_LABEL_PROVIDER + "(adapterFactory);");
sc.add("return labelProvider.getImage(element);");
sc.add("}");
}
private void addGetEndMethod(StringComposite sc) {
sc.add("private int getEnd(" + expectedTerminalClassName + "[] allExpectedElements, int indexInList) {");
sc.add(expectedTerminalClassName + " elementAtIndex = allExpectedElements[indexInList];");
sc.add("int startIncludingHidden = elementAtIndex.getStartIncludingHiddenTokens();");
sc.add("int startExcludingHidden = elementAtIndex.getStartExcludingHiddenTokens();");
sc.add("for (int i = indexInList + 1; i < allExpectedElements.length; i++) {");
sc.add(expectedTerminalClassName + " elementAtI = allExpectedElements[i];");
sc.add("int startIncludingHiddenForI = elementAtI.getStartIncludingHiddenTokens();");
sc.add("int startExcludingHiddenForI = elementAtI.getStartExcludingHiddenTokens();");
sc.add("if (startIncludingHidden != startIncludingHiddenForI || startExcludingHidden != startExcludingHiddenForI) {");
sc.add("return startIncludingHiddenForI - 1;");
sc.add("}");
sc.add("}");
sc.add("return Integer.MAX_VALUE;");
sc.add("}");
sc.addLineBreak();
}
private void addSetPrefixesMethod(JavaComposite sc) {
sc.addJavadoc(
"Calculates the prefix for each given expected element. " +
"The prefix depends on the current document content, the cursor position, and " +
"the position where the element is expected."
);
sc.add("private void setPrefixes(" + LIST + "<" + expectedTerminalClassName + "> expectedElements, String content, int cursorOffset) {");
sc.add("if (cursorOffset < 0) {");
sc.add("return;");
sc.add("}");
sc.add("for (" + expectedTerminalClassName + " expectedElement : expectedElements) {");
sc.add(STRING + " prefix = findPrefix(expectedElements, expectedElement, content, cursorOffset);");
sc.add("expectedElement.setPrefix(prefix);");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
private void addDeriveProposalMethod1(StringComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> deriveProposal(" + expectedCsStringClassName + " csString, String content, String prefix, int cursorOffset) {");
sc.add("String proposal = csString.getValue();");
sc.add(COLLECTION + "<" + completionProposalClassName + "> result = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add("if (matches(proposal, prefix)) {");
sc.add("result.add(new " + completionProposalClassName + "(proposal, prefix, !\"\".equals(prefix), false));");
sc.add("}");
sc.add("return result;");
sc.add("}");
sc.addLineBreak();
}
private void addMatchesMethod(StringComposite sc) {
sc.add("private boolean matches(" + STRING + " proposal, " + STRING + " prefix) {");
sc.add("return (proposal.toLowerCase().startsWith(prefix.toLowerCase()) || " + stringUtilClassName + ".matchCamelCase(prefix, proposal) != null) && !proposal.equals(prefix);");
sc.add("}");
sc.addLineBreak();
}
private void addHandleEnumAttributeMethod(JavaComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> handleEnumAttribute(" + iMetaInformationClassName + " metaInformation, " + expectedStructuralFeatureClassName + " expectedFeature, " + E_ENUM + " enumType, String prefix, " + E_OBJECT + " container) {");
sc.add(COLLECTION + "<" + E_ENUM_LITERAL + "> enumLiterals = enumType.getELiterals();");
sc.add(COLLECTION + "<" + completionProposalClassName + "> result = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add("for (" + E_ENUM_LITERAL + " literal : enumLiterals) {");
sc.add("String unResolvedLiteral = literal.getLiteral();");
sc.addComment("use token resolver to get de-resolved value of the literal");
sc.add(iTokenResolverFactoryClassName + " tokenResolverFactory = metaInformation.getTokenResolverFactory();");
sc.add(iTokenResolverClassName + " tokenResolver = tokenResolverFactory.createTokenResolver(expectedFeature.getTokenName());");
sc.add("String resolvedLiteral = tokenResolver.deResolve(unResolvedLiteral, expectedFeature.getFeature(), container);");
sc.add("if (matches(resolvedLiteral, prefix)) {");
sc.add("result.add(new " + completionProposalClassName + "(resolvedLiteral, prefix, !\"\".equals(prefix), true));");
sc.add("}");
sc.add("}");
sc.add("return result;");
sc.add("}");
sc.addLineBreak();
}
private void addHandleAttributeMethod(StringComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> handleAttribute(" + iMetaInformationClassName + " metaInformation, " + expectedStructuralFeatureClassName + " expectedFeature, " + E_OBJECT + " container, " + E_ATTRIBUTE + " attribute, " + STRING + " prefix) {");
sc.add(COLLECTION + "<" + completionProposalClassName + "> resultSet = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add(OBJECT + "[] defaultValues = attributeValueProvider.getDefaultValues(attribute);");
sc.add("if (defaultValues != null) {");
sc.add("for (Object defaultValue : defaultValues) {");
sc.add("if (defaultValue != null) {");
sc.add(iTokenResolverFactoryClassName + " tokenResolverFactory = metaInformation.getTokenResolverFactory();");
sc.add("String tokenName = expectedFeature.getTokenName();");
sc.add("if (tokenName != null) {");
sc.add(iTokenResolverClassName + " tokenResolver = tokenResolverFactory.createTokenResolver(tokenName);");
sc.add("if (tokenResolver != null) {");
sc.add("String defaultValueAsString = tokenResolver.deResolve(defaultValue, attribute, container);");
sc.add("if (matches(defaultValueAsString, prefix)) {");
sc.add("resultSet.add(new " + completionProposalClassName + "(defaultValueAsString, prefix, !\"\".equals(prefix), true));");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("return resultSet;");
sc.add("}");
sc.addLineBreak();
}
private void addHandleNCReferenceMethod(JavaComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> handleNCReference(" + iMetaInformationClassName + " metaInformation, " + E_OBJECT + " container, " + E_REFERENCE + " reference, " + STRING + " prefix, " + STRING + " tokenName) {");
sc.addComment(
"proposals for non-containment references are derived by calling the " +
"reference resolver switch in fuzzy mode."
);
sc.add(iReferenceResolverSwitchClassName + " resolverSwitch = metaInformation.getReferenceResolverSwitch();");
sc.add(iTokenResolverFactoryClassName + " tokenResolverFactory = metaInformation.getTokenResolverFactory();");
sc.add(iReferenceResolveResultClassName + "<" + E_OBJECT + "> result = new " + referenceResolveResultClassName + "<" + E_OBJECT + ">(true);");
sc.add("resolverSwitch.resolveFuzzy(prefix, container, reference, 0, result);");
sc.add(COLLECTION + "<" + iReferenceMappingClassName + "<" + E_OBJECT + ">> mappings = result.getMappings();");
sc.add("if (mappings != null) {");
sc.add(COLLECTION + "<" + completionProposalClassName + "> resultSet = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add("for (" + iReferenceMappingClassName + "<" + E_OBJECT + "> mapping : mappings) {");
sc.add(IMAGE + " image = null;");
sc.add("if (mapping instanceof " + elementMappingClassName + "<?>) {");
sc.add(elementMappingClassName + "<?> elementMapping = (" + elementMappingClassName + "<?>) mapping;");
sc.add(OBJECT + " target = elementMapping.getTargetElement();");
sc.addComment("de-resolve reference to obtain correct identifier");
sc.add(iTokenResolverClassName + " tokenResolver = tokenResolverFactory.createTokenResolver(tokenName);");
sc.add("final String identifier = tokenResolver.deResolve(elementMapping.getIdentifier(), reference, container);");
sc.add("if (target instanceof " + E_OBJECT + ") {");
sc.add("image = getImage((" + E_OBJECT + ") target);");
sc.add("}");
sc.addComment("check the prefix. return only matching references");
sc.add("if (matches(identifier, prefix)) {");
sc.add("resultSet.add(new " + completionProposalClassName + "(identifier, prefix, true, true, image));");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("return resultSet;");
sc.add("}");
sc.add("return " + COLLECTIONS + ".emptyList();");
sc.add("}");
sc.addLineBreak();
}
private void addDeriveProposalsMethod2(JavaComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> deriveProposals(" + expectedTerminalClassName + " expectedTerminal, String content, " + iTextResourceClassName + " resource, int cursorOffset) {");
sc.add(iMetaInformationClassName + " metaInformation = resource.getMetaInformation();");
sc.add(iLocationMapClassName + " locationMap = resource.getLocationMap();");
sc.add(iExpectedElementClassName + " expectedElement = (" + iExpectedElementClassName + ") expectedTerminal.getTerminal();");
sc.add("if (expectedElement instanceof " + expectedCsStringClassName + ") {");
sc.add(expectedCsStringClassName + " csString = (" + expectedCsStringClassName + ") expectedElement;");
sc.add("return deriveProposal(csString, content, expectedTerminal.getPrefix(), cursorOffset);");
sc.add("} else if (expectedElement instanceof " + expectedStructuralFeatureClassName + ") {");
sc.add(expectedStructuralFeatureClassName + " expectedFeature = (" + expectedStructuralFeatureClassName + ") expectedElement;");
sc.add(E_STRUCTURAL_FEATURE + " feature = expectedFeature.getFeature();");
sc.add(E_CLASSIFIER + " featureType = feature.getEType();");
sc.add(LIST + "<" + E_OBJECT + "> elementsAtCursor = locationMap.getElementsAt(cursorOffset);");
sc.add(E_OBJECT + " container = null;");
sc.addComment("we need to skip the proxy elements at the cursor, because they are not the container for the reference we try to complete");
sc.add("for (int i = 0; i < elementsAtCursor.size(); i++) {");
sc.add("container = elementsAtCursor.get(i);");
sc.add("if (!container.eIsProxy()) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.addComment(
"if no container can be found, the cursor is probably at the " +
"end of the document. we need to create artificial containers."
);
sc.add("if (container == null) {");
sc.add("boolean attachedArtificialContainer = false;");
sc.add(E_CLASS + " containerClass = expectedTerminal.getTerminal().getRuleMetaclass();");
sc.add(E_STRUCTURAL_FEATURE + "[] containmentTrace = expectedTerminal.getContainmentTrace();");
sc.add(LIST + "<" + E_OBJECT + "> contentList = null;");
sc.add("for (" + E_STRUCTURAL_FEATURE + " eStructuralFeature : containmentTrace) {");
sc.add("if (attachedArtificialContainer) {");
sc.add("break;");
sc.add("}");
sc.add(E_CLASS + " neededClass = eStructuralFeature.getEContainingClass();");
sc.addComment("fill the content list during the first iteration of the loop");
sc.add("if (contentList == null) {");
sc.add("contentList = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.add(ITERATOR + "<" + E_OBJECT + "> allContents = resource.getAllContents();");
sc.add("while (allContents.hasNext()) {");
sc.add(E_OBJECT + " next = allContents.next();");
sc.add("contentList.add(next);");
sc.add("}");
sc.add("}");
sc.addComment("find object to attach artificial container to");
sc.add("for (int i = contentList.size() - 1; i >= 0; i--) {");
sc.add(E_OBJECT + " object = contentList.get(i);");
sc.add("if (neededClass.isInstance(object)) {");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Found \" + object);");
}
sc.add(E_OBJECT + " newContainer = containerClass.getEPackage().getEFactoryInstance().create(containerClass);");
+ sc.add("if (eStructuralFeature.getEType().isInstance(newContainer)) {");
sc.add(eObjectUtilClassName + ".setFeature(object, eStructuralFeature, newContainer, false);");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Attached \" + newContainer);");
}
sc.add("container = newContainer;");
sc.add("attachedArtificialContainer = true;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
+ sc.add("}");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_REFERENCE + ") {");
sc.add(E_REFERENCE + " reference = (" + E_REFERENCE + ") feature;");
sc.add("if (featureType instanceof " + E_CLASS + ") {");
sc.add("if (reference.isContainment()) {");
sc.addComment("the FOLLOW set should contain only non-containment references");
sc.add("assert false;");
sc.add("} else {");
sc.add("return handleNCReference(metaInformation, container, reference, expectedTerminal.getPrefix(), expectedFeature.getTokenName());");
sc.add("}");
sc.add("}");
sc.add("} else if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add(E_ATTRIBUTE + " attribute = (" + E_ATTRIBUTE + ") feature;");
sc.add("if (featureType instanceof " + E_ENUM + ") {");
sc.add(E_ENUM + " enumType = (" + E_ENUM + ") featureType;");
sc.add("return handleEnumAttribute(metaInformation, expectedFeature, enumType, expectedTerminal.getPrefix(), container);");
sc.add("} else {");
sc.addComment(
"handle EAttributes (derive default value depending on " +
"the type of the attribute, figure out token resolver, and " +
"call deResolve())"
);
sc.add("return handleAttribute(metaInformation, expectedFeature, container, attribute, expectedTerminal.getPrefix());");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other subclass of EStructuralFeature");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other class implementing IExpectedElement");
sc.add("assert false;");
sc.add("}");
sc.add("return " + COLLECTIONS + ".emptyList();");
sc.add("}");
sc.addLineBreak();
}
private void addDeriveProposalsMethod1(StringComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> deriveProposals(" + LIST + "<" + expectedTerminalClassName + "> expectedElements, String content, " + iTextResourceClassName + " resource, int cursorOffset) {");
sc.add(COLLECTION + "<" + completionProposalClassName + "> resultSet = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add("for (" + expectedTerminalClassName + " expectedElement : expectedElements) {");
sc.add("resultSet.addAll(deriveProposals(expectedElement, content, resource, cursorOffset));");
sc.add("}");
sc.add("return resultSet;");
sc.add("}");
sc.addLineBreak();
}
private void addFindPrefixMethod(StringComposite sc) {
sc.add("private String findPrefix(" + LIST + "<" + expectedTerminalClassName + "> expectedElements, " + expectedTerminalClassName + " expectedAtCursor, String content, int cursorOffset) {");
sc.add("if (cursorOffset < 0) {");
sc.add("return \"\";");
sc.add("}");
sc.add("int end = 0;");
sc.add("for (" + expectedTerminalClassName + " expectedElement : expectedElements) {");
sc.add("if (expectedElement == expectedAtCursor) {");
sc.add("final int start = expectedElement.getStartExcludingHiddenTokens();");
sc.add("if (start >= 0 && start < Integer.MAX_VALUE) {");
sc.add("end = start;");
sc.add("}");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.add("end = Math.min(end, cursorOffset);");
sc.add("final String prefix = content.substring(end, Math.min(content.length(), cursorOffset));");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Found prefix '\" + prefix + \"'\");");
}
sc.add("return prefix;");
sc.add("}");
sc.addLineBreak();
}
private void addRemoveInvalidEntriesAtEndMethod(StringComposite sc) {
sc.add("private void removeInvalidEntriesAtEnd(" + LIST + "<" + expectedTerminalClassName + "> expectedElements) {");
sc.add("for (int i = 0; i < expectedElements.size() - 1;) {");
sc.add(expectedTerminalClassName + " elementAtIndex = expectedElements.get(i);");
sc.add(expectedTerminalClassName + " elementAtNext = expectedElements.get(i + 1);");
sc.add("if (elementAtIndex.getStartExcludingHiddenTokens() == elementAtNext.getStartExcludingHiddenTokens() && shouldRemove(elementAtIndex.getFollowSetID(), elementAtNext.getFollowSetID())) {");
sc.add("expectedElements.remove(i + 1);");
sc.add("} else {");
sc.add("i++;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
private void addRemoveDuplicateEntriesMethod(StringComposite sc) {
sc.add("private void removeDuplicateEntries(" + LIST + "<" + expectedTerminalClassName + "> expectedElements) {");
sc.add("for (int i = 0; i < expectedElements.size() - 1; i++) {");
sc.add(expectedTerminalClassName + " elementAtIndex = expectedElements.get(i);");
sc.add("for (int j = i + 1; j < expectedElements.size();) {");
sc.add(expectedTerminalClassName + " elementAtNext = expectedElements.get(j);");
sc.add("if (elementAtIndex.equals(elementAtNext) && elementAtIndex.getStartExcludingHiddenTokens() == elementAtNext.getStartExcludingHiddenTokens()) {");
sc.add("expectedElements.remove(j);");
sc.add("} else {");
sc.add("j++;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.addLineBreak();
}
private void addShouldRemoveMethod(StringComposite sc) {
sc.add("public boolean shouldRemove(int followSetID1, int followSetID2) {");
sc.add("return followSetID1 != followSetID2;");
sc.add("}");
sc.addLineBreak();
}
private void addComputeCompletionProposalsMethod(JavaComposite sc) {
sc.addJavadoc(
"Computes a set of proposals for the given document assuming the cursor is " +
"at 'cursorOffset'. The proposals are derived using the meta information, i.e., " +
"the generated language plug-in.",
"@param originalResource",
"@param content the documents content",
"@param cursorOffset",
"@return"
);
sc.add("public " + completionProposalClassName + "[] computeCompletionProposals(" + iTextResourceClassName + " originalResource, String content, int cursorOffset) {");
sc.add(RESOURCE_SET + " resourceSet = new " + RESOURCE_SET_IMPL + "();");
sc.addComment("the shadow resource needs the same URI because reference resolvers may use the URI to resolve external references");
sc.add(iTextResourceClassName + " resource = (" + iTextResourceClassName + ") resourceSet.createResource(originalResource.getURI());");
sc.add(BYTE_ARRAY_INPUT_STREAM + " inputStream = new " + BYTE_ARRAY_INPUT_STREAM + "(content.getBytes());");
sc.add(iMetaInformationClassName + " metaInformation = resource.getMetaInformation();");
sc.add(iTextParserClassName + " parser = metaInformation.createParser(inputStream, null);");
sc.add(expectedTerminalClassName + "[] expectedElements = parseToExpectedElements(parser, resource);");
sc.add("if (expectedElements == null) {");
sc.add("return new " + completionProposalClassName + "[0];");
sc.add("}");
sc.add("if (expectedElements.length == 0) {");
sc.add("return new " + completionProposalClassName + "[0];");
sc.add("}");
sc.add(LIST + "<" + expectedTerminalClassName + "> expectedAfterCursor = " + ARRAYS + ".asList(getElementsExpectedAt(expectedElements, cursorOffset));");
sc.add(LIST + "<" + expectedTerminalClassName + "> expectedBeforeCursor = " + ARRAYS + ".asList(getElementsExpectedAt(expectedElements, cursorOffset - 1));");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"parseToCursor(\" + cursorOffset + \") BEFORE CURSOR \" + expectedBeforeCursor);");
sc.add("System.out.println(\"parseToCursor(\" + cursorOffset + \") AFTER CURSOR \" + expectedAfterCursor);");
}
sc.add("setPrefixes(expectedAfterCursor, content, cursorOffset);");
sc.add("setPrefixes(expectedBeforeCursor, content, cursorOffset);");
sc.addComment("first we derive all possible proposals from the set of elements that are expected at the cursor position");
sc.add(COLLECTION + "<" + completionProposalClassName + "> allProposals = new " + LINKED_HASH_SET + "<" + completionProposalClassName + ">();");
sc.add(COLLECTION + "<" + completionProposalClassName + "> rightProposals = deriveProposals(expectedAfterCursor, content, resource, cursorOffset);");
sc.add(COLLECTION + "<" + completionProposalClassName + "> leftProposals = deriveProposals(expectedBeforeCursor, content, resource, cursorOffset - 1);");
sc.addComment(
"second, the set of left proposals (i.e., the ones before the cursor) is " +
"checked for emptiness. if the set is empty, the right proposals (i.e., " +
"the ones after the cursor are removed, because it does not make sense to " +
"propose them until the element before the cursor was completed"
);
sc.add("allProposals.addAll(leftProposals);");
sc.add("if (leftProposals.isEmpty()) {");
sc.add("allProposals.addAll(rightProposals);");
sc.add("}");
sc.addComment(
"third, the proposals are sorted according to their relevance " +
"proposals that matched the prefix are preferred over ones that did not " +
"afterward proposals are sorted alphabetically"
);
sc.add("final " + LIST + "<" + completionProposalClassName + "> sortedProposals = new " + ARRAY_LIST + "<" + completionProposalClassName + ">(allProposals);");
sc.add(COLLECTIONS + ".sort(sortedProposals);");
sc.add("return sortedProposals.toArray(new " + completionProposalClassName + "[sortedProposals.size()]);");
sc.add("}");
sc.addLineBreak();
}
private void addParseToExpectedElementsMethod(StringComposite sc) {
sc.add("public " + expectedTerminalClassName + "[] parseToExpectedElements(" + iTextParserClassName + " parser, " + iTextResourceClassName + " resource) {");
sc.add("final " + LIST + "<" + expectedTerminalClassName + "> expectedElements = parser.parseToExpectedElements(null, resource);");
sc.add("if (expectedElements == null) {");
sc.add("return new " + expectedTerminalClassName + "[0];");
sc.add("}");
sc.add("removeDuplicateEntries(expectedElements);");
sc.add("removeInvalidEntriesAtEnd(expectedElements);");
sc.add("return expectedElements.toArray(new " + expectedTerminalClassName + "[expectedElements.size()]);");
sc.add("}");
sc.addLineBreak();
}
private void addGetExpectedElementsAtMethod(StringComposite sc) {
sc.add("public " + expectedTerminalClassName + "[] getElementsExpectedAt(" + expectedTerminalClassName + "[] allExpectedElements, int cursorOffset) {");
sc.add(LIST + "<" + expectedTerminalClassName + "> expectedAtCursor = new " + ARRAY_LIST + "<" + expectedTerminalClassName + ">();");
sc.add("for (int i = 0; i < allExpectedElements.length; i++) {");
sc.add(expectedTerminalClassName + " expectedElement = allExpectedElements[i];");
sc.add("int startIncludingHidden = expectedElement.getStartIncludingHiddenTokens();");
sc.add("int end = getEnd(allExpectedElements, i);");
sc.add("if (cursorOffset >= startIncludingHidden && cursorOffset <= end) {");
sc.add("expectedAtCursor.add(expectedElement);");
sc.add("}");
sc.add("}");
sc.add("return expectedAtCursor.toArray(new " + expectedTerminalClassName + "[expectedAtCursor.size()]);");
sc.add("}");
sc.addLineBreak();
}
}
| false | true |
private void addDeriveProposalsMethod2(JavaComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> deriveProposals(" + expectedTerminalClassName + " expectedTerminal, String content, " + iTextResourceClassName + " resource, int cursorOffset) {");
sc.add(iMetaInformationClassName + " metaInformation = resource.getMetaInformation();");
sc.add(iLocationMapClassName + " locationMap = resource.getLocationMap();");
sc.add(iExpectedElementClassName + " expectedElement = (" + iExpectedElementClassName + ") expectedTerminal.getTerminal();");
sc.add("if (expectedElement instanceof " + expectedCsStringClassName + ") {");
sc.add(expectedCsStringClassName + " csString = (" + expectedCsStringClassName + ") expectedElement;");
sc.add("return deriveProposal(csString, content, expectedTerminal.getPrefix(), cursorOffset);");
sc.add("} else if (expectedElement instanceof " + expectedStructuralFeatureClassName + ") {");
sc.add(expectedStructuralFeatureClassName + " expectedFeature = (" + expectedStructuralFeatureClassName + ") expectedElement;");
sc.add(E_STRUCTURAL_FEATURE + " feature = expectedFeature.getFeature();");
sc.add(E_CLASSIFIER + " featureType = feature.getEType();");
sc.add(LIST + "<" + E_OBJECT + "> elementsAtCursor = locationMap.getElementsAt(cursorOffset);");
sc.add(E_OBJECT + " container = null;");
sc.addComment("we need to skip the proxy elements at the cursor, because they are not the container for the reference we try to complete");
sc.add("for (int i = 0; i < elementsAtCursor.size(); i++) {");
sc.add("container = elementsAtCursor.get(i);");
sc.add("if (!container.eIsProxy()) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.addComment(
"if no container can be found, the cursor is probably at the " +
"end of the document. we need to create artificial containers."
);
sc.add("if (container == null) {");
sc.add("boolean attachedArtificialContainer = false;");
sc.add(E_CLASS + " containerClass = expectedTerminal.getTerminal().getRuleMetaclass();");
sc.add(E_STRUCTURAL_FEATURE + "[] containmentTrace = expectedTerminal.getContainmentTrace();");
sc.add(LIST + "<" + E_OBJECT + "> contentList = null;");
sc.add("for (" + E_STRUCTURAL_FEATURE + " eStructuralFeature : containmentTrace) {");
sc.add("if (attachedArtificialContainer) {");
sc.add("break;");
sc.add("}");
sc.add(E_CLASS + " neededClass = eStructuralFeature.getEContainingClass();");
sc.addComment("fill the content list during the first iteration of the loop");
sc.add("if (contentList == null) {");
sc.add("contentList = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.add(ITERATOR + "<" + E_OBJECT + "> allContents = resource.getAllContents();");
sc.add("while (allContents.hasNext()) {");
sc.add(E_OBJECT + " next = allContents.next();");
sc.add("contentList.add(next);");
sc.add("}");
sc.add("}");
sc.addComment("find object to attach artificial container to");
sc.add("for (int i = contentList.size() - 1; i >= 0; i--) {");
sc.add(E_OBJECT + " object = contentList.get(i);");
sc.add("if (neededClass.isInstance(object)) {");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Found \" + object);");
}
sc.add(E_OBJECT + " newContainer = containerClass.getEPackage().getEFactoryInstance().create(containerClass);");
sc.add(eObjectUtilClassName + ".setFeature(object, eStructuralFeature, newContainer, false);");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Attached \" + newContainer);");
}
sc.add("container = newContainer;");
sc.add("attachedArtificialContainer = true;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_REFERENCE + ") {");
sc.add(E_REFERENCE + " reference = (" + E_REFERENCE + ") feature;");
sc.add("if (featureType instanceof " + E_CLASS + ") {");
sc.add("if (reference.isContainment()) {");
sc.addComment("the FOLLOW set should contain only non-containment references");
sc.add("assert false;");
sc.add("} else {");
sc.add("return handleNCReference(metaInformation, container, reference, expectedTerminal.getPrefix(), expectedFeature.getTokenName());");
sc.add("}");
sc.add("}");
sc.add("} else if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add(E_ATTRIBUTE + " attribute = (" + E_ATTRIBUTE + ") feature;");
sc.add("if (featureType instanceof " + E_ENUM + ") {");
sc.add(E_ENUM + " enumType = (" + E_ENUM + ") featureType;");
sc.add("return handleEnumAttribute(metaInformation, expectedFeature, enumType, expectedTerminal.getPrefix(), container);");
sc.add("} else {");
sc.addComment(
"handle EAttributes (derive default value depending on " +
"the type of the attribute, figure out token resolver, and " +
"call deResolve())"
);
sc.add("return handleAttribute(metaInformation, expectedFeature, container, attribute, expectedTerminal.getPrefix());");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other subclass of EStructuralFeature");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other class implementing IExpectedElement");
sc.add("assert false;");
sc.add("}");
sc.add("return " + COLLECTIONS + ".emptyList();");
sc.add("}");
sc.addLineBreak();
}
|
private void addDeriveProposalsMethod2(JavaComposite sc) {
sc.add("private " + COLLECTION + "<" + completionProposalClassName + "> deriveProposals(" + expectedTerminalClassName + " expectedTerminal, String content, " + iTextResourceClassName + " resource, int cursorOffset) {");
sc.add(iMetaInformationClassName + " metaInformation = resource.getMetaInformation();");
sc.add(iLocationMapClassName + " locationMap = resource.getLocationMap();");
sc.add(iExpectedElementClassName + " expectedElement = (" + iExpectedElementClassName + ") expectedTerminal.getTerminal();");
sc.add("if (expectedElement instanceof " + expectedCsStringClassName + ") {");
sc.add(expectedCsStringClassName + " csString = (" + expectedCsStringClassName + ") expectedElement;");
sc.add("return deriveProposal(csString, content, expectedTerminal.getPrefix(), cursorOffset);");
sc.add("} else if (expectedElement instanceof " + expectedStructuralFeatureClassName + ") {");
sc.add(expectedStructuralFeatureClassName + " expectedFeature = (" + expectedStructuralFeatureClassName + ") expectedElement;");
sc.add(E_STRUCTURAL_FEATURE + " feature = expectedFeature.getFeature();");
sc.add(E_CLASSIFIER + " featureType = feature.getEType();");
sc.add(LIST + "<" + E_OBJECT + "> elementsAtCursor = locationMap.getElementsAt(cursorOffset);");
sc.add(E_OBJECT + " container = null;");
sc.addComment("we need to skip the proxy elements at the cursor, because they are not the container for the reference we try to complete");
sc.add("for (int i = 0; i < elementsAtCursor.size(); i++) {");
sc.add("container = elementsAtCursor.get(i);");
sc.add("if (!container.eIsProxy()) {");
sc.add("break;");
sc.add("}");
sc.add("}");
sc.addComment(
"if no container can be found, the cursor is probably at the " +
"end of the document. we need to create artificial containers."
);
sc.add("if (container == null) {");
sc.add("boolean attachedArtificialContainer = false;");
sc.add(E_CLASS + " containerClass = expectedTerminal.getTerminal().getRuleMetaclass();");
sc.add(E_STRUCTURAL_FEATURE + "[] containmentTrace = expectedTerminal.getContainmentTrace();");
sc.add(LIST + "<" + E_OBJECT + "> contentList = null;");
sc.add("for (" + E_STRUCTURAL_FEATURE + " eStructuralFeature : containmentTrace) {");
sc.add("if (attachedArtificialContainer) {");
sc.add("break;");
sc.add("}");
sc.add(E_CLASS + " neededClass = eStructuralFeature.getEContainingClass();");
sc.addComment("fill the content list during the first iteration of the loop");
sc.add("if (contentList == null) {");
sc.add("contentList = new " + ARRAY_LIST + "<" + E_OBJECT + ">();");
sc.add(ITERATOR + "<" + E_OBJECT + "> allContents = resource.getAllContents();");
sc.add("while (allContents.hasNext()) {");
sc.add(E_OBJECT + " next = allContents.next();");
sc.add("contentList.add(next);");
sc.add("}");
sc.add("}");
sc.addComment("find object to attach artificial container to");
sc.add("for (int i = contentList.size() - 1; i >= 0; i--) {");
sc.add(E_OBJECT + " object = contentList.get(i);");
sc.add("if (neededClass.isInstance(object)) {");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Found \" + object);");
}
sc.add(E_OBJECT + " newContainer = containerClass.getEPackage().getEFactoryInstance().create(containerClass);");
sc.add("if (eStructuralFeature.getEType().isInstance(newContainer)) {");
sc.add(eObjectUtilClassName + ".setFeature(object, eStructuralFeature, newContainer, false);");
if (INSERT_DEBUG_OUTPUT_CODE) {
sc.add("System.out.println(\"Attached \" + newContainer);");
}
sc.add("container = newContainer;");
sc.add("attachedArtificialContainer = true;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("}");
sc.addLineBreak();
sc.add("if (feature instanceof " + E_REFERENCE + ") {");
sc.add(E_REFERENCE + " reference = (" + E_REFERENCE + ") feature;");
sc.add("if (featureType instanceof " + E_CLASS + ") {");
sc.add("if (reference.isContainment()) {");
sc.addComment("the FOLLOW set should contain only non-containment references");
sc.add("assert false;");
sc.add("} else {");
sc.add("return handleNCReference(metaInformation, container, reference, expectedTerminal.getPrefix(), expectedFeature.getTokenName());");
sc.add("}");
sc.add("}");
sc.add("} else if (feature instanceof " + E_ATTRIBUTE + ") {");
sc.add(E_ATTRIBUTE + " attribute = (" + E_ATTRIBUTE + ") feature;");
sc.add("if (featureType instanceof " + E_ENUM + ") {");
sc.add(E_ENUM + " enumType = (" + E_ENUM + ") featureType;");
sc.add("return handleEnumAttribute(metaInformation, expectedFeature, enumType, expectedTerminal.getPrefix(), container);");
sc.add("} else {");
sc.addComment(
"handle EAttributes (derive default value depending on " +
"the type of the attribute, figure out token resolver, and " +
"call deResolve())"
);
sc.add("return handleAttribute(metaInformation, expectedFeature, container, attribute, expectedTerminal.getPrefix());");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other subclass of EStructuralFeature");
sc.add("assert false;");
sc.add("}");
sc.add("} else {");
sc.addComment("there should be no other class implementing IExpectedElement");
sc.add("assert false;");
sc.add("}");
sc.add("return " + COLLECTIONS + ".emptyList();");
sc.add("}");
sc.addLineBreak();
}
|
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/util/indexing/AbstractUpdateCheckerJob.java b/contentconnector-core/src/main/java/com/gentics/cr/util/indexing/AbstractUpdateCheckerJob.java
index f0671309..740847a3 100644
--- a/contentconnector-core/src/main/java/com/gentics/cr/util/indexing/AbstractUpdateCheckerJob.java
+++ b/contentconnector-core/src/main/java/com/gentics/cr/util/indexing/AbstractUpdateCheckerJob.java
@@ -1,361 +1,367 @@
package com.gentics.cr.util.indexing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.gentics.cr.CRConfig;
import com.gentics.cr.CRConfigUtil;
import com.gentics.cr.CRRequest;
import com.gentics.cr.CRResolvableBean;
import com.gentics.cr.RequestProcessor;
import com.gentics.cr.exceptions.CRException;
import com.gentics.cr.exceptions.WrongOrderException;
import com.gentics.cr.monitoring.MonitorFactory;
import com.gentics.cr.monitoring.UseCase;
/**
* This class is designed as an UpdateChecker for a ContentRepository. It checks
* a Gentics ContentRepository for Updates and gives updated Documents to some
* class
* @author perhab
*
*/
public abstract class AbstractUpdateCheckerJob implements Runnable {
/**
* Log4j logger for error and debug messages.
*/
protected static Logger log =
Logger.getLogger(AbstractUpdateCheckerJob.class);
/**
* Name of class to use for IndexLocation, must extend
* {@link com.gentics.cr.util.indexing.IndexLocation}.
*/
public static final String INDEXLOCATIONCLASS =
"com.gentics.cr.util.indexing.IndexLocation";
/**
* Configuration key for the attribute containing the id.
* @see #idAttribute
*/
protected static final String ID_ATTRIBUTE_KEY = "IDATTRIBUTE";
/**
* Configuration key for the attribute containing an indicator if the object
* was updated.
* @see #timestampAttribute
*/
private static final String TIMESTAMP_ATTR_KEY = "updateattribute";
/**
* Configuration of the UpdateCheckerJob.
*/
protected CRConfig config;
/**
* Identifier of the UpdateCheckerJob.
*/
protected String identifyer;
/**
* Status of the Indexer.
*/
protected IndexerStatus status;
/**
* Name of the attribute identifying the beans.
*/
protected String idAttribute = "contentid";
/**
* Name of the attribute indicating if the object has changed. This
* attribute should change whenever the object is changed in the repository.
*/
protected String timestampAttribute = "";
/**
* TODO javadoc.
*/
private Hashtable<String, CRConfigUtil> configmap;
/**
* index location to compare the objects with.
*/
protected IndexLocation indexLocation;
/**
* marker for saving the duration in milliseconds.
*/
private long duration = 0;
/**
* start time of the job as timestamp.
*/
private long start = 0;
/**
* Initialises the default values for any implementation of the
* {@link AbstractUpdateCheckerJob}.
* @param updateCheckerConfig Configuration of the update job
* @param indexLoc index location to compare with the repository
* @param updateCheckerConfigmap TODO javadoc
*/
public AbstractUpdateCheckerJob(final CRConfig updateCheckerConfig,
final IndexLocation indexLoc,
final Hashtable<String, CRConfigUtil> updateCheckerConfigmap) {
config = updateCheckerConfig;
configmap = updateCheckerConfigmap;
if (configmap == null) {
log.debug("Configmap is empty");
}
identifyer = (String) updateCheckerConfig.getName();
indexLocation = indexLoc;
status = new IndexerStatus();
idAttribute =
updateCheckerConfig.getString(ID_ATTRIBUTE_KEY, idAttribute);
timestampAttribute = updateCheckerConfig
.getString(TIMESTAMP_ATTR_KEY, timestampAttribute);
}
/**
* Gets the config for this UpdateCheckerJob.
*
* @return configuration as CRConfig-object
*/
public final CRConfig getConfig() {
return config;
}
/**
* Gets the Job Identifyer. In most cases this is the CR id.
* @return identifyer as string
*/
public final String getIdentifyer() {
return identifyer;
}
/**
* Get job duration in milliseconds.
* @return duration of the job in milliseconds
*/
public final long getDuration() {
return duration;
}
/**
* Get the job's start time as timestamp.
* @return start time of the job as timestamp
*/
public final long getStart() {
return this.start;
}
/**
* Get the job's start time as date.
* @return start time of the job as date
*/
public final Date getStartDate() {
return new Date(getStart());
}
/**
* Get total count of objects to index.
* @return object count as int.
*/
public final int getObjectsToIndex() {
return status.getObjectCount();
}
/**
* Get the number ob objects already indexed.
* @return objects already indexed in the current job
*/
public final int getObjectsDone() {
return status.getObjectsDone();
}
/**
* Calculates ETA of the current job.
* @return ETA in ms
*/
public final long getETA() {
long eta = 0;
long objDone = this.getObjectsDone();
long objToIndex = this.getObjectsToIndex();
long objTodo = objToIndex - objDone;
long timetaken = System.currentTimeMillis() - this.getStart();
long timePerObj = 0;
if (objDone != 0) {
timePerObj = timetaken / objDone;
}
eta = objTodo * timePerObj;
return eta;
}
/**
* Get Current Status as String.
* @return current status string
*/
public final String getStatusString() {
return status.getCurrentStatusString();
}
/**
* Check if job had an error.
* @return true if error.
*/
public final boolean hasError() {
return status.hasError();
}
/**
* Get the current error message if set.
* @return error message.
*/
public final String getErrorMessage() {
return status.getErrorMessage();
}
/**
* Tests if a {@link AbstractUpdateCheckerJob} has the same identifier as
* the given object being an instance of {@link AbstractUpdateCheckerJob}.
* @param obj Object to test if it is equal to this
* @return <code>true</code> if is equal to obj, otherwise false.
*/
@Override
public boolean equals(final Object obj) {
if (obj instanceof AbstractUpdateCheckerJob) {
if (this.identifyer.equalsIgnoreCase(
((AbstractUpdateCheckerJob) obj).getIdentifyer())) {
return true;
}
}
return false;
}
protected abstract void indexCR(IndexLocation indexLocation, CRConfigUtil config) throws CRException;
/**
* get all objects that are not up to date.
* @param forceFullUpdate - boolean use to force a full update in the index
* @param request - Request describing the objects to index.
* @param rp - RequestProcessor to get the objects from.
* @param indexUpdateChecker - update checker for the index.
* @return {@link Collection} of {@link CRResolvableBean} that need to be
* updated in the index.
* @see IndexUpdateChecker#isUpToDate(String, Object, String,
* com.gentics.api.lib.resolving.Resolvable)
* @see IndexUpdateChecker#deleteStaleObjects()
*/
protected Collection<CRResolvableBean> getObjectsToUpdate(
final CRRequest request, final RequestProcessor rp,
final boolean forceFullUpdate,
final IndexUpdateChecker indexUpdateChecker) {
Collection<CRResolvableBean> updateObjects =
new Vector<CRResolvableBean>();
UseCase objectsToUpdateCase = MonitorFactory.startUseCase(
"AbstractUpdateCheck.getObjectsToUpdate(" + request.get("CRID")
+ ")");
try {
if (forceFullUpdate || "".equals(timestampAttribute)) {
try {
updateObjects = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
- log.error("Error getting results for full index from "
- + "requestprocessor", e);
+ String message = "Error getting objects to full index from "
+ + "RequestProcessor. " + e.getMessage();
+ log.error(message, e);
+ status.setError(message);
}
} else {
//Sorted (by the idAttribute) list of Resolvables to check for
//Updates.
Collection<CRResolvableBean> objectsToIndex;
try {
defaultizeRequest(request);
objectsToIndex = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
- log.error("Error getting results for full index from "
- + "requestprocessor", e);
+ String message = "Error getting objects to index from "
+ + "RequestProcessor. " + e.getMessage();
+ log.error(message, e);
+ status.setError(message);
return null;
}
Iterator<CRResolvableBean> resolvableIterator =
objectsToIndex.iterator();
try {
while (resolvableIterator.hasNext()) {
CRResolvableBean crElement = resolvableIterator.next();
Object crElementIDObject = crElement.get(idAttribute);
if (crElementIDObject == null) {
log.error("IDAttribute is null!");
}
String crElementID = crElementIDObject.toString();
Object crElementTimestamp =
crElement.get(timestampAttribute);
if (!indexUpdateChecker.isUpToDate(crElementID,
crElementTimestamp, timestampAttribute,
crElement)) {
updateObjects.add(crElement);
}
}
} catch (WrongOrderException e) {
log.error("Got the objects from the datasource in the wrong"
+ "order.", e);
+ status.setError("Got the objects from the datasource in the"
+ + "wrong order.");
return null;
}
}
//Finally delete all Objects from Index that are not checked for an
//Update
indexUpdateChecker.deleteStaleObjects();
} finally {
objectsToUpdateCase.stop();
}
return updateObjects;
}
private void defaultizeRequest(CRRequest request) {
String[] prefill = request.getAttributeArray(idAttribute);
List<String> prefillList = Arrays.asList(prefill);
if(!"".equals(timestampAttribute) && !prefillList.contains(timestampAttribute))
{
ArrayList<String> pf = new ArrayList<String>(prefillList);
pf.add(timestampAttribute);
request.setAttributeArray(pf.toArray(prefill));
}
String[] sorting = request.getSortArray();
if (sorting == null) {
request.setSortArray(new String[]{idAttribute + ":asc"});
} else if (!Arrays.asList(sorting).contains(idAttribute + ":asc")) {
ArrayList<String> sf = new ArrayList<String>(Arrays.asList(sorting));
sf.add(idAttribute + ":asc");
request.setSortArray(sf.toArray(sorting));
}
}
/**
* Executes the index process.
*/
public void run() {
this.start = System.currentTimeMillis();
try {
indexCR(this.indexLocation, (CRConfigUtil) this.config);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
this.duration = System.currentTimeMillis() - start;
}
}
| false | true |
protected Collection<CRResolvableBean> getObjectsToUpdate(
final CRRequest request, final RequestProcessor rp,
final boolean forceFullUpdate,
final IndexUpdateChecker indexUpdateChecker) {
Collection<CRResolvableBean> updateObjects =
new Vector<CRResolvableBean>();
UseCase objectsToUpdateCase = MonitorFactory.startUseCase(
"AbstractUpdateCheck.getObjectsToUpdate(" + request.get("CRID")
+ ")");
try {
if (forceFullUpdate || "".equals(timestampAttribute)) {
try {
updateObjects = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
log.error("Error getting results for full index from "
+ "requestprocessor", e);
}
} else {
//Sorted (by the idAttribute) list of Resolvables to check for
//Updates.
Collection<CRResolvableBean> objectsToIndex;
try {
defaultizeRequest(request);
objectsToIndex = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
log.error("Error getting results for full index from "
+ "requestprocessor", e);
return null;
}
Iterator<CRResolvableBean> resolvableIterator =
objectsToIndex.iterator();
try {
while (resolvableIterator.hasNext()) {
CRResolvableBean crElement = resolvableIterator.next();
Object crElementIDObject = crElement.get(idAttribute);
if (crElementIDObject == null) {
log.error("IDAttribute is null!");
}
String crElementID = crElementIDObject.toString();
Object crElementTimestamp =
crElement.get(timestampAttribute);
if (!indexUpdateChecker.isUpToDate(crElementID,
crElementTimestamp, timestampAttribute,
crElement)) {
updateObjects.add(crElement);
}
}
} catch (WrongOrderException e) {
log.error("Got the objects from the datasource in the wrong"
+ "order.", e);
return null;
}
}
//Finally delete all Objects from Index that are not checked for an
//Update
indexUpdateChecker.deleteStaleObjects();
} finally {
objectsToUpdateCase.stop();
}
return updateObjects;
}
|
protected Collection<CRResolvableBean> getObjectsToUpdate(
final CRRequest request, final RequestProcessor rp,
final boolean forceFullUpdate,
final IndexUpdateChecker indexUpdateChecker) {
Collection<CRResolvableBean> updateObjects =
new Vector<CRResolvableBean>();
UseCase objectsToUpdateCase = MonitorFactory.startUseCase(
"AbstractUpdateCheck.getObjectsToUpdate(" + request.get("CRID")
+ ")");
try {
if (forceFullUpdate || "".equals(timestampAttribute)) {
try {
updateObjects = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
String message = "Error getting objects to full index from "
+ "RequestProcessor. " + e.getMessage();
log.error(message, e);
status.setError(message);
}
} else {
//Sorted (by the idAttribute) list of Resolvables to check for
//Updates.
Collection<CRResolvableBean> objectsToIndex;
try {
defaultizeRequest(request);
objectsToIndex = (Collection<CRResolvableBean>)
rp.getObjects(request);
} catch (CRException e) {
String message = "Error getting objects to index from "
+ "RequestProcessor. " + e.getMessage();
log.error(message, e);
status.setError(message);
return null;
}
Iterator<CRResolvableBean> resolvableIterator =
objectsToIndex.iterator();
try {
while (resolvableIterator.hasNext()) {
CRResolvableBean crElement = resolvableIterator.next();
Object crElementIDObject = crElement.get(idAttribute);
if (crElementIDObject == null) {
log.error("IDAttribute is null!");
}
String crElementID = crElementIDObject.toString();
Object crElementTimestamp =
crElement.get(timestampAttribute);
if (!indexUpdateChecker.isUpToDate(crElementID,
crElementTimestamp, timestampAttribute,
crElement)) {
updateObjects.add(crElement);
}
}
} catch (WrongOrderException e) {
log.error("Got the objects from the datasource in the wrong"
+ "order.", e);
status.setError("Got the objects from the datasource in the"
+ "wrong order.");
return null;
}
}
//Finally delete all Objects from Index that are not checked for an
//Update
indexUpdateChecker.deleteStaleObjects();
} finally {
objectsToUpdateCase.stop();
}
return updateObjects;
}
|
diff --git a/cli/src/main/java/com/meltmedia/cadmium/cli/LoggerCommand.java b/cli/src/main/java/com/meltmedia/cadmium/cli/LoggerCommand.java
index fee22ec8..bdd6d913 100644
--- a/cli/src/main/java/com/meltmedia/cadmium/cli/LoggerCommand.java
+++ b/cli/src/main/java/com/meltmedia/cadmium/cli/LoggerCommand.java
@@ -1,140 +1,141 @@
/**
* Copyright 2012 meltmedia
*
* 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.meltmedia.cadmium.cli;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import ch.qos.logback.classic.Level;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.gson.Gson;
import com.meltmedia.cadmium.core.LoggerConfig;
import com.meltmedia.cadmium.core.LoggerServiceResponse;
/**
* <p>CLI Command that queries or updates the logging level of each node in the cluster.</p>
* <p>The @Parameters of this class get wired up by JCommander.</p>
*
* @see <a href="http://jcommander.org/">JCommander</a>
*
* @author John McEntire
*
*/
@Parameters(commandDescription="This command will query or update the logging level.", separators="=")
public class LoggerCommand extends AbstractAuthorizedOnly implements CliCommand {
/**
* A collection of strings that will be assigned the raw parameters that are not associated with an option.
*
* @see <a href="http://jcommander.org/">JCommander</a>
*/
@Parameter(description="[logger] [level] <site>")
private List<String> params;
@Override
public String getCommandName() {return "logger";}
@Override
public void execute() throws Exception {
String logger = null;
String level = null;
String site = null;
if(params != null && params.size() >= 3) {
logger = params.get(0);
level = params.get(1);
site = params.get(2);
} else if (params != null && params.size() == 2) {
String value = params.get(0);
try {
level = Level.toLevel(value, null).levelStr;
} catch(Exception e) {
logger = value;
}
site = params.get(1);
} else if(params != null && params.size() == 1) {
site = params.get(0);
} else {
System.err.println("A site is required!");
System.exit(1);
}
- DefaultHttpClient client = new DefaultHttpClient();
+ DefaultHttpClient client = setTrustAllSSLCerts(new DefaultHttpClient());
HttpMessage method = null;
+ site = this.getSecureBaseUrl(site);
if(level != null) {
- String uri = this.getSecureBaseUrl(site)+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME+"/")+(StringUtils.isNotBlank(level)?level:"DEBUG");
+ String uri = site+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME+"/")+(StringUtils.isNotBlank(level)?level:"DEBUG");
System.out.println("Updating logger ["+(StringUtils.isNotBlank(logger)?logger:"ROOT") + "] to level ["+level+"] for site " + site);
method = new HttpPost(uri);
} else {
- String uri = this.getSecureBaseUrl(site)+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":"");
+ String uri = site+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":"");
System.out.println("Getting levels for "+(StringUtils.isNotBlank(logger)?logger:"all") + " logger[s] on site " + site);
method = new HttpGet(uri);
}
addAuthHeader(method);
HttpResponse response = client.execute((HttpUriRequest) method);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
LoggerServiceResponse configs = new Gson().fromJson(EntityUtils.toString(response.getEntity()), LoggerServiceResponse.class);
List<String> nodes = new ArrayList<String>();
nodes.addAll(configs.getConfigs().keySet());
Collections.sort(nodes);
List<String> loggers = new ArrayList<String>();
Map<String, String[]> loggerLevels = new HashMap<String, String[]>();
for(String node: nodes) {
for(LoggerConfig config : configs.getConfigs().get(node)){
if(!loggers.contains(config.getName())) {
loggers.add(config.getName());
loggerLevels.put(config.getName(), new String[nodes.size()]);
Arrays.fill(loggerLevels.get(config.getName()), "-");
}
loggerLevels.get(config.getName())[nodes.indexOf(node)] = config.getLevel();
}
}
Collections.sort(loggers);
if(loggers.remove(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)) {
loggers.add(0, ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
}
System.out.println("Got " + loggers.size() + " logger[s] and " + nodes.size() + " node[s]");
for(String loggerName : loggers) {
System.out.println("Logger: "+loggerName);
String levels[] = loggerLevels.get(loggerName);
for(String node : nodes) {
System.out.println(" " + node + ": "+levels[nodes.indexOf(node)]);
}
}
} else {
System.err.println("Request failed: " + response.getStatusLine());
System.err.println("Raw response [" + EntityUtils.toString(response.getEntity()) + "]");
}
}
}
| false | true |
public void execute() throws Exception {
String logger = null;
String level = null;
String site = null;
if(params != null && params.size() >= 3) {
logger = params.get(0);
level = params.get(1);
site = params.get(2);
} else if (params != null && params.size() == 2) {
String value = params.get(0);
try {
level = Level.toLevel(value, null).levelStr;
} catch(Exception e) {
logger = value;
}
site = params.get(1);
} else if(params != null && params.size() == 1) {
site = params.get(0);
} else {
System.err.println("A site is required!");
System.exit(1);
}
DefaultHttpClient client = new DefaultHttpClient();
HttpMessage method = null;
if(level != null) {
String uri = this.getSecureBaseUrl(site)+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME+"/")+(StringUtils.isNotBlank(level)?level:"DEBUG");
System.out.println("Updating logger ["+(StringUtils.isNotBlank(logger)?logger:"ROOT") + "] to level ["+level+"] for site " + site);
method = new HttpPost(uri);
} else {
String uri = this.getSecureBaseUrl(site)+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":"");
System.out.println("Getting levels for "+(StringUtils.isNotBlank(logger)?logger:"all") + " logger[s] on site " + site);
method = new HttpGet(uri);
}
addAuthHeader(method);
HttpResponse response = client.execute((HttpUriRequest) method);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
LoggerServiceResponse configs = new Gson().fromJson(EntityUtils.toString(response.getEntity()), LoggerServiceResponse.class);
List<String> nodes = new ArrayList<String>();
nodes.addAll(configs.getConfigs().keySet());
Collections.sort(nodes);
List<String> loggers = new ArrayList<String>();
Map<String, String[]> loggerLevels = new HashMap<String, String[]>();
for(String node: nodes) {
for(LoggerConfig config : configs.getConfigs().get(node)){
if(!loggers.contains(config.getName())) {
loggers.add(config.getName());
loggerLevels.put(config.getName(), new String[nodes.size()]);
Arrays.fill(loggerLevels.get(config.getName()), "-");
}
loggerLevels.get(config.getName())[nodes.indexOf(node)] = config.getLevel();
}
}
Collections.sort(loggers);
if(loggers.remove(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)) {
loggers.add(0, ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
}
System.out.println("Got " + loggers.size() + " logger[s] and " + nodes.size() + " node[s]");
for(String loggerName : loggers) {
System.out.println("Logger: "+loggerName);
String levels[] = loggerLevels.get(loggerName);
for(String node : nodes) {
System.out.println(" " + node + ": "+levels[nodes.indexOf(node)]);
}
}
} else {
System.err.println("Request failed: " + response.getStatusLine());
System.err.println("Raw response [" + EntityUtils.toString(response.getEntity()) + "]");
}
}
|
public void execute() throws Exception {
String logger = null;
String level = null;
String site = null;
if(params != null && params.size() >= 3) {
logger = params.get(0);
level = params.get(1);
site = params.get(2);
} else if (params != null && params.size() == 2) {
String value = params.get(0);
try {
level = Level.toLevel(value, null).levelStr;
} catch(Exception e) {
logger = value;
}
site = params.get(1);
} else if(params != null && params.size() == 1) {
site = params.get(0);
} else {
System.err.println("A site is required!");
System.exit(1);
}
DefaultHttpClient client = setTrustAllSSLCerts(new DefaultHttpClient());
HttpMessage method = null;
site = this.getSecureBaseUrl(site);
if(level != null) {
String uri = site+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME+"/")+(StringUtils.isNotBlank(level)?level:"DEBUG");
System.out.println("Updating logger ["+(StringUtils.isNotBlank(logger)?logger:"ROOT") + "] to level ["+level+"] for site " + site);
method = new HttpPost(uri);
} else {
String uri = site+"/system/logger/"+(StringUtils.isNotBlank(logger)?logger+"/":"");
System.out.println("Getting levels for "+(StringUtils.isNotBlank(logger)?logger:"all") + " logger[s] on site " + site);
method = new HttpGet(uri);
}
addAuthHeader(method);
HttpResponse response = client.execute((HttpUriRequest) method);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
LoggerServiceResponse configs = new Gson().fromJson(EntityUtils.toString(response.getEntity()), LoggerServiceResponse.class);
List<String> nodes = new ArrayList<String>();
nodes.addAll(configs.getConfigs().keySet());
Collections.sort(nodes);
List<String> loggers = new ArrayList<String>();
Map<String, String[]> loggerLevels = new HashMap<String, String[]>();
for(String node: nodes) {
for(LoggerConfig config : configs.getConfigs().get(node)){
if(!loggers.contains(config.getName())) {
loggers.add(config.getName());
loggerLevels.put(config.getName(), new String[nodes.size()]);
Arrays.fill(loggerLevels.get(config.getName()), "-");
}
loggerLevels.get(config.getName())[nodes.indexOf(node)] = config.getLevel();
}
}
Collections.sort(loggers);
if(loggers.remove(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)) {
loggers.add(0, ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
}
System.out.println("Got " + loggers.size() + " logger[s] and " + nodes.size() + " node[s]");
for(String loggerName : loggers) {
System.out.println("Logger: "+loggerName);
String levels[] = loggerLevels.get(loggerName);
for(String node : nodes) {
System.out.println(" " + node + ": "+levels[nodes.indexOf(node)]);
}
}
} else {
System.err.println("Request failed: " + response.getStatusLine());
System.err.println("Raw response [" + EntityUtils.toString(response.getEntity()) + "]");
}
}
|
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java b/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java
index 201537798..9dc71a52d 100644
--- a/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java
+++ b/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java
@@ -1,310 +1,311 @@
/*******************************************************************************
* 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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Adapts {@link org.eclipse.jface.text.IDocument} for doing search and
* replace operations.
*
* @since 3.0
*/
public class FindReplaceDocumentAdapter implements CharSequence {
private static class FindReplaceOperationCode {
}
// Shortcuts to findReplace operation codes
private static final FindReplaceOperationCode FIND_FIRST= new FindReplaceOperationCode();
private static final FindReplaceOperationCode FIND_NEXT= new FindReplaceOperationCode();
private static final FindReplaceOperationCode REPLACE= new FindReplaceOperationCode();
private static final FindReplaceOperationCode REPLACE_FIND_NEXT= new FindReplaceOperationCode();
/**
* The adapted document.
*/
private IDocument fDocument;
/**
* State for findReplace.
*/
private FindReplaceOperationCode fFindReplaceState= null;
/**
* The matcher used in findReplace.
*/
private Matcher fFindReplaceMatcher;
/**
* The match offset from the last findReplace call.
*/
private int fFindReplaceMatchOffset;
/**
* Constructs a new find replace document adapter.
*
* @param document the adapted document
*/
public FindReplaceDocumentAdapter(IDocument document) {
Assert.isNotNull(document);
fDocument= document;
}
/**
* Returns the location of a given string in this adapter's document based on a set of search criteria.
*
* @param startOffset document offset at which search starts
* @param findString the string to find
* @param forwardSearch the search direction
* @param caseSensitive indicates whether lower and upper case should be distinguished
* @param wholeWord indicates whether the findString should be limited by white spaces as
* defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>.
* @param regExSearch if <code>true</code> findString represents a regular expression
* Must not be used in combination with <code>wholeWord</code>.
* @return the find or replace region or <code>null</code> if there was no match
* @throws BadLocationException if startOffset is an invalid document offset
* @throws PatternSyntaxException if a regular expression has invalid syntax
*/
public IRegion find(int startOffset, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
Assert.isTrue(!(regExSearch && wholeWord));
// Adjust offset to special meaning of -1
if (startOffset == -1 && forwardSearch)
startOffset= 0;
if (startOffset == -1 && !forwardSearch)
startOffset= length() - 1;
return findReplace(FIND_FIRST, startOffset, findString, null, forwardSearch, caseSensitive, wholeWord, regExSearch);
}
/**
* Stateful findReplace executes a FIND, REPLACE, REPLACE_FIND or FIND_FIRST operation.
* In case of REPLACE and REPLACE_FIND it sends a <code>DocumentEvent</code> to all
* registered <code>IDocumentListener</code>.
*
* @param startOffset document offset at which search starts
* this value is only used in the FIND_FIRST operation and otherwise ignored
* @param findString the string to find
* this value is only used in the FIND_FIRST operation and otherwise ignored
* @param replaceText the string to replace the current match
* this value is only used in the REPLACE and REPLACE_FIND operations and otherwise ignored
* @param forwardSearch the search direction
* @param caseSensitive indicates whether lower and upper case should be distinguished
* @param wholeWord indicates whether the findString should be limited by white spaces as
* defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>.
* @param regExSearch if <code>true</code> this operation represents a regular expression
* Must not be used in combination with <code>wholeWord</code>.
* @param operationCode specifies what kind of operation is executed
* @return the find or replace region or <code>null</code> if there was no match
* @throws BadLocationException if startOffset is an invalid document offset
* @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation
* @throws PatternSyntaxException if a regular expression has invalid syntax
*/
- private IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
+ private IRegion findReplace(final FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
// Validate option combinations
Assert.isTrue(!(regExSearch && wholeWord));
// Validate state
if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT))
throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$
if (operationCode == FIND_FIRST) {
// Reset
if (findString == null || findString.length() == 0)
return null;
// Validate start offset
if (startOffset < 0 || startOffset >= length())
throw new BadLocationException();
int patternFlags= 0;
if (regExSearch)
patternFlags |= Pattern.MULTILINE;
if (!caseSensitive)
patternFlags |= Pattern.CASE_INSENSITIVE;
if (wholeWord)
findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$
if (!regExSearch && !wholeWord)
findString= asRegPattern(findString);
fFindReplaceMatchOffset= startOffset;
if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) {
/*
* Commented out for optimazation:
* The call is not needed since FIND_FIRST uses find(int) which resets the matcher
*/
// fFindReplaceMatcher.reset();
} else {
Pattern pattern= Pattern.compile(findString, patternFlags);
fFindReplaceMatcher= pattern.matcher(this);
}
}
// Set state
fFindReplaceState= operationCode;
if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) {
if (regExSearch) {
Pattern pattern= fFindReplaceMatcher.pattern();
Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group());
try {
replaceText= replaceTextMatcher.replaceFirst(replaceText);
} catch (IndexOutOfBoundsException ex) {
throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1);
}
}
int offset= fFindReplaceMatcher.start();
fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText);
if (operationCode == REPLACE) {
return new Region(offset, replaceText.length());
}
}
if (operationCode != REPLACE) {
if (forwardSearch) {
boolean found= false;
if (operationCode == FIND_FIRST)
found= fFindReplaceMatcher.find(startOffset);
else
found= fFindReplaceMatcher.find();
- fFindReplaceState= operationCode;
+ if (operationCode == REPLACE_FIND_NEXT)
+ fFindReplaceState= FIND_NEXT;
if (found && fFindReplaceMatcher.group().length() > 0) {
return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length());
} else {
return null;
}
} else { // backward search
boolean found= fFindReplaceMatcher.find(0);
int index= -1;
int length= -1;
while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) {
index= fFindReplaceMatcher.start();
length= fFindReplaceMatcher.group().length();
found= fFindReplaceMatcher.find(index + 1);
}
fFindReplaceMatchOffset= index;
if (index > -1) {
// must set matcher to correct position
fFindReplaceMatcher.find(index);
return new Region(index, length);
} else
return null;
}
}
return null;
}
/**
* Converts a non-regex string to a pattern
* that can be used with the regex search engine.
*
* @param string the non-regex pattern
* @return the string converted to a regex pattern
*/
private String asRegPattern(String string) {
StringBuffer out= new StringBuffer(string.length());
boolean quoting= false;
for (int i= 0, length= string.length(); i < length; i++) {
char ch= string.charAt(i);
if (ch == '\\') {
if (quoting) {
out.append("\\E"); //$NON-NLS-1$
quoting= false;
}
out.append("\\\\"); //$NON-NLS-1$
continue;
}
if (!quoting) {
out.append("\\Q"); //$NON-NLS-1$
quoting= true;
}
out.append(ch);
}
if (quoting)
out.append("\\E"); //$NON-NLS-1$
return out.toString();
}
/**
* Substitutes the previous match with the given text.
* Sends a <code>DocumentEvent</code> to all registered <code>IDocumentListener</code>.
*
* @param text the substitution text
* @param regExReplace if <code>true</code> <code>text</code> represents a regular expression
* @return the replace region or <code>null</code> if there was no match
* @throws BadLocationException if startOffset is an invalid document offset
* @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation
* @throws PatternSyntaxException if a regular expression has invalid syntax
*
* @see DocumentEvent
* @see IDocumentListener
*/
public IRegion replace(String text, boolean regExReplace) throws BadLocationException {
return findReplace(REPLACE, -1, null, text, false, false, false, regExReplace);
}
// ---------- CharSequence implementation ----------
/*
* @see java.lang.CharSequence#length()
*/
public int length() {
return fDocument.getLength();
}
/*
* @see java.lang.CharSequence#charAt(int)
*/
public char charAt(int index) {
try {
return fDocument.getChar(index);
} catch (BadLocationException e) {
throw new IndexOutOfBoundsException();
}
}
/*
* @see java.lang.CharSequence#subSequence(int, int)
*/
public CharSequence subSequence(int start, int end) {
try {
return fDocument.get(start, end - start);
} catch (BadLocationException e) {
throw new IndexOutOfBoundsException();
}
}
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return fDocument.get();
}
}
| false | true |
private IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
// Validate option combinations
Assert.isTrue(!(regExSearch && wholeWord));
// Validate state
if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT))
throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$
if (operationCode == FIND_FIRST) {
// Reset
if (findString == null || findString.length() == 0)
return null;
// Validate start offset
if (startOffset < 0 || startOffset >= length())
throw new BadLocationException();
int patternFlags= 0;
if (regExSearch)
patternFlags |= Pattern.MULTILINE;
if (!caseSensitive)
patternFlags |= Pattern.CASE_INSENSITIVE;
if (wholeWord)
findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$
if (!regExSearch && !wholeWord)
findString= asRegPattern(findString);
fFindReplaceMatchOffset= startOffset;
if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) {
/*
* Commented out for optimazation:
* The call is not needed since FIND_FIRST uses find(int) which resets the matcher
*/
// fFindReplaceMatcher.reset();
} else {
Pattern pattern= Pattern.compile(findString, patternFlags);
fFindReplaceMatcher= pattern.matcher(this);
}
}
// Set state
fFindReplaceState= operationCode;
if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) {
if (regExSearch) {
Pattern pattern= fFindReplaceMatcher.pattern();
Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group());
try {
replaceText= replaceTextMatcher.replaceFirst(replaceText);
} catch (IndexOutOfBoundsException ex) {
throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1);
}
}
int offset= fFindReplaceMatcher.start();
fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText);
if (operationCode == REPLACE) {
return new Region(offset, replaceText.length());
}
}
if (operationCode != REPLACE) {
if (forwardSearch) {
boolean found= false;
if (operationCode == FIND_FIRST)
found= fFindReplaceMatcher.find(startOffset);
else
found= fFindReplaceMatcher.find();
fFindReplaceState= operationCode;
if (found && fFindReplaceMatcher.group().length() > 0) {
return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length());
} else {
return null;
}
} else { // backward search
boolean found= fFindReplaceMatcher.find(0);
int index= -1;
int length= -1;
while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) {
index= fFindReplaceMatcher.start();
length= fFindReplaceMatcher.group().length();
found= fFindReplaceMatcher.find(index + 1);
}
fFindReplaceMatchOffset= index;
if (index > -1) {
// must set matcher to correct position
fFindReplaceMatcher.find(index);
return new Region(index, length);
} else
return null;
}
}
return null;
}
|
private IRegion findReplace(final FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
// Validate option combinations
Assert.isTrue(!(regExSearch && wholeWord));
// Validate state
if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT))
throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$
if (operationCode == FIND_FIRST) {
// Reset
if (findString == null || findString.length() == 0)
return null;
// Validate start offset
if (startOffset < 0 || startOffset >= length())
throw new BadLocationException();
int patternFlags= 0;
if (regExSearch)
patternFlags |= Pattern.MULTILINE;
if (!caseSensitive)
patternFlags |= Pattern.CASE_INSENSITIVE;
if (wholeWord)
findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$
if (!regExSearch && !wholeWord)
findString= asRegPattern(findString);
fFindReplaceMatchOffset= startOffset;
if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) {
/*
* Commented out for optimazation:
* The call is not needed since FIND_FIRST uses find(int) which resets the matcher
*/
// fFindReplaceMatcher.reset();
} else {
Pattern pattern= Pattern.compile(findString, patternFlags);
fFindReplaceMatcher= pattern.matcher(this);
}
}
// Set state
fFindReplaceState= operationCode;
if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) {
if (regExSearch) {
Pattern pattern= fFindReplaceMatcher.pattern();
Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group());
try {
replaceText= replaceTextMatcher.replaceFirst(replaceText);
} catch (IndexOutOfBoundsException ex) {
throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1);
}
}
int offset= fFindReplaceMatcher.start();
fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText);
if (operationCode == REPLACE) {
return new Region(offset, replaceText.length());
}
}
if (operationCode != REPLACE) {
if (forwardSearch) {
boolean found= false;
if (operationCode == FIND_FIRST)
found= fFindReplaceMatcher.find(startOffset);
else
found= fFindReplaceMatcher.find();
if (operationCode == REPLACE_FIND_NEXT)
fFindReplaceState= FIND_NEXT;
if (found && fFindReplaceMatcher.group().length() > 0) {
return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length());
} else {
return null;
}
} else { // backward search
boolean found= fFindReplaceMatcher.find(0);
int index= -1;
int length= -1;
while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) {
index= fFindReplaceMatcher.start();
length= fFindReplaceMatcher.group().length();
found= fFindReplaceMatcher.find(index + 1);
}
fFindReplaceMatchOffset= index;
if (index > -1) {
// must set matcher to correct position
fFindReplaceMatcher.find(index);
return new Region(index, length);
} else
return null;
}
}
return null;
}
|
diff --git a/src/main/java/com/innovatrics/iseglib/SegLibException.java b/src/main/java/com/innovatrics/iseglib/SegLibException.java
index 238b990..eed85c8 100644
--- a/src/main/java/com/innovatrics/iseglib/SegLibException.java
+++ b/src/main/java/com/innovatrics/iseglib/SegLibException.java
@@ -1,16 +1,16 @@
package com.innovatrics.iseglib;
/**
* Exception thrown by the {@link SegLib} wrapper methods.
* @author Martin Vysny
*/
public class SegLibException extends RuntimeException {
private static final long serialVersionUID = 1L;
public final int errorCode;
public SegLibException(final String msg, final int errorCode) {
- super(msg);
+ super("Error #" + errorCode + ": msg");
this.errorCode = errorCode;
}
}
| true | true |
public SegLibException(final String msg, final int errorCode) {
super(msg);
this.errorCode = errorCode;
}
|
public SegLibException(final String msg, final int errorCode) {
super("Error #" + errorCode + ": msg");
this.errorCode = errorCode;
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java b/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java
index 68d547438..4376361fe 100644
--- a/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java
@@ -1,638 +1,642 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_CLASS_NEW;
import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_EXTENDS;
import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_NO_PRIMITIVES;
import java.util.ArrayList;
import java.util.Collections;
import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.BoxingStrategy;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
public class CallableBuilder {
static interface DefaultValueMethodTransformation {
public JCExpression makeDefaultValueMethod(AbstractTransformer gen,
Parameter defaultedParam, Tree.Term forwardCallTo, List<JCExpression> defaultMethodArgs);
}
public static final DefaultValueMethodTransformation DEFAULTED_PARAM_METHOD = new DefaultValueMethodTransformation() {
@Override
public JCExpression makeDefaultValueMethod(AbstractTransformer gen,
Parameter defaultedParam,
Tree.Term forwardCallTo, List<JCExpression> defaultMethodArgs) {
JCExpression fn = null;
if (forwardCallTo != null) {
if (forwardCallTo instanceof Tree.BaseMemberOrTypeExpression) {
fn = gen.makeUnquotedIdent(
Naming.getDefaultedParamMethodName((Declaration)defaultedParam.getModel().getScope(), defaultedParam));
} else if (forwardCallTo instanceof Tree.QualifiedMemberOrTypeExpression) {
fn = gen.makeQualIdent(
gen.expressionGen().transformTermForInvocation(((Tree.QualifiedMemberOrTypeExpression)forwardCallTo).getPrimary(), null),
Naming.getDefaultedParamMethodName((Declaration)defaultedParam.getModel().getScope(), defaultedParam));
}
}
if (fn == null) {
fn = gen.makeUnquotedIdent(Naming.getDefaultedParamMethodName(null, defaultedParam));
}
return gen.make().Apply(null,
fn,
defaultMethodArgs);
}
};
DefaultValueMethodTransformation defaultValueCall = DEFAULTED_PARAM_METHOD;
private final AbstractTransformer gen;
private final ProducedType typeModel;
private final ParameterList paramLists;
private boolean noDelegates;
private int numParams;
private int minimumParams;
private boolean isVariadic;
private boolean hasOptionalParameters;
private java.util.List<ProducedType> parameterTypes;
private CallableBuilder(CeylonTransformer gen, ProducedType typeModel, ParameterList paramLists) {
this.gen = gen;
this.typeModel = typeModel;
this.paramLists = paramLists;
this.numParams = paramLists.getParameters().size();
this.minimumParams = 0;
for(Parameter p : paramLists.getParameters()){
if(p.isDefaulted() || p.isSequenced())
break;
this.minimumParams++;
}
this.isVariadic = numParams > 0 && paramLists.getParameters().get(numParams-1).isSequenced();
this.hasOptionalParameters = minimumParams != numParams;
}
/**
* Constructs an {@code AbstractCallable} suitable for wrapping a method reference.
*/
public static CallableBuilder methodReference(CeylonTransformer gen, Tree.Term expr, ParameterList parameterList) {
CallableBuilder cb = new CallableBuilder(gen, expr.getTypeModel(), parameterList);
cb.parameterTypes = cb.getParameterTypesFromCallableModel();
cb.forwardTo(expr);
return cb;
}
/**
* Used for "static" method or class references like
* value x = Integer.plus;
* value y = Foo.method;
* value z = Outer.Inner;
*/
public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen,
ProducedType typeModel,
final Functional methodOrClass,
ProducedReference producedReference) {
final String instanceName = "$instance";
final ParameterList parameterList = methodOrClass.getParameterLists().get(0);
final ProducedType type = gen.getReturnTypeOfCallable(typeModel);
CallableBuilder inner = new CallableBuilder(gen, type, parameterList);
inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels();
class InstanceDefaultValueCall implements DefaultValueMethodTransformation {
@Override
public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo, List<JCExpression> defaultMethodArgs) {
if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
// We can't generate a call to the dpm because there isn't one!
// But since FunctionalParameters cannot currently have
// defaulted parameters this *must* be a variadic parameter
// and it's default is always empty.
return gen.makeEmptyAsSequential(true);
}
JCExpression fn = gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName),
Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam));
return gen.make().Apply(null,
fn,
defaultMethodArgs);
}
}
inner.defaultValueCall = new InstanceDefaultValueCall();
CallBuilder callBuilder = CallBuilder.instance(gen);
if (methodOrClass instanceof Method) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Class) {
if (Strategy.generateInstantiator((Class)methodOrClass)) {
callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass));
} else {
callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null),
gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW));
}
} else {
Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName());
}
ListBuffer<ExpressionAndType> reified = ListBuffer.lb();
DirectInvocation.addReifiedArguments(gen, producedReference, reified);
for (ExpressionAndType reifiedArgument : reified) {
callBuilder.argument(reifiedArgument.expression);
}
for (Parameter parameter : parameterList.getParameters()) {
callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName()));
}
JCExpression innerInvocation = callBuilder.build();
// Need to worry about boxing for Method and FunctionalParameter
if (methodOrClass instanceof TypedDeclaration) {
innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation,
methodOrClass.getType(),
!CodegenUtil.isUnBoxed((TypedDeclaration)methodOrClass),
BoxingStrategy.BOXED, methodOrClass.getType());
+ } else if (Strategy.isInstantiatorUntyped((Class)methodOrClass)) {
+ // $new method declared to return Object, so needs typecast
+ innerInvocation = gen.make().TypeCast(gen.makeJavaType(
+ ((Class)methodOrClass).getType()), innerInvocation);
}
inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation)));
ParameterList outerPl = new ParameterList();
Parameter instanceParameter = new Parameter();
instanceParameter.setName(instanceName);
Value valueModel = new Value();
instanceParameter.setModel(valueModel);
valueModel.setType(gen.getParameterTypeOfCallable(typeModel, 0));
valueModel.setUnboxed(false);
outerPl.getParameters().add(instanceParameter);
CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl);
outer.parameterTypes = outer.getParameterTypesFromParameterModels();
outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build())));
return outer;
}
/**
* Used for "static" value references like
* value x = Integer.plus;
* value y = Foo.method;
* value z = Outer.Inner;
*/
public static CallableBuilder unboundValueMemberReference(CeylonTransformer gen,
ProducedType typeModel,
final TypedDeclaration value) {
final String instanceName = "$instance";
CallBuilder callBuilder = CallBuilder.instance(gen);
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), value, Naming.NA_GETTER | Naming.NA_MEMBER));
JCExpression innerInvocation = callBuilder.build();
innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, value.getType(), !value.getUnboxed(), BoxingStrategy.BOXED, value.getType());
ParameterList outerPl = new ParameterList();
Parameter instanceParameter = new Parameter();
instanceParameter.setName(instanceName);
Value valueModel = new Value();
instanceParameter.setModel(valueModel);
valueModel.setType(gen.getParameterTypeOfCallable(typeModel, 0));
valueModel.setUnboxed(false);
outerPl.getParameters().add(instanceParameter);
CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl);
outer.parameterTypes = outer.getParameterTypesFromParameterModels();
outer.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation)));
return outer;
}
/**
* Constructs an {@code AbstractCallable} suitable for an anonymous function.
*/
public static CallableBuilder anonymous(
CeylonTransformer gen, Tree.Expression expr, ParameterList parameterList,
Tree.ParameterList parameterListTree,
ProducedType callableTypeModel, boolean noDelegates) {
JCExpression transformedExpr = gen.expressionGen().transformExpression(expr, BoxingStrategy.BOXED, gen.getReturnTypeOfCallable(callableTypeModel));
final List<JCStatement> stmts = List.<JCStatement>of(gen.make().Return(transformedExpr));
return methodArgument(gen, callableTypeModel, parameterList, parameterListTree, stmts, noDelegates);
}
public static CallableBuilder methodArgument(
CeylonTransformer gen,
ProducedType callableTypeModel,
ParameterList parameterList,
Tree.ParameterList parameterListTree,
List<JCStatement> stmts) {
return methodArgument(gen, callableTypeModel, parameterList, parameterListTree, stmts, false);
}
public static CallableBuilder methodArgument(
CeylonTransformer gen,
ProducedType callableTypeModel,
ParameterList parameterList,
Tree.ParameterList parameterListTree,
List<JCStatement> stmts, boolean noDelegates) {
CallableBuilder cb = new CallableBuilder(gen, callableTypeModel, parameterList);
cb.parameterTypes = cb.getParameterTypesFromParameterModels();
cb.parameterDefaultValueMethods(parameterListTree);
cb.noDelegates = noDelegates;
cb.useBody(stmts);
return cb;
}
/**
* Constructs an {@code AbstractCallable} suitable for use in a method
* definition with a multiple parameter list.
*/
public static CallableBuilder mpl(
CeylonTransformer gen,
ProducedType typeModel,
ParameterList parameterList,
Tree.ParameterList parameterListTree,
List<JCStatement> body) {
CallableBuilder cb = new CallableBuilder(gen, typeModel, parameterList);
if (body == null) {
body = List.<JCStatement>nil();
}
cb.parameterTypes = cb.getParameterTypesFromParameterModels();
cb.parameterDefaultValueMethods(parameterListTree);
cb.useBody(body);
return cb;
}
private ListBuffer<JCTree> parameterDefaultValueMethods;
private ListBuffer<JCTree> callMethods = new ListBuffer<JCTree>();
public CallableBuilder forwardTo(Tree.Term forwardCallTo) {
if (forwardCallTo == null) {
throw new RuntimeException();
}
// now generate a method for each supported minimum number of parameters below 4
// which delegates to the $call$typed method if required
for(int i=minimumParams,max = Math.min(numParams,4);i<max;i++){
ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
makeDefaultedCall(i, stmts, forwardCallTo);
makeForwardedInvocation(i, stmts, forwardCallTo);
callMethods.append(makeCallMethod(stmts.toList(), i));
}
// generate the $call method for the max number of parameters,
// which delegates to the $call$typed method if required
ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
makeDefaultedCall(numParams, stmts, forwardCallTo);
makeForwardedInvocation(numParams, stmts, forwardCallTo);
callMethods.append(makeCallMethod(stmts.toList(), numParams));
return this;
}
public CallableBuilder useBody(List<JCStatement> body) {
if (!noDelegates) {
// now generate a method for each supported minimum number of parameters below 4
// which delegates to the $call$typed method if required
for(int i=minimumParams,max = Math.min(numParams,4);i<max;i++){
ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
makeDefaultedCall(i, stmts, null);
makeCallTypedCallOrBody(i, stmts, body);
callMethods.append(makeCallMethod(stmts.toList(), i));
}
}
// generate the $call method for the max number of parameters,
// which delegates to the $call$typed method if required
ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
makeDefaultedCall(numParams, stmts, null);
makeCallTypedCallOrBody(numParams, stmts, body);
callMethods.append(makeCallMethod(stmts.toList(), numParams));
// generate the $call$typed method if required
if(hasOptionalParameters)
callMethods.append(makeCallTypedMethod(body));
return this;
}
public CallableBuilder parameterDefaultValueMethods(Tree.ParameterList parameterListTree) {
if (parameterDefaultValueMethods == null) {
parameterDefaultValueMethods = ListBuffer.lb();
}
for(Tree.Parameter p : parameterListTree.getParameters()){
if(Decl.getDefaultArgument(p) != null || p.getParameterModel().isSequenced()){
MethodDefinitionBuilder methodBuilder = gen.classGen().makeParamDefaultValueMethod(false, null, parameterListTree, p, null);
this.parameterDefaultValueMethods.append(methodBuilder.build());
}
}
return this;
}
public JCNewClass build() {
// Generate a subclass of Callable
ListBuffer<JCTree> classBody = new ListBuffer<JCTree>();
if (parameterDefaultValueMethods != null) {
classBody.appendList(parameterDefaultValueMethods);
}
classBody.appendList(callMethods);
JCClassDecl classDef = gen.make().AnonymousClassDef(gen.make().Modifiers(0), classBody.toList());
int variadicIndex = isVariadic ? numParams - 1 : -1;
JCNewClass instance = gen.make().NewClass(null,
null,
gen.makeJavaType(typeModel, JT_EXTENDS | JT_CLASS_NEW),
List.<JCExpression>of(gen.makeReifiedTypeArgument(typeModel.getTypeArgumentList().get(0)),
gen.makeReifiedTypeArgument(typeModel.getTypeArgumentList().get(1)),
gen.make().Literal(typeModel.getProducedTypeName(true)),
gen.make().TypeCast(gen.syms().shortType, gen.makeInteger(variadicIndex))),
classDef);
return instance;
}
private java.util.List<ProducedType> getParameterTypesFromCallableModel() {
java.util.List<ProducedType> parameterTypes = new ArrayList<ProducedType>(numParams);
for(int i=0;i<numParams;i++) {
parameterTypes.add(gen.getParameterTypeOfCallable(typeModel, i));
}
return parameterTypes;
}
private java.util.List<ProducedType> getParameterTypesFromParameterModels() {
java.util.List<ProducedType> parameterTypes = new ArrayList<ProducedType>(numParams);
// get them from our declaration
for(Parameter p : paramLists.getParameters()){
ProducedType pt;
MethodOrValue pm = p.getModel();
if(pm instanceof Method
&& ((Method)pm).isParameter())
pt = gen.getTypeForFunctionalParameter((Method) pm);
else
pt = p.getType();
parameterTypes.add(pt);
}
return parameterTypes;
}
private JCExpression getTypedParameter(Parameter param, int argIndex, boolean varargs){
JCExpression argExpr;
if (!varargs) {
// The Callable has overridden one of the non-varargs call()
// methods
argExpr = gen.make().Ident(
makeParamName(gen, argIndex));
} else {
// The Callable has overridden the varargs call() method
// so we need to index into the varargs array
argExpr = gen.make().Indexed(
gen.make().Ident(makeParamName(gen, 0)),
gen.make().Literal(argIndex));
}
// make sure we unbox it if required
argExpr = gen.expressionGen().applyErasureAndBoxing(argExpr,
parameterTypes.get(argIndex), // it came in as Object, but we need to pretend its type
// is the parameter type because that's how unboxing determines how it has to unbox
true, // it's completely erased
true, // it came in boxed
CodegenUtil.getBoxingStrategy(param.getModel()), // see if we need to box
parameterTypes.get(argIndex), // see what type we need
ExpressionTransformer.EXPR_DOWN_CAST); // we're effectively downcasting it from Object
return argExpr;
}
private void makeDefaultedCall(final int i, ListBuffer<JCStatement> stmts,
Tree.Term forwardCallTo) {
// collect every parameter
int a = 0;
for(Parameter param : paramLists.getParameters()){
// don't read default parameter values for forwarded calls
if(forwardCallTo != null && i == a)
break;
stmts.append(makeArgumentVar(param, a, i, forwardCallTo));
a++;
}
}
private void makeCallTypedCallOrBody(final int i, ListBuffer<JCStatement> stmts, List<JCStatement> body) {
if(hasOptionalParameters){
// chain to n param typed method
List<JCExpression> args = List.nil();
// pass along the parameters
for(int a=paramLists.getParameters().size()-1;a>=0;a--){
Parameter param = paramLists.getParameters().get(a);
args = args.prepend(gen.makeUnquotedIdent(getCallableTempVarName(param, null)));
}
JCMethodInvocation chain = gen.make().Apply(null, gen.makeUnquotedIdent(Naming.getCallableTypedMethodName()), args);
stmts.append(gen.make().Return(chain));
}else{
// insert the method body directly
stmts.appendList(body);
}
return;
}
/**
* <p>Makes a variable declaration for variable which will be used as an
* argument to a call. The variable is initialized to either the
* corresponding parameter,</p>
* <pre>
* Foo foo = (Foo)arg0;
* </pre>
* <p>or the default value for the corresponding parameter</p>
* <pre>
* Bar bar = $$bar(**previous-args**);
* </pre>
*/
private JCVariableDecl makeArgumentVar(final Parameter param,
final int a, final int i, Tree.Term forwardCallTo) {
// read the value
JCExpression paramExpression = getTypedParameter(param, a, i>3);
JCExpression varInitialExpression;
if(param.isDefaulted() || param.isSequenced()){
if(i > 3){
// must check if it's defined
JCExpression test = gen.make().Binary(JCTree.GT, gen.makeSelect(getParamName(0), "length"), gen.makeInteger(a));
JCExpression elseBranch = makeDefaultValueCall(param, a, forwardCallTo);
varInitialExpression = gen.make().Conditional(test, paramExpression, elseBranch);
}else if(a >= i){
// get its default value because we don't have it
varInitialExpression = makeDefaultValueCall(param, a, forwardCallTo);
}else{
// we must have it
varInitialExpression = paramExpression;
}
}else{
varInitialExpression = paramExpression;
}
// store it in a local var
int flags = 0;
if(!CodegenUtil.isUnBoxed(param.getModel())){
flags |= AbstractTransformer.JT_NO_PRIMITIVES;
}
// Always go raw if we're forwarding, because we're building the call ourselves and we don't get a chance to apply erasure and
// casting to parameter expressions when we pass them to the forwarded method. Ideally we could set it up correctly so that
// the proper erasure is done when we read from the Callable.call Object param, but since we store it in a variable defined here,
// we'd need to duplicate some of the erasure logic here to make or not the type raw, and that would be worse.
// Besides, named parameter invocation does the same.
// See https://github.com/ceylon/ceylon-compiler/issues/1005
if(forwardCallTo != null)
flags |= AbstractTransformer.JT_RAW;
JCVariableDecl var = gen.make().VarDef(gen.make().Modifiers(Flags.FINAL),
gen.naming.makeUnquotedName(getCallableTempVarName(param, forwardCallTo)),
gen.makeJavaType(parameterTypes.get(a), flags),
varInitialExpression);
return var;
}
private void makeForwardedInvocation(int i, ListBuffer<JCStatement> stmts, Tree.Term forwardCallTo) {
ProducedReference target;
if (forwardCallTo instanceof Tree.MemberOrTypeExpression) {
target = ((Tree.MemberOrTypeExpression)forwardCallTo).getTarget();
} else if (forwardCallTo instanceof Tree.FunctionArgument) {
Method method = ((Tree.FunctionArgument) forwardCallTo).getDeclarationModel();
target = method.getProducedReference(null, Collections.<ProducedType>emptyList());
} else {
throw new RuntimeException(forwardCallTo.getNodeType());
}
TypeDeclaration primaryDeclaration = forwardCallTo.getTypeModel().getDeclaration();
CallableInvocation invocationBuilder = new CallableInvocation (
gen,
forwardCallTo,
primaryDeclaration,
target,
gen.getReturnTypeOfCallable(forwardCallTo.getTypeModel()),
forwardCallTo,
paramLists,
i);
boolean prevCallableInv = gen.expressionGen().withinSyntheticClassBody(true);
JCExpression invocation;
try {
invocation = gen.expressionGen().transformInvocation(invocationBuilder);
} finally {
gen.expressionGen().withinSyntheticClassBody(prevCallableInv);
}
stmts.append(gen.make().Return(invocation));
}
private String getCallableTempVarName(Parameter param, Tree.Term forwardCallTo) {
// prefix them with $$ if we only forward, otherwise we need them to have the proper names
return forwardCallTo != null ? Naming.getCallableTempVarName(param) : param.getName();
}
private JCExpression makeDefaultValueCall(Parameter defaultedParam, int i,
Tree.Term forwardCallTo){
// add the default value
List<JCExpression> defaultMethodArgs = List.nil();
// pass all the previous values
for(int a=i-1;a>=0;a--){
Parameter param = paramLists.getParameters().get(a);
JCExpression previousValue = gen.makeUnquotedIdent(getCallableTempVarName(param, forwardCallTo));
defaultMethodArgs = defaultMethodArgs.prepend(previousValue);
}
// now call the default value method
return defaultValueCall.makeDefaultValueMethod(gen, defaultedParam, forwardCallTo, defaultMethodArgs);
}
private JCTree makeCallMethod(List<JCStatement> body, int numParams) {
MethodDefinitionBuilder callMethod = MethodDefinitionBuilder.callable(gen);
callMethod.isOverride(true);
callMethod.modifiers(Flags.PUBLIC);
ProducedType returnType = gen.getReturnTypeOfCallable(typeModel);
callMethod.resultType(gen.makeJavaType(returnType, JT_NO_PRIMITIVES), null);
// Now append formal parameters
switch (numParams) {
case 3:
callMethod.parameter(makeCallableCallParam(0, numParams-3));
// fall through
case 2:
callMethod.parameter(makeCallableCallParam(0, numParams-2));
// fall through
case 1:
callMethod.parameter(makeCallableCallParam(0, numParams-1));
break;
case 0:
break;
default: // use varargs
callMethod.parameter(makeCallableCallParam(Flags.VARARGS, 0));
}
// Return the call result, or null if a void method
callMethod.body(body);
return callMethod.build();
}
private JCTree makeCallTypedMethod(List<JCStatement> body) {
// make the method
MethodDefinitionBuilder methodBuilder = MethodDefinitionBuilder.systemMethod(gen, Naming.getCallableTypedMethodName());
methodBuilder.noAnnotations();
methodBuilder.modifiers(Flags.PRIVATE);
ProducedType returnType = gen.getReturnTypeOfCallable(typeModel);
methodBuilder.resultType(gen.makeJavaType(returnType, JT_NO_PRIMITIVES), null);
// add all parameters
int i=0;
for(Parameter param : paramLists.getParameters()){
ParameterDefinitionBuilder parameterBuilder = ParameterDefinitionBuilder.instance(gen, param.getName());
JCExpression paramType = gen.makeJavaType(parameterTypes.get(i));
parameterBuilder.type(paramType, null);
methodBuilder.parameter(parameterBuilder);
i++;
}
// Return the call result, or null if a void method
methodBuilder.body(body);
return methodBuilder.build();
}
private static Name makeParamName(AbstractTransformer gen, int paramIndex) {
return gen.names().fromString(getParamName(paramIndex));
}
private static String getParamName(int paramIndex) {
return "$param$"+paramIndex;
}
private ParameterDefinitionBuilder makeCallableCallParam(long flags, int ii) {
JCExpression type = gen.makeIdent(gen.syms().objectType);
if ((flags & Flags.VARARGS) != 0) {
type = gen.make().TypeArray(type);
}
ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.instance(gen, getParamName(ii));
pdb.modifiers(Flags.FINAL | flags);
pdb.type(type, null);
return pdb;
/*
return gen.make().VarDef(gen.make().Modifiers(Flags.FINAL | Flags.PARAMETER | flags),
makeParamName(gen, ii), type, null);
*/
}
}
| true | true |
public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen,
ProducedType typeModel,
final Functional methodOrClass,
ProducedReference producedReference) {
final String instanceName = "$instance";
final ParameterList parameterList = methodOrClass.getParameterLists().get(0);
final ProducedType type = gen.getReturnTypeOfCallable(typeModel);
CallableBuilder inner = new CallableBuilder(gen, type, parameterList);
inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels();
class InstanceDefaultValueCall implements DefaultValueMethodTransformation {
@Override
public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo, List<JCExpression> defaultMethodArgs) {
if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
// We can't generate a call to the dpm because there isn't one!
// But since FunctionalParameters cannot currently have
// defaulted parameters this *must* be a variadic parameter
// and it's default is always empty.
return gen.makeEmptyAsSequential(true);
}
JCExpression fn = gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName),
Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam));
return gen.make().Apply(null,
fn,
defaultMethodArgs);
}
}
inner.defaultValueCall = new InstanceDefaultValueCall();
CallBuilder callBuilder = CallBuilder.instance(gen);
if (methodOrClass instanceof Method) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Class) {
if (Strategy.generateInstantiator((Class)methodOrClass)) {
callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass));
} else {
callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null),
gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW));
}
} else {
Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName());
}
ListBuffer<ExpressionAndType> reified = ListBuffer.lb();
DirectInvocation.addReifiedArguments(gen, producedReference, reified);
for (ExpressionAndType reifiedArgument : reified) {
callBuilder.argument(reifiedArgument.expression);
}
for (Parameter parameter : parameterList.getParameters()) {
callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName()));
}
JCExpression innerInvocation = callBuilder.build();
// Need to worry about boxing for Method and FunctionalParameter
if (methodOrClass instanceof TypedDeclaration) {
innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation,
methodOrClass.getType(),
!CodegenUtil.isUnBoxed((TypedDeclaration)methodOrClass),
BoxingStrategy.BOXED, methodOrClass.getType());
}
inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation)));
ParameterList outerPl = new ParameterList();
Parameter instanceParameter = new Parameter();
instanceParameter.setName(instanceName);
Value valueModel = new Value();
instanceParameter.setModel(valueModel);
valueModel.setType(gen.getParameterTypeOfCallable(typeModel, 0));
valueModel.setUnboxed(false);
outerPl.getParameters().add(instanceParameter);
CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl);
outer.parameterTypes = outer.getParameterTypesFromParameterModels();
outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build())));
return outer;
}
|
public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen,
ProducedType typeModel,
final Functional methodOrClass,
ProducedReference producedReference) {
final String instanceName = "$instance";
final ParameterList parameterList = methodOrClass.getParameterLists().get(0);
final ProducedType type = gen.getReturnTypeOfCallable(typeModel);
CallableBuilder inner = new CallableBuilder(gen, type, parameterList);
inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels();
class InstanceDefaultValueCall implements DefaultValueMethodTransformation {
@Override
public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo, List<JCExpression> defaultMethodArgs) {
if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
// We can't generate a call to the dpm because there isn't one!
// But since FunctionalParameters cannot currently have
// defaulted parameters this *must* be a variadic parameter
// and it's default is always empty.
return gen.makeEmptyAsSequential(true);
}
JCExpression fn = gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName),
Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam));
return gen.make().Apply(null,
fn,
defaultMethodArgs);
}
}
inner.defaultValueCall = new InstanceDefaultValueCall();
CallBuilder callBuilder = CallBuilder.instance(gen);
if (methodOrClass instanceof Method) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Method
&& ((Method)methodOrClass).isParameter()) {
callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER));
} else if (methodOrClass instanceof Class) {
if (Strategy.generateInstantiator((Class)methodOrClass)) {
callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass));
} else {
callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null),
gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW));
}
} else {
Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName());
}
ListBuffer<ExpressionAndType> reified = ListBuffer.lb();
DirectInvocation.addReifiedArguments(gen, producedReference, reified);
for (ExpressionAndType reifiedArgument : reified) {
callBuilder.argument(reifiedArgument.expression);
}
for (Parameter parameter : parameterList.getParameters()) {
callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName()));
}
JCExpression innerInvocation = callBuilder.build();
// Need to worry about boxing for Method and FunctionalParameter
if (methodOrClass instanceof TypedDeclaration) {
innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation,
methodOrClass.getType(),
!CodegenUtil.isUnBoxed((TypedDeclaration)methodOrClass),
BoxingStrategy.BOXED, methodOrClass.getType());
} else if (Strategy.isInstantiatorUntyped((Class)methodOrClass)) {
// $new method declared to return Object, so needs typecast
innerInvocation = gen.make().TypeCast(gen.makeJavaType(
((Class)methodOrClass).getType()), innerInvocation);
}
inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation)));
ParameterList outerPl = new ParameterList();
Parameter instanceParameter = new Parameter();
instanceParameter.setName(instanceName);
Value valueModel = new Value();
instanceParameter.setModel(valueModel);
valueModel.setType(gen.getParameterTypeOfCallable(typeModel, 0));
valueModel.setUnboxed(false);
outerPl.getParameters().add(instanceParameter);
CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl);
outer.parameterTypes = outer.getParameterTypesFromParameterModels();
outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build())));
return outer;
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/evaluator/GreqlEvaluator.java b/src/de/uni_koblenz/jgralab/greql2/evaluator/GreqlEvaluator.java
index bafd00119..3f9523e18 100644
--- a/src/de/uni_koblenz/jgralab/greql2/evaluator/GreqlEvaluator.java
+++ b/src/de/uni_koblenz/jgralab/greql2/evaluator/GreqlEvaluator.java
@@ -1,1209 +1,1209 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2010 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.evaluator;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.GraphIO;
import de.uni_koblenz.jgralab.GraphIOException;
import de.uni_koblenz.jgralab.ImplementationType;
import de.uni_koblenz.jgralab.JGraLab;
import de.uni_koblenz.jgralab.ProgressFunction;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.GraphIO.TGFilenameFilter;
import de.uni_koblenz.jgralab.codegenerator.CodeGeneratorConfiguration;
import de.uni_koblenz.jgralab.graphmarker.BooleanGraphMarker;
import de.uni_koblenz.jgralab.graphmarker.GraphMarker;
import de.uni_koblenz.jgralab.greql2.SerializableGreql2;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.LogCostModel;
import de.uni_koblenz.jgralab.greql2.evaluator.logging.EvaluationLogger;
import de.uni_koblenz.jgralab.greql2.evaluator.logging.Level2LogReader;
import de.uni_koblenz.jgralab.greql2.evaluator.logging.Level2Logger;
import de.uni_koblenz.jgralab.greql2.evaluator.logging.LoggingType;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexEvaluator;
import de.uni_koblenz.jgralab.greql2.exception.CostModelException;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.OptimizerException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueImpl;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueSet;
import de.uni_koblenz.jgralab.greql2.optimizer.DefaultOptimizer;
import de.uni_koblenz.jgralab.greql2.optimizer.Optimizer;
import de.uni_koblenz.jgralab.greql2.parser.ManualGreqlParser;
import de.uni_koblenz.jgralab.greql2.schema.Greql2;
import de.uni_koblenz.jgralab.impl.ProgressFunctionImpl;
import de.uni_koblenz.jgralab.schema.AggregationKind;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.GraphClass;
import de.uni_koblenz.jgralab.schema.Schema;
import de.uni_koblenz.jgralab.schema.VertexClass;
import de.uni_koblenz.jgralab.schema.impl.SchemaImpl;
import de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot;
/**
* This is the core class of the GReQL-2 Evaluator. It takes a GReQL-2 Query as
* String or Graph and a JGraLab-Datagraph and evaluates the Query on this
* graph. The result is a JValue-object, it can be accessed using the method
* <code>JValue getEvaluationResult()</code>.
*
* @author [email protected]
*
*/
public class GreqlEvaluator {
public static void main(String[] args) throws FileNotFoundException,
IOException, GraphIOException {
if ((args.length < 1) || (args.length > 2)) {
System.err
.println("Usage: java GreqlEvaluator <query> [<graphfile>]");
System.exit(1);
}
JGraLab.setLogLevel(Level.OFF);
String query = args[0];
Graph datagraph = null;
if (args.length == 2) {
datagraph = GraphIO.loadSchemaAndGraphFromFile(args[1],
CodeGeneratorConfiguration.WITHOUT_TRANSACTIONS,
new ProgressFunctionImpl());
}
GreqlEvaluator eval = new GreqlEvaluator(query, datagraph, null);
eval.startEvaluation();
JValue result = eval.getEvaluationResult();
System.out.println("Evaluation Result:");
System.out.println("==================");
if (result.isCollection()) {
for (JValue jv : result.toCollection()) {
System.out.println(jv);
}
} else if (result.isMap()) {
for (Entry<JValue, JValue> e : result.toJValueMap().entrySet()) {
System.out.println(e.getKey() + " --> " + e.getValue());
}
} else {
System.out.println(result);
}
}
/**
* toggles which expressions are added to the index. Only vertex- and
* edgeset expressions that need more than <code>indextimeBarrier</code> ms
* to calculate are added
*/
private static final long INDEX_TIME_BARRIER = 10;
/**
* Print the current value of each variable in a declaration layer during
* evaluation.
*/
public static boolean DEBUG_DECLARATION_ITERATIONS = false;
/**
* Print the text representation of the optimized query after optimization.
*/
public static boolean DEBUG_OPTIMIZATION = false;
/**
* toggles wether to use indexing for vertex sets or not
*/
public static final boolean VERTEX_INDEXING = true;
/**
* toggles the maximal size of the vertex index for each graph with respect
* to graph size. For instance, a value of 50 (fifty) here will allow the
* vertex index to need 5 (five) times more size than the vertex array in
* the graph. For a graph with 1.000.000 vertices, this array needs 4MB in
* the memory.
*/
public static final int VERTEX_INDEX_SIZE = 50;
/**
* stores the already optimized syntaxgraphs (query strings are the keys,
* here).
*/
protected static Map<String, SoftReference<List<SyntaxGraphEntry>>> optimizedGraphs;
public static synchronized void resetOptimizedSyntaxGraphs() {
if (optimizedGraphs == null) {
optimizedGraphs = new HashMap<String, SoftReference<List<SyntaxGraphEntry>>>();
} else {
optimizedGraphs.clear();
}
}
/**
* The directory where the GreqlEvaluator stores the optimized syntax graphs
*/
protected static File optimizedSyntaxGraphsDirectory = getTmpDirectory();
/**
* The directory where the {@link EvaluationLogger} stores and loads its
* logfiles from.
*/
protected static File evaluationLoggerDirectory = getTmpDirectory();
/**
* stores the graph indizes (maps graphId values to GraphIndizes)
*/
protected static Map<String, SoftReference<GraphIndex>> graphIndizes;
public static synchronized void resetGraphIndizes() {
if (graphIndizes == null) {
graphIndizes = new HashMap<String, SoftReference<GraphIndex>>();
} else {
graphIndizes.clear();
}
}
/**
* The GraphMarker that stores all vertex evaluators
*/
protected GraphMarker<VertexEvaluator> vertexEvalGraphMarker;
protected BooleanGraphMarker subgraphMarker;
/**
* @return the subgraphMarker
*/
public BooleanGraphMarker getSubgraphMarker() {
return subgraphMarker;
}
/**
* Sets the marker for evaluating only on marked elements. Also sets the
* datagraph to the given marker's graph.
*
* @param subgraphMarker
* the subgraphMarker to set
*/
public void setSubgraphMarker(BooleanGraphMarker subgraphMarker) {
this.subgraphMarker = subgraphMarker;
this.datagraph = subgraphMarker.getGraph();
}
/**
* The map of SimpleName to Type of types that is known in the evaluator by
* import statements in the greql query
*/
protected Map<String, AttributedElementClass> knownTypes = new HashMap<String, AttributedElementClass>(); // initial
/**
* returns the vertexEvalGraph marker that is used
*/
public final GraphMarker<VertexEvaluator> getVertexEvaluatorGraphMarker() {
return vertexEvalGraphMarker;
}
/**
* Creates the map of optimized syntaxgraphs as soon as the GreqlEvaluator
* gets loaded
*/
static {
resetOptimizedSyntaxGraphs();
resetGraphIndizes();
}
private static Logger logger = Logger.getLogger(GreqlEvaluator.class
.getName());
/**
* Gets a vertex index for a part of a query
*
* @param graph
* the graph to get an index for
* @param queryPart
* the query part to search for in the index structure
* @return a JValueSet with the result of that queryPart or null if the
* query part is not yet indexed
*/
public static synchronized JValueSet getVertexIndex(Graph graph,
String queryPart) {
SoftReference<GraphIndex> ref = graphIndizes.get(graph.getId());
if (ref == null) {
return null;
}
GraphIndex index = ref.get();
if (index == null) {
graphIndizes.remove(ref);
return null;
}
if (index.isValid(graph)) {
return index.getVertexSet(queryPart);
}
return null;
}
/**
* Adds the given vertex set as the result of the given queryPart to the
* index of the given graph
*/
public static synchronized void addVertexIndex(Graph graph,
String queryPart, JValueSet vertexSet) {
SoftReference<GraphIndex> ref = graphIndizes.get(graph.getId());
GraphIndex index = null;
if (ref != null) {
index = ref.get();
if (index == null) {
// remove the old reference
graphIndizes.remove(ref);
}
}
if (index == null) {
index = new GraphIndex(graph);
graphIndizes.put(graph.getId(),
new SoftReference<GraphIndex>(index));
}
index.addVertexSet(queryPart, vertexSet);
}
/**
* @return th time barrier after which unused indices were removed
*/
public long getIndexTimeBarrier() {
return INDEX_TIME_BARRIER;
}
/**
* adds a optimized graph to the list of syntaxgraphs. Sets the used flag to
*/
protected static synchronized void addOptimizedSyntaxGraph(
String queryString, SyntaxGraphEntry entry) {
SoftReference<List<SyntaxGraphEntry>> ref = optimizedGraphs
.get(queryString);
List<SyntaxGraphEntry> entryList = null;
if (ref != null) {
entryList = ref.get();
if (entryList == null) {
optimizedGraphs.remove(ref);
}
}
if (entryList == null) {
entryList = new ArrayList<SyntaxGraphEntry>();
}
if (!entryList.contains(entry)) {
entryList.add(entry);
}
optimizedGraphs.put(queryString,
new SoftReference<List<SyntaxGraphEntry>>(entryList));
}
/**
* gets an unlocked syntaxgraph out of the optimzedGraph map and locks it
*/
protected static synchronized SyntaxGraphEntry getOptimizedSyntaxGraph(
String queryString, Optimizer optimizer, CostModel costModel) {
SoftReference<List<SyntaxGraphEntry>> ref = optimizedGraphs
.get(queryString);
List<SyntaxGraphEntry> entryList = null;
if (ref != null) {
entryList = ref.get();
if (entryList == null) {
optimizedGraphs.remove(ref);
}
}
if (entryList == null) {
return null;
}
for (SyntaxGraphEntry entry : entryList) {
if (entry.getCostModel().isEquivalent(costModel)) {
Optimizer opt = entry.getOptimizer();
if (((opt != null) && opt.isEquivalent(optimizer))
|| ((opt == null) && (optimizer == null))) {
if (entry.lock()) {
return entry;
}
}
}
}
return null;
}
/**
* Load all optimized {@link SyntaxGraphEntry}s in
* optimizedSyntaxGraphsDirectory.
*
* @throws GraphIOException
* if the optimizedGraphsDirectory is not accessible.
* @see #setOptimizedSyntaxGraphsDirectory(File)
* @see #getOptimizedSyntaxGraphsDirectory()
*/
public static synchronized void loadOptimizedSyntaxGraphs()
throws GraphIOException {
if (!(optimizedSyntaxGraphsDirectory.exists()
&& optimizedSyntaxGraphsDirectory.canRead() && optimizedSyntaxGraphsDirectory
.canExecute())) {
throw new GraphIOException(
optimizedSyntaxGraphsDirectory.getPath()
+ " is not accessible. Does it really exist and are the permissions ok?");
}
for (File syntaxGraphFile : optimizedSyntaxGraphsDirectory
.listFiles(TGFilenameFilter.instance())) {
logger.info("Loading SyntaxGraphEntry \""
+ syntaxGraphFile.getPath() + "\".");
SyntaxGraphEntry entry;
try {
entry = new SyntaxGraphEntry(syntaxGraphFile);
addOptimizedSyntaxGraph(entry.getQueryText(), entry);
} catch (GraphIOException e) {
e.printStackTrace();
}
}
}
/**
* Save all {@link SyntaxGraphEntry}s in optimizedGraphs to
* optimizedSyntaxGraphDirectory.
*/
public static synchronized void saveOptimizedSyntaxGraphs() {
for (SoftReference<List<SyntaxGraphEntry>> ref : optimizedGraphs
.values()) {
List<SyntaxGraphEntry> entryList = ref.get();
if (entryList == null) {
continue;
}
for (SyntaxGraphEntry entry : entryList) {
try {
entry.saveToDirectory(optimizedSyntaxGraphsDirectory);
} catch (GraphIOException e) {
e.printStackTrace();
}
}
}
}
/**
* This attribute holds the query-string
*/
protected String queryString = null;
public void setQuery(String queryString) {
this.queryString = queryString;
reset();
}
public String getQuery() {
return queryString;
}
public void setQueryFile(File query) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(query));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
reader.close();
System.out.println("Query read from file:");
System.out.println(sb.toString());
setQuery(sb.toString());
}
/**
* Reset to before-start state, so that a new query can be evaluated.
*/
private void reset() {
queryGraph = null;
result = null;
started = false;
vertexEvalGraphMarker = null;
knownTypes.clear();
}
/**
* This attribute holds the query-graph
*/
private Greql2 queryGraph = null;
/**
* This attribute holds the entry of the optimizedSyntaxGraph map that is
* currently used
*/
protected SyntaxGraphEntry syntaxGraphEntry = null;
/**
* This is the optimizer who optimizes the greql2 syntaxgraph
*/
private Optimizer optimizer = null;
/**
* If set to <code>true</code>, then the query will be optimized before
* evaluation. Otherwise it will be evaluated without any optimizations.
*/
private boolean optimize = true;
/**
* If set to <code>true</code>, then a stored optimized syntaxgraph will be
* used if <code>optimize == true</code> and such a graph exists.
*/
private boolean useSavedOptimizedSyntaxGraph = true;
/**
* This attribute holds the datagraph
*/
protected Graph datagraph = null;
/**
* This attribute holds the result of the evaluation
*/
protected JValue result = null;
/**
* This attribute holds the EvaluationLogger, which logs the evaluation
*/
protected EvaluationLogger evaluationLogger = null;
/**
* The {@link LoggingType} that should be used. It defaults to
* {@link LoggingType#SCHEMA}.
*/
protected LoggingType evaluationLoggingType = LoggingType.SCHEMA;
/**
* This attribute holds the CostModel which estimates the evaluation costs
*/
protected CostModel costModel = null;
/**
* The progress function this evaluator uses, may be null
*/
protected ProgressFunction progressFunction = null;
/**
* holds the number of interpretetation steps that have been passed since
* the last call of the progress function
*/
protected long progressStepsPassed = 0;
/**
* the time the ovarall evaluation (parsing + optimization + evluation) took
* in milliseconds
*/
protected long overallEvaluationTime = -1;
/**
* The plain time needed for evaluation.
*/
protected long plainEvaluationTime = -1;
/**
* The time needed for optimization.
*/
protected long optimizationTime = -1;
/**
* The time needed for parsing the query.
*/
protected long parseTime = -1;
/**
* @return the time the ovarall evaluation (parsing + optimization +
* evluation) took in milliseconds
*/
public long getOverallEvaluationTime() {
return overallEvaluationTime;
}
/**
* This attribute is true if the evaluation has already been started, false
* otherwise
*/
protected boolean started = false;
/**
* Holds the variables that are defined via using, they are called bound or
* free variables
*/
protected Map<String, JValue> variableMap = null;
/**
* Holds the estimated needed for evaluation time in abstract units
*/
protected long estimatedInterpretationSteps = 0;
/**
* Holds the already passed time in abstract time units
*/
protected long passedInterpretationSteps = 0;
/**
* should be called by every vertex evaluator to indicate a progress. The
* given value should be the ownEvaluationCosts of that VertexEvaluator.
* Calls the progress()-Method of the progress function this evaluator uses
*/
public final void progress(long value) {
progressStepsPassed += value;
if (progressFunction != null) {
while (progressStepsPassed > progressFunction.getUpdateInterval()) {
progressFunction.progress(1);
progressStepsPassed -= progressFunction.getUpdateInterval();
}
}
passedInterpretationSteps += value;
}
/**
* returns the changes variableMap
*/
public Map<String, JValue> getVariables() {
return variableMap;
}
public JValue getVariable(String name) {
if ((variableMap != null) && variableMap.containsKey(name)) {
return variableMap.get(name);
}
return new JValueImpl();
}
public void setVariables(Map<String, JValue> varMap) {
variableMap = varMap;
}
public void setVariable(String varName, JValue value) {
if (variableMap == null) {
variableMap = new HashMap<String, JValue>();
}
variableMap.put(varName, value);
}
/**
* returns the result of the evaluation
*/
public JValue getEvaluationResult() {
return result;
}
/**
* returns the logging-component
*/
public final EvaluationLogger getEvaluationLogger() {
return evaluationLogger;
}
/**
* @return the tmp directory of that system. On Unix/Linux this is /tmp.
*/
private static File getTmpDirectory() {
File tmpFile = null, tmpDir = null;
try {
tmpFile = File.createTempFile("_tmp", "xyz");
tmpDir = tmpFile.getParentFile();
tmpFile.delete();
} catch (IOException e) {
e.printStackTrace();
tmpDir = new File("/tmp/");
}
return tmpDir;
}
/**
* creates the logging-component
*/
protected void createEvaluationLogger() {
if (evaluationLogger == null) {
try {
evaluationLogger = new Level2Logger(evaluationLoggerDirectory,
datagraph, evaluationLoggingType);
if (evaluationLogger.load()) {
logger.info("Successfully loaded logger file "
+ evaluationLogger.getLogfileName() + ".");
} else {
logger.info("Couldn't load logger file "
+ evaluationLogger.getLogfileName() + ".");
}
} catch (InterruptedException e) {
// TODO (heimdall) Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* sets the logger which is used to log the evlauation
*/
public void setEvaluationLogger(EvaluationLogger logger) {
this.evaluationLogger = logger;
}
/**
* returns the CostModel which is used to estimate the evaluation costs
*/
public CostModel getCostModel() {
return costModel;
}
/**
* sets the CostModel which is used to estimate the evaluation costs
*/
public void setCostModel(CostModel m) {
costModel = m;
}
/**
* returns the query syntaxgraph
*/
public Greql2 getSyntaxGraph() {
return queryGraph;
}
/**
* Creates a new GreqlEvaluator for the given Query and Datagraph
*
* @param query
* the string-representation of the query to evaluate
* @param datagraph
* the Datagraph on which the query gets evaluated
* @param variables
* a Map<String, JValue> of bound variables
* @param progressFunction
* the ProgressFunction which indicates the progress, for
* instance display a progress bar etc.
*/
public GreqlEvaluator(String query, Graph datagraph,
Map<String, JValue> variables, ProgressFunction progressFunction) {
this(datagraph, variables, progressFunction);
setQuery(query);
}
private GreqlEvaluator(Graph datagraph, Map<String, JValue> variables,
ProgressFunction progressFunction) {
if (datagraph == null) {
this.datagraph = createMinimalGraph();
} else {
this.datagraph = datagraph;
}
knownTypes = new HashMap<String, AttributedElementClass>();
this.variableMap = variables;
this.progressFunction = progressFunction;
}
public void addKnownType(AttributedElementClass knownType) {
knownTypes.put(knownType.getSimpleName(), knownType);
}
public AttributedElementClass getKnownType(String typeSimpleName) {
return knownTypes.get(typeSimpleName);
}
private Graph minimalGraph = null;
/**
* @return a minimal graph (no vertices and no edges) of a minimal schema.
*/
private Graph createMinimalGraph() {
if (minimalGraph == null) {
Schema minimalSchema = new SchemaImpl("MinimalSchema",
"de.uni_koblenz.jgralab.greqlminschema");
GraphClass gc = minimalSchema.createGraphClass("MinimalGraph");
VertexClass n = gc.createVertexClass("Node");
gc.createEdgeClass("Link", n, 0, Integer.MAX_VALUE, "",
AggregationKind.NONE, n, 0, Integer.MAX_VALUE, "",
AggregationKind.NONE);
minimalSchema
.compile(CodeGeneratorConfiguration.WITHOUT_TRANSACTIONS);
Method graphCreateMethod = minimalSchema
.getGraphCreateMethod(ImplementationType.STANDARD);
try {
minimalGraph = (Graph) (graphCreateMethod.invoke(null,
new Object[] { "test", 1, 1 }));
} catch (Exception e) {
e.printStackTrace();
}
}
return minimalGraph;
}
/**
* Creates a new GreqlEvaluator for the given Query and Datagraph
*
* @param query
* the string-representation of the query to evaluate
* @param datagraph
* the Datagraph on which the query gets evaluated
* @param variables
* a Map<String, JValue> of bound variables
*/
public GreqlEvaluator(String query, Graph datagraph,
Map<String, JValue> variables) {
this(query, datagraph, variables, null);
}
/**
* Creates an new GreqlEvaluator for the query in the given file and the
* given datagraph
*
* @param queryFile
* the name of the file whehre the query to evaluate is stored in
* @param datagraph
* the Datagraph on which the query gets evaluated
* @param variables
* a Map<String, JValue> of bound variables
* @param progressFunction
* the ProgressFunction which indicates the progress, for
* instance display a progress bar etc.
*/
public GreqlEvaluator(File queryFile, Graph datagraph,
Map<String, JValue> variables, ProgressFunction progressFunction)
throws FileNotFoundException, IOException {
this(datagraph, variables, progressFunction);
// Read query from file (afuhr)
this.setQueryFile(queryFile);
}
/**
* Creates an new GreqlEvaluator for the query in the given file and the
* given datagraph
*
* @param queryFile
* the name of the file whehre the query to evaluate is stored in
* @param datagraph
* the Datagraph on which the query gets evaluated
* @param variables
* a Map<String, JValue> of bound variables
*/
public GreqlEvaluator(File queryFile, Graph datagraph,
Map<String, JValue> variables) throws FileNotFoundException,
IOException {
this(queryFile, datagraph, variables, null);
}
/**
* returns the datagraph
*/
public Graph getDatagraph() {
return datagraph;
}
/**
* Parses the given query-string and creates the query-graph out of it
*/
protected boolean parseQuery(String query) throws EvaluateException {
long parseStartTime = System.currentTimeMillis();
ManualGreqlParser parser = new ManualGreqlParser(query);
try {
parser.parse();
} catch (Exception e) {
// e.printStackTrace();
throw new EvaluateException("Error parsing query \"" + queryString
+ "\".", e);
}
queryGraph = parser.getGraph();
parseTime = System.currentTimeMillis() - parseStartTime;
return true;
}
/**
* Creates the VertexEvaluator-Object at the vertices in the syntaxgraph
*/
public void createVertexEvaluators() throws EvaluateException {
vertexEvalGraphMarker = new GraphMarker<VertexEvaluator>(queryGraph);
Vertex currentVertex = queryGraph.getFirstVertex();
while (currentVertex != null) {
VertexEvaluator vertexEval = VertexEvaluator.createVertexEvaluator(
currentVertex, this);
if (vertexEval != null) {
vertexEvalGraphMarker.mark(currentVertex, vertexEval);
}
currentVertex = currentVertex.getNextVertex();
}
}
/**
* clears the tempresults that are stored in the VertexEvaluators-Objects at
* the syntaxgraph nodes
*
* @param optimizer
*/
private void resetVertexEvaluators() {
Vertex currentVertex = queryGraph.getFirstVertex();
while (currentVertex != null) {
VertexEvaluator vertexEval = vertexEvalGraphMarker
.getMark(currentVertex);
if (vertexEval != null) {
vertexEval.resetToInitialState();
}
currentVertex = currentVertex.getNextVertex();
}
}
/**
* Transforms the textual query representation into an optimized
* syntaxgraph, adds the VertexEvaluator object to the vertices of that
* graph and stores this as attribute queryGraph.
*/
protected void createOptimizedSyntaxGraph() throws EvaluateException,
OptimizerException {
long optimizerStartTime = System.currentTimeMillis();
if (optimizer == null) {
optimizer = new DefaultOptimizer();
}
if (useSavedOptimizedSyntaxGraph
&& optimizedGraphs.containsKey(queryString)) {
syntaxGraphEntry = getOptimizedSyntaxGraph(queryString, optimizer,
costModel);
if (syntaxGraphEntry != null) {
queryGraph = syntaxGraphEntry.getSyntaxGraph();
createVertexEvaluators();
costModel.setGreqlEvaluator(this);
logger.info("Using stored optimized syntax graph.");
return;
}
}
// No optimized graph for this query, optimizer and costmodel was found.
if (queryGraph == null) {
parseQuery(queryString);
}
if (DEBUG_OPTIMIZATION) {
System.out
.println("#########################################################");
System.out
.println("################## Unoptimized Query ####################");
System.out
.println("#########################################################");
String name = "__greql-query.";
try {
GraphIO.saveGraphToFile(name + "tg", queryGraph,
new ProgressFunctionImpl());
Tg2Dot.printGraphAsDot(queryGraph, true, name + "dot");
} catch (GraphIOException e) {
e.printStackTrace();
}
System.out.println("Saved query graph to " + name + "tg/dot.");
System.out
.println("#########################################################");
}
createVertexEvaluators();
optimizer.optimize(this, queryGraph);
syntaxGraphEntry = new SyntaxGraphEntry(queryString, queryGraph,
optimizer, costModel, true);
addOptimizedSyntaxGraph(queryString, syntaxGraphEntry);
createVertexEvaluators();
optimizationTime = System.currentTimeMillis() - optimizerStartTime;
}
/**
* same as startEvaluation(false), provides for convenience
*
* @return true if the evaluation succeeds, false otherwise
* @throws EvaluateException
*/
public boolean startEvaluation() throws EvaluateException,
OptimizerException {
return startEvaluation(false);
}
/**
* Starts the evaluation. If the query is a store-query, modifies the bound
* variables
*
* @param log
* if set to true, the evaluation will be logged. If no logger
* was set before, the Level2Logger is used
* @return true on success, false otherwise
* @throws EvaluateException
* if something gets wrong during evaluation
*/
public boolean startEvaluation(boolean log) throws EvaluateException,
OptimizerException {
if (started) {
return (result != null);
}
started = true;
parseTime = 0;
optimizationTime = 0;
plainEvaluationTime = 0;
overallEvaluationTime = 0;
long startTime = System.currentTimeMillis();
if (datagraph == null) {
this.datagraph = createMinimalGraph();
}
if (log) {
createEvaluationLogger();
}
// Initialize the CostModel if there's none
if (costModel == null) {
// costModel = new DefaultCostModel(vertexEvalGraphMarker);
Level2LogReader logReader;
if (evaluationLogger == null) {
evaluationLoggerDirectory = getTmpDirectory();
logReader = new Level2LogReader(evaluationLoggerDirectory,
datagraph);
} else {
logReader = new Level2LogReader((Level2Logger) evaluationLogger);
}
try {
costModel = new LogCostModel(logReader, 0.7f, this);
} catch (CostModelException e) {
e.printStackTrace();
}
}
if (optimize) {
createOptimizedSyntaxGraph();
if (DEBUG_OPTIMIZATION) {
System.out
.println("#########################################################");
System.out
.println("################### Optimized Query #####################");
System.out
.println("#########################################################");
if (queryGraph instanceof SerializableGreql2) {
System.out.println(((SerializableGreql2) queryGraph)
.serialize());
} else {
System.out.println("Couldn't serialize Greql2 graph...");
}
String name = "__optimized-greql-query.";
try {
GraphIO.saveGraphToFile(name + "tg", queryGraph,
new ProgressFunctionImpl());
Tg2Dot.printGraphAsDot(queryGraph, true, name + "dot");
} catch (GraphIOException e) {
e.printStackTrace();
}
System.out.println("Saved optimized query graph to " + name
+ "tg/dot.");
System.out
.println("#########################################################");
}
} else {
parseQuery(queryString);
createVertexEvaluators();
}
if (queryGraph == null) {
throw new RuntimeException(
"Empty query graph supplied, no evaluation possible");
}
if (queryGraph.getVCount() <= 1) {
// Graph contains only root vertex
result = new JValueImpl();
return true;
}
// Calculate the evaluation costs
VertexEvaluator greql2ExpEval = vertexEvalGraphMarker
.getMark(queryGraph.getFirstGreql2Expression());
if (progressFunction != null) {
estimatedInterpretationSteps = greql2ExpEval
.getInitialSubtreeEvaluationCosts(new GraphSize(datagraph));
progressFunction.init(estimatedInterpretationSteps);
}
long plainEvaluationStartTime = System.currentTimeMillis();
result = vertexEvalGraphMarker.getMark(
- queryGraph.getFirstGreql2Expression()).getResult(null);
+ queryGraph.getFirstGreql2Expression()).getResult(subgraphMarker);
// last, remove all added tempAttributes, currently, this are only
// subgraphAttributes
if (progressFunction != null) {
progressFunction.finished();
}
plainEvaluationTime = System.currentTimeMillis()
- plainEvaluationStartTime;
if (evaluationLogger != null) {
try {
if (evaluationLogger.store()) {
logger.info("Successfully stored logfile to "
+ evaluationLogger.getLogfileName() + ".");
} else {
logger.warning("Couldn't store logfile to "
+ evaluationLogger.getLogfileName() + ".");
}
} catch (IOException ex) {
throw new EvaluateException("Error writing log to file: "
+ evaluationLogger.getLogfileName(), ex);
}
}
resetVertexEvaluators();
if (syntaxGraphEntry != null) {
syntaxGraphEntry.release();
}
overallEvaluationTime = System.currentTimeMillis() - startTime;
started = false;
return true;
}
/**
* Sets the optimizer to optimize the syntaxgraph this evaluator evaluates
*
* @param optimizer
* the optimizer to use
*/
public void setOptimizer(Optimizer optimizer) {
this.optimizer = optimizer;
}
/**
* Sets the optimizer to optimize the syntaxgraph this evaluator evaluates
*/
public Optimizer getOptimizer() {
return optimizer;
}
public void setDatagraph(Graph datagraph) {
this.datagraph = datagraph;
}
/**
* @return <code>true</code> if the query will be optimized before
* evaluation, <code>false</code> otherwise.
*/
public boolean isOptimize() {
return optimize;
}
/**
* @param optimize
* If <code>true</code>, then the query will be optimized before
* evaluation. If <code>false</code> it will be evaluated without
* any optimizations.
*/
public void setOptimize(boolean optimize) {
this.optimize = optimize;
}
/**
* @return the time needed for optimizing the query or -1 if no optimization
* was done.
*/
public long getOptimizationTime() {
return optimizationTime;
}
/**
* @return the time needed for parsing the query.
*/
public long getParseTime() {
return parseTime;
}
public void printEvaluationTimes() {
logger.info("Overall evaluation took "
+ overallEvaluationTime
/ 1000d
+ " seconds.\n"
+ " --> parsing time : "
+ parseTime
/ 1000d
+ "\n --> optimization time : "
+ optimizationTime
/ 1000d
+ "\n --> plain evaluation time: "
+ plainEvaluationTime
/ 1000d
+ "\n"
+ (progressFunction != null ? "Estimated evaluation costs: "
+ estimatedInterpretationSteps : ""));
}
public static File getOptimizedSyntaxGraphsDirectory() {
return optimizedSyntaxGraphsDirectory;
}
public static void setOptimizedSyntaxGraphsDirectory(
File optimizedSyntaxGraphsDirectory) {
GreqlEvaluator.optimizedSyntaxGraphsDirectory = optimizedSyntaxGraphsDirectory;
}
/**
* @return The directory where the {@link EvaluationLogger} stores and loads
* its logfiles.
*/
public static File getEvaluationLoggerDirectory() {
return evaluationLoggerDirectory;
}
/**
* @param loggerDirectory
* The directory where the {@link EvaluationLogger} stores and
* loads its logfiles.
*/
public static void setEvaluationLoggerDirectory(File loggerDirectory) {
GreqlEvaluator.evaluationLoggerDirectory = loggerDirectory;
}
public LoggingType getEvaluationLoggingType() {
return evaluationLoggingType;
}
public void setEvaluationLoggingType(LoggingType loggerLoggingType) {
this.evaluationLoggingType = loggerLoggingType;
}
public boolean isUseSavedOptimizedSyntaxGraph() {
return useSavedOptimizedSyntaxGraph;
}
public void setUseSavedOptimizedSyntaxGraph(
boolean useSavedOptimizedSyntaxGraph) {
this.useSavedOptimizedSyntaxGraph = useSavedOptimizedSyntaxGraph;
}
}
| true | true |
public boolean startEvaluation(boolean log) throws EvaluateException,
OptimizerException {
if (started) {
return (result != null);
}
started = true;
parseTime = 0;
optimizationTime = 0;
plainEvaluationTime = 0;
overallEvaluationTime = 0;
long startTime = System.currentTimeMillis();
if (datagraph == null) {
this.datagraph = createMinimalGraph();
}
if (log) {
createEvaluationLogger();
}
// Initialize the CostModel if there's none
if (costModel == null) {
// costModel = new DefaultCostModel(vertexEvalGraphMarker);
Level2LogReader logReader;
if (evaluationLogger == null) {
evaluationLoggerDirectory = getTmpDirectory();
logReader = new Level2LogReader(evaluationLoggerDirectory,
datagraph);
} else {
logReader = new Level2LogReader((Level2Logger) evaluationLogger);
}
try {
costModel = new LogCostModel(logReader, 0.7f, this);
} catch (CostModelException e) {
e.printStackTrace();
}
}
if (optimize) {
createOptimizedSyntaxGraph();
if (DEBUG_OPTIMIZATION) {
System.out
.println("#########################################################");
System.out
.println("################### Optimized Query #####################");
System.out
.println("#########################################################");
if (queryGraph instanceof SerializableGreql2) {
System.out.println(((SerializableGreql2) queryGraph)
.serialize());
} else {
System.out.println("Couldn't serialize Greql2 graph...");
}
String name = "__optimized-greql-query.";
try {
GraphIO.saveGraphToFile(name + "tg", queryGraph,
new ProgressFunctionImpl());
Tg2Dot.printGraphAsDot(queryGraph, true, name + "dot");
} catch (GraphIOException e) {
e.printStackTrace();
}
System.out.println("Saved optimized query graph to " + name
+ "tg/dot.");
System.out
.println("#########################################################");
}
} else {
parseQuery(queryString);
createVertexEvaluators();
}
if (queryGraph == null) {
throw new RuntimeException(
"Empty query graph supplied, no evaluation possible");
}
if (queryGraph.getVCount() <= 1) {
// Graph contains only root vertex
result = new JValueImpl();
return true;
}
// Calculate the evaluation costs
VertexEvaluator greql2ExpEval = vertexEvalGraphMarker
.getMark(queryGraph.getFirstGreql2Expression());
if (progressFunction != null) {
estimatedInterpretationSteps = greql2ExpEval
.getInitialSubtreeEvaluationCosts(new GraphSize(datagraph));
progressFunction.init(estimatedInterpretationSteps);
}
long plainEvaluationStartTime = System.currentTimeMillis();
result = vertexEvalGraphMarker.getMark(
queryGraph.getFirstGreql2Expression()).getResult(null);
// last, remove all added tempAttributes, currently, this are only
// subgraphAttributes
if (progressFunction != null) {
progressFunction.finished();
}
plainEvaluationTime = System.currentTimeMillis()
- plainEvaluationStartTime;
if (evaluationLogger != null) {
try {
if (evaluationLogger.store()) {
logger.info("Successfully stored logfile to "
+ evaluationLogger.getLogfileName() + ".");
} else {
logger.warning("Couldn't store logfile to "
+ evaluationLogger.getLogfileName() + ".");
}
} catch (IOException ex) {
throw new EvaluateException("Error writing log to file: "
+ evaluationLogger.getLogfileName(), ex);
}
}
resetVertexEvaluators();
if (syntaxGraphEntry != null) {
syntaxGraphEntry.release();
}
overallEvaluationTime = System.currentTimeMillis() - startTime;
started = false;
return true;
}
|
public boolean startEvaluation(boolean log) throws EvaluateException,
OptimizerException {
if (started) {
return (result != null);
}
started = true;
parseTime = 0;
optimizationTime = 0;
plainEvaluationTime = 0;
overallEvaluationTime = 0;
long startTime = System.currentTimeMillis();
if (datagraph == null) {
this.datagraph = createMinimalGraph();
}
if (log) {
createEvaluationLogger();
}
// Initialize the CostModel if there's none
if (costModel == null) {
// costModel = new DefaultCostModel(vertexEvalGraphMarker);
Level2LogReader logReader;
if (evaluationLogger == null) {
evaluationLoggerDirectory = getTmpDirectory();
logReader = new Level2LogReader(evaluationLoggerDirectory,
datagraph);
} else {
logReader = new Level2LogReader((Level2Logger) evaluationLogger);
}
try {
costModel = new LogCostModel(logReader, 0.7f, this);
} catch (CostModelException e) {
e.printStackTrace();
}
}
if (optimize) {
createOptimizedSyntaxGraph();
if (DEBUG_OPTIMIZATION) {
System.out
.println("#########################################################");
System.out
.println("################### Optimized Query #####################");
System.out
.println("#########################################################");
if (queryGraph instanceof SerializableGreql2) {
System.out.println(((SerializableGreql2) queryGraph)
.serialize());
} else {
System.out.println("Couldn't serialize Greql2 graph...");
}
String name = "__optimized-greql-query.";
try {
GraphIO.saveGraphToFile(name + "tg", queryGraph,
new ProgressFunctionImpl());
Tg2Dot.printGraphAsDot(queryGraph, true, name + "dot");
} catch (GraphIOException e) {
e.printStackTrace();
}
System.out.println("Saved optimized query graph to " + name
+ "tg/dot.");
System.out
.println("#########################################################");
}
} else {
parseQuery(queryString);
createVertexEvaluators();
}
if (queryGraph == null) {
throw new RuntimeException(
"Empty query graph supplied, no evaluation possible");
}
if (queryGraph.getVCount() <= 1) {
// Graph contains only root vertex
result = new JValueImpl();
return true;
}
// Calculate the evaluation costs
VertexEvaluator greql2ExpEval = vertexEvalGraphMarker
.getMark(queryGraph.getFirstGreql2Expression());
if (progressFunction != null) {
estimatedInterpretationSteps = greql2ExpEval
.getInitialSubtreeEvaluationCosts(new GraphSize(datagraph));
progressFunction.init(estimatedInterpretationSteps);
}
long plainEvaluationStartTime = System.currentTimeMillis();
result = vertexEvalGraphMarker.getMark(
queryGraph.getFirstGreql2Expression()).getResult(subgraphMarker);
// last, remove all added tempAttributes, currently, this are only
// subgraphAttributes
if (progressFunction != null) {
progressFunction.finished();
}
plainEvaluationTime = System.currentTimeMillis()
- plainEvaluationStartTime;
if (evaluationLogger != null) {
try {
if (evaluationLogger.store()) {
logger.info("Successfully stored logfile to "
+ evaluationLogger.getLogfileName() + ".");
} else {
logger.warning("Couldn't store logfile to "
+ evaluationLogger.getLogfileName() + ".");
}
} catch (IOException ex) {
throw new EvaluateException("Error writing log to file: "
+ evaluationLogger.getLogfileName(), ex);
}
}
resetVertexEvaluators();
if (syntaxGraphEntry != null) {
syntaxGraphEntry.release();
}
overallEvaluationTime = System.currentTimeMillis() - startTime;
started = false;
return true;
}
|
diff --git a/src/som/primitives/ObjectPrimitives.java b/src/som/primitives/ObjectPrimitives.java
index 885d526..162e3bf 100644
--- a/src/som/primitives/ObjectPrimitives.java
+++ b/src/som/primitives/ObjectPrimitives.java
@@ -1,118 +1,118 @@
/**
* Copyright (c) 2009 Michael Haupt, [email protected]
* Software Architecture Group, Hasso Plattner Institute, Potsdam, Germany
* http://www.hpi.uni-potsdam.de/swa/
*
* 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.
*/
package som.primitives;
import com.oracle.truffle.api.frame.VirtualFrame;
import som.vm.Universe;
import som.vmobjects.Array;
import som.vmobjects.Class;
import som.vmobjects.Integer;
import som.vmobjects.Invokable;
import som.vmobjects.Object;
import som.vmobjects.Primitive;
import som.vmobjects.Symbol;
public class ObjectPrimitives extends Primitives {
public ObjectPrimitives(final Universe universe) {
super(universe);
}
public void installPrimitives() {
installInstancePrimitive(new Primitive("==", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
if (self == args[0])
return universe.trueObject;
else
return universe.falseObject;
}
});
installInstancePrimitive(new Primitive("hashcode", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
return universe.newInteger(self.hashCode());
}
});
installInstancePrimitive(new Primitive("objectSize", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
int size = self.getNumberOfFields();
if (self instanceof Array)
size += ((Array) self).getNumberOfIndexableFields();
return universe.newInteger(size);
}
});
installInstancePrimitive(new Primitive("perform:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:inSuperclass:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Class clazz = (Class) args[1];
Invokable invokable = clazz.lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:withArguments:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Array argsArr = (Array) args[1];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
- return invokable.invoke(frame, self, new Object[] { argsArr });
+ return invokable.invoke(frame, self, argsArr.indexableFields);
}
});
installInstancePrimitive(new Primitive("instVarAt:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
return self.getField(idx.getEmbeddedInteger() - 1);
}
});
installInstancePrimitive(new Primitive("instVarAt:put:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
Object val = args[1];
self.setField(idx.getEmbeddedInteger() - 1, val);
return val;
}
});
}
}
| true | true |
public void installPrimitives() {
installInstancePrimitive(new Primitive("==", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
if (self == args[0])
return universe.trueObject;
else
return universe.falseObject;
}
});
installInstancePrimitive(new Primitive("hashcode", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
return universe.newInteger(self.hashCode());
}
});
installInstancePrimitive(new Primitive("objectSize", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
int size = self.getNumberOfFields();
if (self instanceof Array)
size += ((Array) self).getNumberOfIndexableFields();
return universe.newInteger(size);
}
});
installInstancePrimitive(new Primitive("perform:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:inSuperclass:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Class clazz = (Class) args[1];
Invokable invokable = clazz.lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:withArguments:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Array argsArr = (Array) args[1];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
return invokable.invoke(frame, self, new Object[] { argsArr });
}
});
installInstancePrimitive(new Primitive("instVarAt:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
return self.getField(idx.getEmbeddedInteger() - 1);
}
});
installInstancePrimitive(new Primitive("instVarAt:put:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
Object val = args[1];
self.setField(idx.getEmbeddedInteger() - 1, val);
return val;
}
});
}
|
public void installPrimitives() {
installInstancePrimitive(new Primitive("==", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
if (self == args[0])
return universe.trueObject;
else
return universe.falseObject;
}
});
installInstancePrimitive(new Primitive("hashcode", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
return universe.newInteger(self.hashCode());
}
});
installInstancePrimitive(new Primitive("objectSize", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
int size = self.getNumberOfFields();
if (self instanceof Array)
size += ((Array) self).getNumberOfIndexableFields();
return universe.newInteger(size);
}
});
installInstancePrimitive(new Primitive("perform:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:inSuperclass:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Class clazz = (Class) args[1];
Invokable invokable = clazz.lookupInvokable(selector);
return invokable.invoke(frame, self, null);
}
});
installInstancePrimitive(new Primitive("perform:withArguments:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Symbol selector = (Symbol) args[0];
Array argsArr = (Array) args[1];
Invokable invokable = self.getSOMClass().lookupInvokable(selector);
return invokable.invoke(frame, self, argsArr.indexableFields);
}
});
installInstancePrimitive(new Primitive("instVarAt:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
return self.getField(idx.getEmbeddedInteger() - 1);
}
});
installInstancePrimitive(new Primitive("instVarAt:put:", universe) {
public Object invoke(final VirtualFrame frame, final Object self, final Object[] args) {
Integer idx = (Integer) args[0];
Object val = args[1];
self.setField(idx.getEmbeddedInteger() - 1, val);
return val;
}
});
}
|
diff --git a/src/me/cnaude/plugin/TeleportRequest/TRCommands.java b/src/me/cnaude/plugin/TeleportRequest/TRCommands.java
index c8f1a66..f1bce5f 100644
--- a/src/me/cnaude/plugin/TeleportRequest/TRCommands.java
+++ b/src/me/cnaude/plugin/TeleportRequest/TRCommands.java
@@ -1,85 +1,74 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package me.cnaude.plugin.TeleportRequest;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author cnaude
*/
public class TRCommands implements CommandExecutor {
private final TR plugin;
public TRCommands(TR instance) {
this.plugin = instance;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
+ if (player.isDead()) {
+ sender.sendMessage(ChatColor.RED + "You are dead!!");
+ return true;
+ }
if (!sender.hasPermission("teleportrequest.rtp")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (args.length == 1) {
String arg = args[0];
if (arg.equalsIgnoreCase("yes")) {
// accept request
plugin.acceptRequest(player, "all");
return true;
}
if (arg.equalsIgnoreCase("no")) {
// deny request
plugin.denyRequest(player, "all");
return true;
}
Player dstPlayer = Bukkit.getPlayerExact(arg);
if (dstPlayer == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.AQUA
+ arg + ChatColor.RED + " is not online!");
return true;
} else if (player.equals(dstPlayer)) {
sender.sendMessage(ChatColor.RED + "Why would you do that!? ");
return true;
} else {
// send tp request to dstPlayer from player
plugin.sendRequest(player, dstPlayer);
return true;
}
- } else if (args.length >= 2) {
- String arg = args[0];
- for (int x = 1; x < args.length; x++) {
- String pName = args[x];
- if (arg.equalsIgnoreCase("yes")) {
- // accept request
- plugin.acceptRequest(player, pName);
- } else if (arg.equalsIgnoreCase("no")) {
- // deny request
- plugin.denyRequest(player, pName);
- } else {
- return false;
- }
- }
- return true;
} else {
return false;
}
} else {
if (sender != null) {
sender.sendMessage("Only a player can send teleport requests.");
}
return true;
}
}
}
| false | true |
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
if (!sender.hasPermission("teleportrequest.rtp")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (args.length == 1) {
String arg = args[0];
if (arg.equalsIgnoreCase("yes")) {
// accept request
plugin.acceptRequest(player, "all");
return true;
}
if (arg.equalsIgnoreCase("no")) {
// deny request
plugin.denyRequest(player, "all");
return true;
}
Player dstPlayer = Bukkit.getPlayerExact(arg);
if (dstPlayer == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.AQUA
+ arg + ChatColor.RED + " is not online!");
return true;
} else if (player.equals(dstPlayer)) {
sender.sendMessage(ChatColor.RED + "Why would you do that!? ");
return true;
} else {
// send tp request to dstPlayer from player
plugin.sendRequest(player, dstPlayer);
return true;
}
} else if (args.length >= 2) {
String arg = args[0];
for (int x = 1; x < args.length; x++) {
String pName = args[x];
if (arg.equalsIgnoreCase("yes")) {
// accept request
plugin.acceptRequest(player, pName);
} else if (arg.equalsIgnoreCase("no")) {
// deny request
plugin.denyRequest(player, pName);
} else {
return false;
}
}
return true;
} else {
return false;
}
} else {
if (sender != null) {
sender.sendMessage("Only a player can send teleport requests.");
}
return true;
}
}
|
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
if (player.isDead()) {
sender.sendMessage(ChatColor.RED + "You are dead!!");
return true;
}
if (!sender.hasPermission("teleportrequest.rtp")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (args.length == 1) {
String arg = args[0];
if (arg.equalsIgnoreCase("yes")) {
// accept request
plugin.acceptRequest(player, "all");
return true;
}
if (arg.equalsIgnoreCase("no")) {
// deny request
plugin.denyRequest(player, "all");
return true;
}
Player dstPlayer = Bukkit.getPlayerExact(arg);
if (dstPlayer == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.AQUA
+ arg + ChatColor.RED + " is not online!");
return true;
} else if (player.equals(dstPlayer)) {
sender.sendMessage(ChatColor.RED + "Why would you do that!? ");
return true;
} else {
// send tp request to dstPlayer from player
plugin.sendRequest(player, dstPlayer);
return true;
}
} else {
return false;
}
} else {
if (sender != null) {
sender.sendMessage("Only a player can send teleport requests.");
}
return true;
}
}
|
diff --git a/plugins/org.eclipse.emf.compare.match/src/org/eclipse/emf/compare/match/service/MatchEngineRegistry.java b/plugins/org.eclipse.emf.compare.match/src/org/eclipse/emf/compare/match/service/MatchEngineRegistry.java
index 342fe71d4..387f88d4b 100644
--- a/plugins/org.eclipse.emf.compare.match/src/org/eclipse/emf/compare/match/service/MatchEngineRegistry.java
+++ b/plugins/org.eclipse.emf.compare.match/src/org/eclipse/emf/compare/match/service/MatchEngineRegistry.java
@@ -1,186 +1,190 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 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.emf.compare.match.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.compare.match.EMFCompareMatchMessages;
import org.eclipse.emf.compare.match.engine.GenericMatchEngine;
import org.eclipse.emf.compare.match.engine.IMatchEngine;
/* (non-javadoc) we make use of the ordering of the engines, do not change Map and List implementations. */
/**
* This registry will be initialized with all the match engines that could be parsed from the extension points
* if Eclipse is running according to {@link EMFPlugin#IS_ECLIPSE_RUNNING}, else it will contain only the two
* generic ones. Clients can add their own match engines in the registry for standalone usage.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
public final class MatchEngineRegistry extends HashMap<String, List<Object>> {
/** Singleton instance of the registry. */
public static final MatchEngineRegistry INSTANCE = new MatchEngineRegistry();
/** Wild card for file extensions. */
private static final String ALL_EXTENSIONS = "*"; //$NON-NLS-1$
/** Name of the extension point to parse for engines. */
private static final String MATCH_ENGINES_EXTENSION_POINT = "org.eclipse.emf.compare.match.engine"; //$NON-NLS-1$
/** Serial version UID is used when deserializing Objects. */
private static final long serialVersionUID = 2237008034183610765L;
/** Externalized here to avoid too many distinct usages. */
private static final String TAG_ENGINE = "matchengine"; //$NON-NLS-1$
/**
* As this is a singleton, hide the default constructor. Access the instance through the field
* {@link #INSTANCE}.
*/
private MatchEngineRegistry() {
if (EMFPlugin.IS_ECLIPSE_RUNNING) {
parseExtensionMetadata();
} else {
// Add both generic engines
putValue(ALL_EXTENSIONS, new GenericMatchEngine());
}
}
/**
* This will return the list of engines available for a given fileExtension. Engines must have been
* registered through an extension point for this to return anything else than an empty list. Note that
* engines registered against {@value #ALL_EXTENSIONS} will always be returned at the end of this list.
*
* @param fileExtension
* Extension of the file we seek the matching engines for.
* @return The list of available engines.
*/
public List<MatchEngineDescriptor> getDescriptors(String fileExtension) {
final List<Object> specific = get(fileExtension);
final List<Object> candidates = new ArrayList<Object>(get(ALL_EXTENSIONS));
if (specific != null) {
candidates.addAll(0, specific);
}
final List<MatchEngineDescriptor> engines = new ArrayList<MatchEngineDescriptor>(candidates.size());
for (final Object value : candidates) {
if (value instanceof MatchEngineDescriptor) {
engines.add((MatchEngineDescriptor)value);
}
}
return engines;
}
/**
* Returns the highest priority {@link IMatchEngine} registered against the given file extension. Specific
* engines will always come before generic ones regardless of their priority. If engines have been
* manually added to the list, the latest added will be returned.
*
* @param fileExtension
* The extension of the file we need a {@link IMatchEngine} for.
* @return The best {@link IMatchEngine} for the given file extension.
*/
public IMatchEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
- final int highestPriority = -1;
+ int highestPriority = -1;
IMatchEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
+ highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
+ break;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
+ highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
+ break;
}
}
}
return highest;
}
/**
* Adds the given value in the list of engines known for the given extension.
*
* @param key
* The file extension we wish to add an engine for.
* @param value
* Engine to be added.
*/
public void putValue(String key, Object value) {
if (value instanceof IMatchEngine || value instanceof MatchEngineDescriptor) {
List<Object> values = get(key);
if (values != null) {
values.add(value);
} else {
values = new ArrayList<Object>();
values.add(value);
super.put(key, values);
}
} else
throw new IllegalArgumentException(EMFCompareMatchMessages.getString(
"MatchEngineRegistry.IllegalEngine", value.getClass().getName())); //$NON-NLS-1$
}
/**
* This will parse the given {@link IConfigurationElement configuration element} and return a descriptor
* for it if it describes and engine.
*
* @param configElement
* Configuration element to parse.
* @return {@link MatchEngineDescriptor} wrapped around <code>configElement</code> if it describes an
* engine, <code>null</code> otherwise.
*/
private MatchEngineDescriptor parseEngine(IConfigurationElement configElement) {
if (!configElement.getName().equals(TAG_ENGINE))
return null;
final MatchEngineDescriptor desc = new MatchEngineDescriptor(configElement);
return desc;
}
/**
* This will parse the currently running platform for extensions and store all the match engines that can
* be found.
*/
private void parseExtensionMetadata() {
final IExtension[] extensions = Platform.getExtensionRegistry().getExtensionPoint(
MATCH_ENGINES_EXTENSION_POINT).getExtensions();
for (int i = 0; i < extensions.length; i++) {
final IConfigurationElement[] configElements = extensions[i].getConfigurationElements();
for (int j = 0; j < configElements.length; j++) {
final MatchEngineDescriptor desc = parseEngine(configElements[j]);
final String[] fileExtensions = desc.getFileExtension().split(","); //$NON-NLS-1$
for (final String ext : fileExtensions) {
putValue(ext, desc);
}
}
}
}
}
| false | true |
public IMatchEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
final int highestPriority = -1;
IMatchEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
}
}
}
return highest;
}
|
public IMatchEngine getHighestEngine(String fileExtension) {
final List<Object> engines = get(fileExtension);
int highestPriority = -1;
IMatchEngine highest = null;
if (engines != null) {
for (final Object engine : engines) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
break;
}
}
}
// couldn't find a specific engine, search through the generic ones
if (highest == null) {
for (final Object engine : get(ALL_EXTENSIONS)) {
if (engine instanceof MatchEngineDescriptor) {
final MatchEngineDescriptor desc = (MatchEngineDescriptor)engine;
if (desc.getPriorityValue() > highestPriority) {
highest = desc.getEngineInstance();
highestPriority = desc.getPriorityValue();
}
} else if (engine instanceof IMatchEngine) {
highest = (IMatchEngine)engine;
break;
}
}
}
return highest;
}
|
diff --git a/src/uk/org/ponder/rsac/BeanDefUtil.java b/src/uk/org/ponder/rsac/BeanDefUtil.java
index ee457ac..63b6b3b 100644
--- a/src/uk/org/ponder/rsac/BeanDefUtil.java
+++ b/src/uk/org/ponder/rsac/BeanDefUtil.java
@@ -1,263 +1,265 @@
/*
* Created on 04-Feb-2006
*/
// Some code in this file is subject to the ASF licence, terms follow:
/*
* Copyright 2002-2004 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.
*/
// Under term 4c) of the licence, attribution details taken from the original
// source (AbstractBeanFactory.java) are as follows:
// * @author Rod Johnson
// * @author Juergen Hoeller
// * @since 15 April 2001
package uk.org.ponder.rsac;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.ChildBeanDefinition;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.RootBeanDefinition;
import uk.org.ponder.conversion.StringArrayParser;
import uk.org.ponder.reflect.ClassGetter;
import uk.org.ponder.saxalizer.AccessMethod;
import uk.org.ponder.saxalizer.MethodAnalyser;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.util.Logger;
public class BeanDefUtil {
// We would *love* to use more of the AbstractBeanFactory code from which
// this is taken but i) this is coupled to the inefficient (not to say broken)
// PropertyEditor infastructure, and ii) has reliance on synchronized maps
// which we MUST dispense with in request scope.
// NB an IMPORTANT CHANGE from the ABF version is change of references to
// AbstractBeanFactory into ConfigurableListableBeanFactory. This considerably
// weakens the type generality of our system but is unavoidable since
// CLBF is the LOWEST level at which a getBeanDefinition() method is visible
// to us, since we are no longer members of ABF. Since in practice we plan
// to implement all RSAC using GenericApplicationContexts, this is not a
// problem, and anyone who wants to inherit bean definitions FROM application
// scope INTO request scope is i) deranged and ii) gets everything they
// deserve.
static RootBeanDefinition getMergedBeanDefinition(
ConfigurableListableBeanFactory factory, String beanName,
boolean includingAncestors) throws BeansException {
try {
return getMergedBeanDefinition(factory, beanName, factory
.getBeanDefinition(beanName));
}
catch (NoSuchBeanDefinitionException ex) {
if (includingAncestors
&& factory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
return getMergedBeanDefinition(factory, beanName, true);
}
else {
throw ex;
}
}
}
static RootBeanDefinition getMergedBeanDefinition(
ConfigurableListableBeanFactory factory, String beanName,
BeanDefinition bd) throws BeansException {
if (bd instanceof RootBeanDefinition) {
return (RootBeanDefinition) bd;
}
else if (bd instanceof ChildBeanDefinition) {
ChildBeanDefinition cbd = (ChildBeanDefinition) bd;
RootBeanDefinition pbd = null;
if (!beanName.equals(cbd.getParentName())) {
pbd = getMergedBeanDefinition(factory, cbd.getParentName(), true);
}
else {
if (factory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
ConfigurableListableBeanFactory parentFactory = (ConfigurableListableBeanFactory) factory
.getParentBeanFactory();
pbd = getMergedBeanDefinition(parentFactory, cbd.getParentName(),
true);
}
else {
throw new NoSuchBeanDefinitionException(
cbd.getParentName(),
"Parent name '"
+ cbd.getParentName()
+ "' is equal to bean name '"
+ beanName
+ "' - cannot be resolved without an AbstractBeanFactory parent");
}
}
// deep copy with overridden values
RootBeanDefinition rbd = new RootBeanDefinition(pbd);
rbd.overrideFrom(cbd);
return rbd;
}
else {
throw new BeanDefinitionStoreException(bd.getResourceDescription(),
beanName,
"Definition is neither a RootBeanDefinition nor a ChildBeanDefinition");
}
}
static RSACBeanInfo convertBeanDef(BeanDefinition origdef, String beanname,
ConfigurableListableBeanFactory factory, MethodAnalyser abdAnalyser,
BeanDefConverter converter) {
RSACBeanInfo rbi = new RSACBeanInfo();
AbstractBeanDefinition def = getMergedBeanDefinition(factory, beanname,
origdef);
MutablePropertyValues pvs = def.getPropertyValues();
PropertyValue[] values = pvs.getPropertyValues();
for (int j = 0; j < values.length; ++j) {
PropertyValue thispv = values[j];
Object beannames = BeanDefUtil.propertyValueToBeanName(thispv.getValue(),
converter);
boolean skip = false;
// skip recording the dependency if it was unresolvable (some
// unrecognised
// type) or was a single-valued type referring to a static dependency.
// NB - we now record ALL dependencies - bean-copying strategy
// discontinued.
if (beannames == null
// || beannames instanceof String
// && !blankcontext.containsBean((String) beannames)
) {
skip = true;
}
if (!skip) {
rbi.recordDependency(thispv.getName(), beannames);
}
}
// NB - illegal cast here is unavoidable.
// Bit of a problem here with Spring flow - apparently the bean class
// will NOT be set for a "factory-method" bean UNTIL it has been
// instantiated
// via the logic in AbstractAutowireCapableBeanFactory l.376:
// protected BeanWrapper instantiateUsingFactoryMethod(
AbstractBeanDefinition abd = def;
rbi.factorybean = abd.getFactoryBeanName();
rbi.factorymethod = abd.getFactoryMethodName();
rbi.initmethod = abd.getInitMethodName();
rbi.destroymethod = abd.getDestroyMethodName();
rbi.islazyinit = abd.isLazyInit();
rbi.dependson = abd.getDependsOn();
rbi.issingleton = abd.isSingleton();
rbi.isabstract = abd.isAbstract();
rbi.aliases = factory.containsBeanDefinition(beanname) ? factory
.getAliases(beanname)
: StringArrayParser.EMPTY_STRINGL;
if (abd.hasConstructorArgumentValues()) {
rbi.constructorargvals = abd.getConstructorArgumentValues();
}
if (rbi.factorymethod == null) {
// Core Spring change at 2.0M5 - ALL bean classes are now irrevocably lazy!!
// Package org.springframework.beans
// introduced lazy loading (and lazy validation) of bean classes in standard bean factories and bean definition readers
AccessMethod bcnaccess = abdAnalyser.getAccessMethod("beanClassName");
if (bcnaccess != null) {
String bcn = (String) bcnaccess.getChildObject(abd);
- rbi.beanclass = ClassGetter.forName(bcn);
+ if (bcn != null) {
+ rbi.beanclass = ClassGetter.forName(bcn);
+ }
}
else {
// all right then BE like that! We'll work out the class later.
// NB - beandef.getBeanClass() was eliminated around 1.2, we must
// use the downcast even earlier now.
rbi.beanclass = abd.getBeanClass();
}
}
return rbi;
}
// magic evil code from AbstractBeanFactory l.443 - this is the main reason
// I abandoned Spring Forms and the like, and it will return to plague us.
// Just take a look at the constructor for BeanWrapperImpl - one of these
// is created for EVERY BEAN IN A FACTORY!
// protected BeanWrapper createBeanWrapper(Object beanInstance) {
// return (beanInstance != null ? new BeanWrapperImpl(beanInstance) : new
// BeanWrapperImpl());
// }
// this method is really
// resolveValueIfNecessary **LITE**, we assume all other resolution
// is done by the parent factory and are ONLY interested in propertyvalues
// that refer to other beans IN THIS CONTAINER.
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
// l.900:
// protected Object resolveValueIfNecessary(
// String beanName, RootBeanDefinition mergedBeanDefinition, String argName,
// Object value)
// throws BeansException {
// Since actual values are the rarer case, make THEM the composite ones.
// returns either a String or StringList of bean names, or a ValueHolder
public static Object propertyValueToBeanName(Object value,
BeanDefConverter converter) {
Object beanspec = null;
if (value instanceof BeanDefinitionHolder) {
// Resolve BeanDefinitionHolder: contains BeanDefinition with name and
// aliases.
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
String beanname = bdHolder.getBeanName();
converter.convertBeanDef(bdHolder.getBeanDefinition(), beanname, true);
beanspec = beanname;
}
else if (value instanceof BeanDefinition) {
throw new IllegalArgumentException(
"No idea what to do with bean definition!");
}
else if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
beanspec = ref.getBeanName();
}
else if (value instanceof ManagedList) {
List valuelist = (List) value;
StringList togo = new StringList();
for (int i = 0; i < valuelist.size(); ++i) {
String thisbeanname = (String) propertyValueToBeanName(
valuelist.get(i), converter);
togo.add(thisbeanname);
}
beanspec = togo;
}
else if (value instanceof String) {
beanspec = new ValueHolder((String) value);
}
else if (value instanceof TypedStringValue) {
beanspec = new ValueHolder(((TypedStringValue)value).getValue());
}
else {
Logger.log.warn("RSACBeanLocator Got value " + value
+ " of unknown type " + value.getClass() + ": ignoring");
}
return beanspec;
}
}
| true | true |
static RSACBeanInfo convertBeanDef(BeanDefinition origdef, String beanname,
ConfigurableListableBeanFactory factory, MethodAnalyser abdAnalyser,
BeanDefConverter converter) {
RSACBeanInfo rbi = new RSACBeanInfo();
AbstractBeanDefinition def = getMergedBeanDefinition(factory, beanname,
origdef);
MutablePropertyValues pvs = def.getPropertyValues();
PropertyValue[] values = pvs.getPropertyValues();
for (int j = 0; j < values.length; ++j) {
PropertyValue thispv = values[j];
Object beannames = BeanDefUtil.propertyValueToBeanName(thispv.getValue(),
converter);
boolean skip = false;
// skip recording the dependency if it was unresolvable (some
// unrecognised
// type) or was a single-valued type referring to a static dependency.
// NB - we now record ALL dependencies - bean-copying strategy
// discontinued.
if (beannames == null
// || beannames instanceof String
// && !blankcontext.containsBean((String) beannames)
) {
skip = true;
}
if (!skip) {
rbi.recordDependency(thispv.getName(), beannames);
}
}
// NB - illegal cast here is unavoidable.
// Bit of a problem here with Spring flow - apparently the bean class
// will NOT be set for a "factory-method" bean UNTIL it has been
// instantiated
// via the logic in AbstractAutowireCapableBeanFactory l.376:
// protected BeanWrapper instantiateUsingFactoryMethod(
AbstractBeanDefinition abd = def;
rbi.factorybean = abd.getFactoryBeanName();
rbi.factorymethod = abd.getFactoryMethodName();
rbi.initmethod = abd.getInitMethodName();
rbi.destroymethod = abd.getDestroyMethodName();
rbi.islazyinit = abd.isLazyInit();
rbi.dependson = abd.getDependsOn();
rbi.issingleton = abd.isSingleton();
rbi.isabstract = abd.isAbstract();
rbi.aliases = factory.containsBeanDefinition(beanname) ? factory
.getAliases(beanname)
: StringArrayParser.EMPTY_STRINGL;
if (abd.hasConstructorArgumentValues()) {
rbi.constructorargvals = abd.getConstructorArgumentValues();
}
if (rbi.factorymethod == null) {
// Core Spring change at 2.0M5 - ALL bean classes are now irrevocably lazy!!
// Package org.springframework.beans
// introduced lazy loading (and lazy validation) of bean classes in standard bean factories and bean definition readers
AccessMethod bcnaccess = abdAnalyser.getAccessMethod("beanClassName");
if (bcnaccess != null) {
String bcn = (String) bcnaccess.getChildObject(abd);
rbi.beanclass = ClassGetter.forName(bcn);
}
else {
// all right then BE like that! We'll work out the class later.
// NB - beandef.getBeanClass() was eliminated around 1.2, we must
// use the downcast even earlier now.
rbi.beanclass = abd.getBeanClass();
}
}
return rbi;
}
|
static RSACBeanInfo convertBeanDef(BeanDefinition origdef, String beanname,
ConfigurableListableBeanFactory factory, MethodAnalyser abdAnalyser,
BeanDefConverter converter) {
RSACBeanInfo rbi = new RSACBeanInfo();
AbstractBeanDefinition def = getMergedBeanDefinition(factory, beanname,
origdef);
MutablePropertyValues pvs = def.getPropertyValues();
PropertyValue[] values = pvs.getPropertyValues();
for (int j = 0; j < values.length; ++j) {
PropertyValue thispv = values[j];
Object beannames = BeanDefUtil.propertyValueToBeanName(thispv.getValue(),
converter);
boolean skip = false;
// skip recording the dependency if it was unresolvable (some
// unrecognised
// type) or was a single-valued type referring to a static dependency.
// NB - we now record ALL dependencies - bean-copying strategy
// discontinued.
if (beannames == null
// || beannames instanceof String
// && !blankcontext.containsBean((String) beannames)
) {
skip = true;
}
if (!skip) {
rbi.recordDependency(thispv.getName(), beannames);
}
}
// NB - illegal cast here is unavoidable.
// Bit of a problem here with Spring flow - apparently the bean class
// will NOT be set for a "factory-method" bean UNTIL it has been
// instantiated
// via the logic in AbstractAutowireCapableBeanFactory l.376:
// protected BeanWrapper instantiateUsingFactoryMethod(
AbstractBeanDefinition abd = def;
rbi.factorybean = abd.getFactoryBeanName();
rbi.factorymethod = abd.getFactoryMethodName();
rbi.initmethod = abd.getInitMethodName();
rbi.destroymethod = abd.getDestroyMethodName();
rbi.islazyinit = abd.isLazyInit();
rbi.dependson = abd.getDependsOn();
rbi.issingleton = abd.isSingleton();
rbi.isabstract = abd.isAbstract();
rbi.aliases = factory.containsBeanDefinition(beanname) ? factory
.getAliases(beanname)
: StringArrayParser.EMPTY_STRINGL;
if (abd.hasConstructorArgumentValues()) {
rbi.constructorargvals = abd.getConstructorArgumentValues();
}
if (rbi.factorymethod == null) {
// Core Spring change at 2.0M5 - ALL bean classes are now irrevocably lazy!!
// Package org.springframework.beans
// introduced lazy loading (and lazy validation) of bean classes in standard bean factories and bean definition readers
AccessMethod bcnaccess = abdAnalyser.getAccessMethod("beanClassName");
if (bcnaccess != null) {
String bcn = (String) bcnaccess.getChildObject(abd);
if (bcn != null) {
rbi.beanclass = ClassGetter.forName(bcn);
}
}
else {
// all right then BE like that! We'll work out the class later.
// NB - beandef.getBeanClass() was eliminated around 1.2, we must
// use the downcast even earlier now.
rbi.beanclass = abd.getBeanClass();
}
}
return rbi;
}
|
diff --git a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToggleButtonTest.java b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToggleButtonTest.java
index 9f35865..5a3aa03 100644
--- a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToggleButtonTest.java
+++ b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToggleButtonTest.java
@@ -1,115 +1,114 @@
/*******************************************************************************
* Copyright (c) 2008 Ketan Padegaonkar 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:
* Ketan Padegaonkar - initial API and implementation
*******************************************************************************/
package org.eclipse.swtbot.swt.finder.widgets;
import static org.eclipse.swtbot.swt.finder.SWTBotTestCase.assertTextContains;
import static org.eclipse.swtbot.swt.finder.SWTBotTestCase.pass;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.finders.AbstractSWTTestCase;
import org.eclipse.swtbot.swt.finder.finders.ControlFinder;
import org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Ketan Padegaonkar <KetanPadegaonkar [at] gmail [dot] com>
* @version $Id$
*/
public class SWTBotToggleButtonTest extends AbstractSWTTestCase {
private SWTBot bot;
private long oldTimeout;
@Before
public void lowerTimeout() {
this.oldTimeout = SWTBotPreferences.TIMEOUT;
SWTBotPreferences.TIMEOUT = 2000;
}
@After
public void resetTimeout() {
SWTBotPreferences.TIMEOUT = oldTimeout;
}
@Test
public void clicksToggleButton() throws Exception {
try {
List<Text> findControls = new ControlFinder().findControls(widgetOfType(Text.class));
SWTBotText text = new SWTBotText(findControls.get(0));
+ bot.checkBox("Listen").select();
text.setText("");
- assertFalse(bot.checkBox("Listen").isChecked());
- bot.checkBox("Listen").click();
assertFalse(bot.toggleButton("One").isPressed());
bot.toggleButton("One").click();
assertTrue(bot.toggleButton("One").isPressed());
assertTextContains("Selection [13]: SelectionEvent{Button {One}", text);
} finally {
- bot.checkBox("Listen").click();
+ bot.checkBox("Listen").deselect();
bot.button("Clear").click();
}
}
@Test
public void doesNotMatchRadioButtons() throws Exception {
try {
assertNull(bot.toggleButton("SWT.TOGGLE").widget);
fail("Expecting WidgetNotFoundException");
} catch (WidgetNotFoundException e) {
pass();
}
try {
assertNull(bot.toggleButton("Preferred").widget);
fail("Expecting WidgetNotFoundException");
} catch (WidgetNotFoundException e) {
pass();
}
}
@Test
public void doesNotMatchRegularButtons() throws Exception {
try {
assertNull(bot.toggleButton("Change...").widget);
fail("Expecting WidgetNotFoundException");
} catch (WidgetNotFoundException e) {
pass();
}
try {
assertNull(bot.toggleButton("Change").widget);
fail("Expecting WidgetNotFoundException");
} catch (WidgetNotFoundException e) {
pass();
}
}
public void setUp() throws Exception {
super.setUp();
bot = new SWTBot();
bot.tabItem("Button").activate();
bot.radio("SWT.TOGGLE").click();
}
public void tearDown() throws Exception {
super.tearDown();
bot.radio("SWT.PUSH").click();
}
}
| false | true |
public void clicksToggleButton() throws Exception {
try {
List<Text> findControls = new ControlFinder().findControls(widgetOfType(Text.class));
SWTBotText text = new SWTBotText(findControls.get(0));
text.setText("");
assertFalse(bot.checkBox("Listen").isChecked());
bot.checkBox("Listen").click();
assertFalse(bot.toggleButton("One").isPressed());
bot.toggleButton("One").click();
assertTrue(bot.toggleButton("One").isPressed());
assertTextContains("Selection [13]: SelectionEvent{Button {One}", text);
} finally {
bot.checkBox("Listen").click();
bot.button("Clear").click();
}
}
|
public void clicksToggleButton() throws Exception {
try {
List<Text> findControls = new ControlFinder().findControls(widgetOfType(Text.class));
SWTBotText text = new SWTBotText(findControls.get(0));
bot.checkBox("Listen").select();
text.setText("");
assertFalse(bot.toggleButton("One").isPressed());
bot.toggleButton("One").click();
assertTrue(bot.toggleButton("One").isPressed());
assertTextContains("Selection [13]: SelectionEvent{Button {One}", text);
} finally {
bot.checkBox("Listen").deselect();
bot.button("Clear").click();
}
}
|
diff --git a/src/main/java/ru/xrm/app/parsers/VacancySectionParser.java b/src/main/java/ru/xrm/app/parsers/VacancySectionParser.java
index 3824ed1..c03c32b 100644
--- a/src/main/java/ru/xrm/app/parsers/VacancySectionParser.java
+++ b/src/main/java/ru/xrm/app/parsers/VacancySectionParser.java
@@ -1,79 +1,79 @@
package ru.xrm.app.parsers;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import ru.xrm.app.config.Config;
import ru.xrm.app.config.Entry;
import ru.xrm.app.domain.Section;
import ru.xrm.app.misc.SectionSet;
public class VacancySectionParser {
Config config;
String html;
Section sections;
public VacancySectionParser(Config config, String html){
this.config = config;
this.html = html;
}
public List<Section> parse() {
SectionSet sections=SectionSet.getInstance();
//List<Section> sections = new ArrayList<Section>();
List<Entry> vacancySectionProperties=config.getVacancySectionProperties();
Document doc = Jsoup.parse(html);
for (Entry prop:vacancySectionProperties){
// here we got multiple elements for each vacancySectionProperty
Elements elems=doc.select(prop.getCssQuery());
Object value="";
int idx=0;
for (Element e:elems){
if (prop.getElementWalker() != null){
e=prop.getElementWalker().walk(e);
}
if (prop.getElementEvaluator() !=null){
value=prop.getElementEvaluator().evaluate(e);
}
if (prop.getPropertyTransformer() !=null){
value = prop.getPropertyTransformer().transform(value.toString());
}
Section section;
// if object of some index does not exists, create it and add to result
try{
- section=sections.getByIndex(idx);
- }catch(IndexOutOfBoundsException e1){
+ section=sections.getSections().get(idx);
+ }catch(IndexOutOfBoundsException ex){
section=new Section();
sections.add(section);
}
// fill property for current object
try {
section.setProperty(prop.getKey(), value);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
// configuration exception
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
idx++;
}
}
return sections.getSections();
}
}
| true | true |
public List<Section> parse() {
SectionSet sections=SectionSet.getInstance();
//List<Section> sections = new ArrayList<Section>();
List<Entry> vacancySectionProperties=config.getVacancySectionProperties();
Document doc = Jsoup.parse(html);
for (Entry prop:vacancySectionProperties){
// here we got multiple elements for each vacancySectionProperty
Elements elems=doc.select(prop.getCssQuery());
Object value="";
int idx=0;
for (Element e:elems){
if (prop.getElementWalker() != null){
e=prop.getElementWalker().walk(e);
}
if (prop.getElementEvaluator() !=null){
value=prop.getElementEvaluator().evaluate(e);
}
if (prop.getPropertyTransformer() !=null){
value = prop.getPropertyTransformer().transform(value.toString());
}
Section section;
// if object of some index does not exists, create it and add to result
try{
section=sections.getByIndex(idx);
}catch(IndexOutOfBoundsException e1){
section=new Section();
sections.add(section);
}
// fill property for current object
try {
section.setProperty(prop.getKey(), value);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
// configuration exception
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
idx++;
}
}
return sections.getSections();
}
|
public List<Section> parse() {
SectionSet sections=SectionSet.getInstance();
//List<Section> sections = new ArrayList<Section>();
List<Entry> vacancySectionProperties=config.getVacancySectionProperties();
Document doc = Jsoup.parse(html);
for (Entry prop:vacancySectionProperties){
// here we got multiple elements for each vacancySectionProperty
Elements elems=doc.select(prop.getCssQuery());
Object value="";
int idx=0;
for (Element e:elems){
if (prop.getElementWalker() != null){
e=prop.getElementWalker().walk(e);
}
if (prop.getElementEvaluator() !=null){
value=prop.getElementEvaluator().evaluate(e);
}
if (prop.getPropertyTransformer() !=null){
value = prop.getPropertyTransformer().transform(value.toString());
}
Section section;
// if object of some index does not exists, create it and add to result
try{
section=sections.getSections().get(idx);
}catch(IndexOutOfBoundsException ex){
section=new Section();
sections.add(section);
}
// fill property for current object
try {
section.setProperty(prop.getKey(), value);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
// configuration exception
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
idx++;
}
}
return sections.getSections();
}
|
diff --git a/org/python/compiler/ArgListCompiler.java b/org/python/compiler/ArgListCompiler.java
index 440aca12..c6da6e6d 100644
--- a/org/python/compiler/ArgListCompiler.java
+++ b/org/python/compiler/ArgListCompiler.java
@@ -1,107 +1,107 @@
// Copyright � Corporation for National Research Initiatives
package org.python.compiler;
import org.python.parser.*;
import java.io.IOException;
import java.util.Vector;
import java.util.Enumeration;
public class ArgListCompiler extends org.python.parser.Visitor
{
public boolean arglist, keywordlist;
public Vector defaults;
public Vector names;
public SimpleNode init_code;
public ArgListCompiler() {
arglist = keywordlist = false;
defaults = new Vector();
names = new Vector();
init_code = new SimpleNode(PythonGrammarTreeConstants.JJTSUITE);
}
public void reset() {
arglist = keywordlist = false;
defaults.removeAllElements();
names.removeAllElements();
//init_code.removeAllElements();
}
public SimpleNode[] getDefaults() {
SimpleNode[] children = new SimpleNode[defaults.size()];
for (int i=0; i<children.length; i++) {
children[i] = (SimpleNode)defaults.elementAt(i);
}
return children;
}
public Object varargslist(SimpleNode node) throws Exception {
int n = node.getNumChildren();
for (int i=0; i<n; i++) {
node.getChild(i).visit(this);
}
return null;
}
public Object ExtraArgList(SimpleNode node) throws Exception {
arglist = true;
names.addElement(node.getChild(0).visit(this));
return null;
}
public Object ExtraKeywordList(SimpleNode node) throws Exception {
keywordlist = true;
names.addElement(node.getChild(0).visit(this));
return null;
}
public Object defaultarg(SimpleNode node) throws Exception {
Object name = node.getChild(0).visit(this);
// make sure the named argument isn't already in the list of arguments
for (Enumeration e=names.elements(); e.hasMoreElements();) {
String objname = (String)e.nextElement();
if (objname.equals(name))
- throw new ParseException("duplicate keyword found: " + name,
- node);
+ throw new ParseException("duplicate argument name found: " +
+ name, node);
}
names.addElement(name);
//Handle tuple arguments properly
if (node.getChild(0).id == PythonGrammarTreeConstants.JJTFPLIST) {
SimpleNode expr = new SimpleNode(
PythonGrammarTreeConstants.JJTEXPR_STMT);
// Set the right line number for this expr
expr.beginLine = node.beginLine;
expr.jjtAddChild(node.getChild(0), 0);
SimpleNode nm = new SimpleNode(PythonGrammarTreeConstants.JJTNAME);
nm.setInfo(name);
expr.jjtAddChild(nm, 1);
init_code.jjtAddChild(expr, init_code.getNumChildren());
}
// Handle default args if specified
if (node.getNumChildren() > 1) {
defaults.addElement(node.getChild(1));
} else {
if (defaults.size() > 0)
throw new ParseException(
"non-default argument follows default argument");
}
return null;
}
public Object fplist(SimpleNode node) throws Exception {
String name = "(";
int n = node.getNumChildren();
for (int i=0; i<n-1; i++) {
name = name+node.getChild(i).visit(this)+", ";
}
name = name+node.getChild(n-1).visit(this)+")";
return name;
}
public Object Name(SimpleNode node) throws ParseException, IOException {
return node.getInfo();
}
}
| true | true |
public Object defaultarg(SimpleNode node) throws Exception {
Object name = node.getChild(0).visit(this);
// make sure the named argument isn't already in the list of arguments
for (Enumeration e=names.elements(); e.hasMoreElements();) {
String objname = (String)e.nextElement();
if (objname.equals(name))
throw new ParseException("duplicate keyword found: " + name,
node);
}
names.addElement(name);
//Handle tuple arguments properly
if (node.getChild(0).id == PythonGrammarTreeConstants.JJTFPLIST) {
SimpleNode expr = new SimpleNode(
PythonGrammarTreeConstants.JJTEXPR_STMT);
// Set the right line number for this expr
expr.beginLine = node.beginLine;
expr.jjtAddChild(node.getChild(0), 0);
SimpleNode nm = new SimpleNode(PythonGrammarTreeConstants.JJTNAME);
nm.setInfo(name);
expr.jjtAddChild(nm, 1);
init_code.jjtAddChild(expr, init_code.getNumChildren());
}
// Handle default args if specified
if (node.getNumChildren() > 1) {
defaults.addElement(node.getChild(1));
} else {
if (defaults.size() > 0)
throw new ParseException(
"non-default argument follows default argument");
}
return null;
}
|
public Object defaultarg(SimpleNode node) throws Exception {
Object name = node.getChild(0).visit(this);
// make sure the named argument isn't already in the list of arguments
for (Enumeration e=names.elements(); e.hasMoreElements();) {
String objname = (String)e.nextElement();
if (objname.equals(name))
throw new ParseException("duplicate argument name found: " +
name, node);
}
names.addElement(name);
//Handle tuple arguments properly
if (node.getChild(0).id == PythonGrammarTreeConstants.JJTFPLIST) {
SimpleNode expr = new SimpleNode(
PythonGrammarTreeConstants.JJTEXPR_STMT);
// Set the right line number for this expr
expr.beginLine = node.beginLine;
expr.jjtAddChild(node.getChild(0), 0);
SimpleNode nm = new SimpleNode(PythonGrammarTreeConstants.JJTNAME);
nm.setInfo(name);
expr.jjtAddChild(nm, 1);
init_code.jjtAddChild(expr, init_code.getNumChildren());
}
// Handle default args if specified
if (node.getNumChildren() > 1) {
defaults.addElement(node.getChild(1));
} else {
if (defaults.size() > 0)
throw new ParseException(
"non-default argument follows default argument");
}
return null;
}
|
diff --git a/SoarSuite/soar-java/soar-smljava/src/main/java/edu/umich/soar/robot/OutputLinkManager.java b/SoarSuite/soar-java/soar-smljava/src/main/java/edu/umich/soar/robot/OutputLinkManager.java
index b13311192..456cbfa40 100644
--- a/SoarSuite/soar-java/soar-smljava/src/main/java/edu/umich/soar/robot/OutputLinkManager.java
+++ b/SoarSuite/soar-java/soar-smljava/src/main/java/edu/umich/soar/robot/OutputLinkManager.java
@@ -1,120 +1,125 @@
package edu.umich.soar.robot;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import sml.Agent;
import sml.Identifier;
/**
* @author voigtjr Soar output-link management. Creates input for splinter and
* other parts of the system.
*/
final public class OutputLinkManager {
private static final Logger logger = Logger.getLogger(OutputLinkManager.class);
private final Agent agent;
private final HashMap<String, Command> commands = new HashMap<String, Command>();
private final Set<Integer> completedTimeTags = new HashSet<Integer>();
private Command runningCommand;
public OutputLinkManager(Agent agent) {
this.agent = agent;
}
public DifferentialDriveCommand update() {
// TODO: update status of running command
// process output
DifferentialDriveCommand ddc = null;
for (int i = 0; i < agent.GetNumberCommands(); ++i) {
Identifier commandWme = agent.GetCommand(i);
// is it already complete?
Integer timetag = Integer.valueOf(commandWme.GetTimeTag());
if (completedTimeTags.contains(timetag)) {
continue;
}
completedTimeTags.add(timetag);
// is it already running?
synchronized (this) {
if (runningCommand != null && runningCommand.wme().GetTimeTag() == timetag) {
continue;
}
}
String commandName = commandWme.GetAttribute();
logger.debug(commandName + " timetag:" + timetag);
Command commandObject = commands.get(commandName);
if (commandObject == null) {
CommandStatus.error.addStatus(commandWme, "Unknown command: " + commandName);
continue;
}
if (commandObject.createsDDC()) {
if (ddc != null) {
+ if (commandObject instanceof EStopCommand) {
+ CommandStatus.error.addStatus(commandWme, "Encountered estop command, overriding existing command " + ddc);
+ ddc = DifferentialDriveCommand.newEStopCommand();
+ continue;
+ }
CommandStatus.error.addStatus(commandWme, "Ignoring command " + commandName + " because already have " + ddc);
continue;
}
if (runningCommand != null) {
runningCommand.interrupt();
runningCommand = null;
}
}
if (!commandObject.execute(commandWme)) {
if (commandObject.createsDDC()) {
logger.warn("Error with new drive command, commanding estop.");
ddc = DifferentialDriveCommand.newEStopCommand();
}
continue;
}
if (commandObject.createsDDC()) {
ddc = commandObject.getDDC();
runningCommand = commandObject;
logger.debug(ddc);
}
}
if (runningCommand != null && runningCommand.update()) {
runningCommand = null;
}
return ddc;
}
public void destroy() {
commands.clear();
completedTimeTags.clear();
runningCommand = null;
}
public void create(WaypointInterface waypoints, SendMessagesInterface msgSend,
ReceiveMessagesInterface msgRcv, ConfigureInterface configure,
OffsetPose opose) {
commands.put(MotorCommand.NAME, MotorCommand.newInstance());
commands.put(SetVelocityCommand.NAME, SetVelocityCommand.newInstance());
commands.put(SetLinearVelocityCommand.NAME, SetLinearVelocityCommand.newInstance());
commands.put(SetAngularVelocityCommand.NAME, SetAngularVelocityCommand.newInstance());
commands.put(SetHeadingCommand.NAME, SetHeadingCommand.newInstance(opose));
commands.put(SetHeadingLinearCommand.NAME, SetHeadingLinearCommand.newInstance(opose));
commands.put(StopCommand.NAME, StopCommand.newInstance(opose));
commands.put(EStopCommand.NAME, EStopCommand.newInstance());
commands.put(AddWaypointCommand.NAME, AddWaypointCommand.newInstance(opose, waypoints));
commands.put(RemoveWaypointCommand.NAME, RemoveWaypointCommand.newInstance(waypoints));
commands.put(EnableWaypointCommand.NAME, EnableWaypointCommand.newInstance(waypoints));
commands.put(DisableWaypointCommand.NAME, DisableWaypointCommand.newInstance(waypoints));
commands.put(SendMessageCommand.NAME, SendMessageCommand.newInstance(msgSend, agent.GetAgentName()));
commands.put(RemoveMessageCommand.NAME, RemoveMessageCommand.newInstance(msgRcv));
commands.put(ClearMessagesCommand.NAME, ClearMessagesCommand.newInstance(msgRcv));
commands.put(ConfigureCommand.NAME, ConfigureCommand.newInstance(opose, configure));
}
}
| true | true |
public DifferentialDriveCommand update() {
// TODO: update status of running command
// process output
DifferentialDriveCommand ddc = null;
for (int i = 0; i < agent.GetNumberCommands(); ++i) {
Identifier commandWme = agent.GetCommand(i);
// is it already complete?
Integer timetag = Integer.valueOf(commandWme.GetTimeTag());
if (completedTimeTags.contains(timetag)) {
continue;
}
completedTimeTags.add(timetag);
// is it already running?
synchronized (this) {
if (runningCommand != null && runningCommand.wme().GetTimeTag() == timetag) {
continue;
}
}
String commandName = commandWme.GetAttribute();
logger.debug(commandName + " timetag:" + timetag);
Command commandObject = commands.get(commandName);
if (commandObject == null) {
CommandStatus.error.addStatus(commandWme, "Unknown command: " + commandName);
continue;
}
if (commandObject.createsDDC()) {
if (ddc != null) {
CommandStatus.error.addStatus(commandWme, "Ignoring command " + commandName + " because already have " + ddc);
continue;
}
if (runningCommand != null) {
runningCommand.interrupt();
runningCommand = null;
}
}
if (!commandObject.execute(commandWme)) {
if (commandObject.createsDDC()) {
logger.warn("Error with new drive command, commanding estop.");
ddc = DifferentialDriveCommand.newEStopCommand();
}
continue;
}
if (commandObject.createsDDC()) {
ddc = commandObject.getDDC();
runningCommand = commandObject;
logger.debug(ddc);
}
}
if (runningCommand != null && runningCommand.update()) {
runningCommand = null;
}
return ddc;
}
|
public DifferentialDriveCommand update() {
// TODO: update status of running command
// process output
DifferentialDriveCommand ddc = null;
for (int i = 0; i < agent.GetNumberCommands(); ++i) {
Identifier commandWme = agent.GetCommand(i);
// is it already complete?
Integer timetag = Integer.valueOf(commandWme.GetTimeTag());
if (completedTimeTags.contains(timetag)) {
continue;
}
completedTimeTags.add(timetag);
// is it already running?
synchronized (this) {
if (runningCommand != null && runningCommand.wme().GetTimeTag() == timetag) {
continue;
}
}
String commandName = commandWme.GetAttribute();
logger.debug(commandName + " timetag:" + timetag);
Command commandObject = commands.get(commandName);
if (commandObject == null) {
CommandStatus.error.addStatus(commandWme, "Unknown command: " + commandName);
continue;
}
if (commandObject.createsDDC()) {
if (ddc != null) {
if (commandObject instanceof EStopCommand) {
CommandStatus.error.addStatus(commandWme, "Encountered estop command, overriding existing command " + ddc);
ddc = DifferentialDriveCommand.newEStopCommand();
continue;
}
CommandStatus.error.addStatus(commandWme, "Ignoring command " + commandName + " because already have " + ddc);
continue;
}
if (runningCommand != null) {
runningCommand.interrupt();
runningCommand = null;
}
}
if (!commandObject.execute(commandWme)) {
if (commandObject.createsDDC()) {
logger.warn("Error with new drive command, commanding estop.");
ddc = DifferentialDriveCommand.newEStopCommand();
}
continue;
}
if (commandObject.createsDDC()) {
ddc = commandObject.getDDC();
runningCommand = commandObject;
logger.debug(ddc);
}
}
if (runningCommand != null && runningCommand.update()) {
runningCommand = null;
}
return ddc;
}
|
diff --git a/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java b/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
index a28cda6d1..ba1ed38e1 100644
--- a/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
+++ b/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
@@ -1,219 +1,217 @@
/*
* $Id: RadioRenderer.java,v 1.90 2008/01/15 20:34:50 rlubke Exp $
*/
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
// RadioRenderer.java
package com.sun.faces.renderkit.html_basic;
import com.sun.faces.renderkit.Attribute;
import com.sun.faces.renderkit.AttributeManager;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.util.RequestStateManager;
import javax.el.ELException;
import javax.faces.component.UIComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import java.util.Collection;
import java.util.Iterator;
import java.io.IOException;
/**
* <B>ReadoRenderer</B> is a class that renders the current value of
* <code>UISelectOne<code> or <code>UISelectMany<code> component as a list of
* radio buttons
*/
public class RadioRenderer extends SelectManyCheckboxListRenderer {
private static final Attribute[] ATTRIBUTES =
AttributeManager.getAttributes(AttributeManager.Key.SELECTONERADIO);
// ------------------------------------------------------- Protected Methods
@Override
protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (newValue.equals(curValue)) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component);
writer.endElement("input");
- writer.endElement("td");
- writer.startElement("td",component);
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
} // end of class RadioRenderer
| true | true |
protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (newValue.equals(curValue)) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component);
writer.endElement("input");
writer.endElement("td");
writer.startElement("td",component);
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
|
protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (newValue.equals(curValue)) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component);
writer.endElement("input");
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
|
diff --git a/org.iucn.sis.server.extensions.user/src/org/iucn/sis/server/extensions/user/resources/UserRestlet.java b/org.iucn.sis.server.extensions.user/src/org/iucn/sis/server/extensions/user/resources/UserRestlet.java
index 8a40b37d..7c567ade 100644
--- a/org.iucn.sis.server.extensions.user/src/org/iucn/sis/server/extensions/user/resources/UserRestlet.java
+++ b/org.iucn.sis.server.extensions.user/src/org/iucn/sis/server/extensions/user/resources/UserRestlet.java
@@ -1,249 +1,255 @@
package org.iucn.sis.server.extensions.user.resources;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.iucn.sis.server.api.io.PermissionIO;
import org.iucn.sis.server.api.io.UserIO;
import org.iucn.sis.server.api.persistance.SISPersistentManager;
import org.iucn.sis.server.api.persistance.hibernate.PersistentException;
import org.iucn.sis.server.api.restlets.BaseServiceRestlet;
import org.iucn.sis.shared.api.models.PermissionGroup;
import org.iucn.sis.shared.api.models.User;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ResourceException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.solertium.util.TrivialExceptionHandler;
public class UserRestlet extends BaseServiceRestlet {
public UserRestlet(Context context) {
super(context);
}
@Override
public void definePaths() {
paths.add("/users/{username}");
paths.add("/users");
}
private String getUsername(Request request) {
return (String) request.getAttributes().get("username");
}
public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException {
String username = getUsername(request);
if (username == null)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please provide a username");
UserIO userIO = new UserIO(session);
PermissionIO permissionIO = new PermissionIO(session);
boolean isID = false;
try {
Integer.parseInt(username);
isID = true;
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
final User user;
if (isID) {
try {
user = SISPersistentManager.instance().getObject(session, User.class, Integer.valueOf(username));
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
else
user = userIO.getUserFromUsername(username);
if (user == null)
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "User not found.");
Document doc = getEntityAsDocument(entity);
NodeList fields = doc.getElementsByTagName("field");
for (int i = 0; i < fields.getLength(); i++) {
Element field = (Element) fields.item(i);
String name = field.getAttribute("name");
String value = field.getTextContent();
if ("firstname".equalsIgnoreCase(name))
user.setFirstName(value);
else if ("lastname".equalsIgnoreCase(name))
user.setLastName(value);
else if ("username".equalsIgnoreCase(name)) {
if (!username.equals(value)) {
- //They want to change the username...
- User existing = userIO.getUserFromUsername(value);
- if (existing != null)
- throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
+ /*
+ * They want to change the username... check if this
+ * user is active first; if they are disabled, we
+ * don't care what they do...
+ */
+ if (user.getState() == User.ACTIVE) {
+ User existing = userIO.getUserFromUsername(value);
+ if (existing != null)
+ throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
+ }
user.setUsername(value);
if (user.getEmail() == null || username.equals(user.getEmail()))
user.setEmail(value);
}
}
else if ("nickname".equalsIgnoreCase(name))
user.setNickname(value);
else if ("initials".equalsIgnoreCase(name))
user.setInitials(value);
else if ("affiliation".equalsIgnoreCase(name))
user.setAffiliation(value);
else if ("sisUser".equalsIgnoreCase(name) || "sis".equalsIgnoreCase(name))
user.setSisUser(Boolean.valueOf(value));
else if ("rapidListUser".equalsIgnoreCase(name))
user.setRapidlistUser(Boolean.valueOf(value));
else if ("quickgroup".equalsIgnoreCase(name)){
user.getPermissionGroups().clear();
for (String permName : value.split(",")) {
try {
PermissionGroup group = permissionIO.getPermissionGroup(permName);
if (group != null)
user.getPermissionGroups().add(group);
else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("The permission group " + permName + " does not exist.", MediaType.TEXT_PLAIN);
return;
}
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
else if ("state".equalsIgnoreCase(name)) {
Integer state = null;
try {
state = Integer.valueOf(value);
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
if (state == null || !(state.intValue() == User.ACTIVE || state.intValue() == User.DELETED)) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("Invalid user state specified.", MediaType.TEXT_PLAIN);
return;
}
if (state.intValue() == User.ACTIVE && user.getState() == User.DELETED) {
/*
* Ensure this is legal!
*/
User existing = userIO.getUserFromUsername(user.getUsername());
if (existing != null)
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
}
user.setState(state);
}
else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "The property " + name + " is invalid.");
}
try {
if (userIO.saveUser(user))
response.setStatus(Status.SUCCESS_OK);
else
throw new ResourceException(Status.SERVER_ERROR_INTERNAL);
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
@Override
public Representation handleGet(Request request, Response response, Session session) throws ResourceException {
Criteria criteria = session.createCriteria(User.class);
if (getUsername(request) != null)
criteria.add(Restrictions.eq("username", getUsername(request)));
String sort = request.getResourceRef().getQueryAsForm().getFirstValue("sort");
if (sort != null && !"".equals(sort))
criteria.addOrder(Order.asc(sort));
List<User> list;
try {
list = criteria.list();
} catch (Exception e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
StringBuilder results = new StringBuilder("<xml>");
for (User user : list)
results.append(user.toFullXML());
results.append("</xml>");
return new StringRepresentation(results.toString(), MediaType.TEXT_XML);
/*
ExperimentalSelectQuery query = new ExperimentalSelectQuery();
query.select("user", "*");
query.select("user_permission", "permission_group_id");
query.join("user_permission", new QRelationConstraint(new CanonicalColumnName("user", "id"),
new CanonicalColumnName("user_permission", "user_id")));
query.constrain(new QComparisonConstraint(new CanonicalColumnName("user", "state"), QConstraint.CT_EQUALS,
User.ACTIVE));
if (getUsername() != null) {
query.constrain(new QComparisonConstraint(new CanonicalColumnName("user", "username"),
QConstraint.CT_EQUALS, getUsername()));
}
String queryString = query.getSQL(SIS.get().getExecutionContext().getDBSession());
queryString = queryString.replaceAll("JOIN", "LEFT JOIN");
final Map<Integer, User> idToUsers = new HashMap<Integer, User>();
try {
SIS.get().getExecutionContext().doQuery(queryString, new RowProcessor() {
@Override
public void process(Row row) {
PermissionGroup group = new PermissionGroup();
group.setID(row.get("permission_group_id").getInteger());
if (idToUsers.containsKey(group.getId())) {
if (group.getId() != 0)
idToUsers.get(group.getId()).getPermissionGroups().add(group);
} else {
User user = new User();
user.setId(row.get("id").getInteger());
user.setUsername(row.get("username").getString());
user.setFirstName(row.get("first_name").getString());
user.setLastName(row.get("last_name").getString());
user.setInitials(row.get("initials").getString());
user.setAffiliation(row.get("affiliation").getString());
user.setSisUser(row.get("sis_user").getInteger().equals(1));
user.setRapidlistUser(row.get("rapidlist_user").getInteger().equals(1));
user.setEmail(row.get("email").getString());
if (group.getId() != 0)
user.getPermissionGroups().add(group);
idToUsers.put(user.getId(), user);
}
}
});
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
StringBuilder results = new StringBuilder("<xml>");
for (User user : idToUsers.values()) {
results.append(user.toFullXML());
}
results.append("</xml>");
return new StringRepresentation(results.toString(), MediaType.TEXT_XML);
*/
}
}
| true | true |
public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException {
String username = getUsername(request);
if (username == null)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please provide a username");
UserIO userIO = new UserIO(session);
PermissionIO permissionIO = new PermissionIO(session);
boolean isID = false;
try {
Integer.parseInt(username);
isID = true;
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
final User user;
if (isID) {
try {
user = SISPersistentManager.instance().getObject(session, User.class, Integer.valueOf(username));
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
else
user = userIO.getUserFromUsername(username);
if (user == null)
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "User not found.");
Document doc = getEntityAsDocument(entity);
NodeList fields = doc.getElementsByTagName("field");
for (int i = 0; i < fields.getLength(); i++) {
Element field = (Element) fields.item(i);
String name = field.getAttribute("name");
String value = field.getTextContent();
if ("firstname".equalsIgnoreCase(name))
user.setFirstName(value);
else if ("lastname".equalsIgnoreCase(name))
user.setLastName(value);
else if ("username".equalsIgnoreCase(name)) {
if (!username.equals(value)) {
//They want to change the username...
User existing = userIO.getUserFromUsername(value);
if (existing != null)
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
user.setUsername(value);
if (user.getEmail() == null || username.equals(user.getEmail()))
user.setEmail(value);
}
}
else if ("nickname".equalsIgnoreCase(name))
user.setNickname(value);
else if ("initials".equalsIgnoreCase(name))
user.setInitials(value);
else if ("affiliation".equalsIgnoreCase(name))
user.setAffiliation(value);
else if ("sisUser".equalsIgnoreCase(name) || "sis".equalsIgnoreCase(name))
user.setSisUser(Boolean.valueOf(value));
else if ("rapidListUser".equalsIgnoreCase(name))
user.setRapidlistUser(Boolean.valueOf(value));
else if ("quickgroup".equalsIgnoreCase(name)){
user.getPermissionGroups().clear();
for (String permName : value.split(",")) {
try {
PermissionGroup group = permissionIO.getPermissionGroup(permName);
if (group != null)
user.getPermissionGroups().add(group);
else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("The permission group " + permName + " does not exist.", MediaType.TEXT_PLAIN);
return;
}
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
else if ("state".equalsIgnoreCase(name)) {
Integer state = null;
try {
state = Integer.valueOf(value);
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
if (state == null || !(state.intValue() == User.ACTIVE || state.intValue() == User.DELETED)) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("Invalid user state specified.", MediaType.TEXT_PLAIN);
return;
}
if (state.intValue() == User.ACTIVE && user.getState() == User.DELETED) {
/*
* Ensure this is legal!
*/
User existing = userIO.getUserFromUsername(user.getUsername());
if (existing != null)
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
}
user.setState(state);
}
else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "The property " + name + " is invalid.");
}
try {
if (userIO.saveUser(user))
response.setStatus(Status.SUCCESS_OK);
else
throw new ResourceException(Status.SERVER_ERROR_INTERNAL);
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
|
public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException {
String username = getUsername(request);
if (username == null)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please provide a username");
UserIO userIO = new UserIO(session);
PermissionIO permissionIO = new PermissionIO(session);
boolean isID = false;
try {
Integer.parseInt(username);
isID = true;
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
final User user;
if (isID) {
try {
user = SISPersistentManager.instance().getObject(session, User.class, Integer.valueOf(username));
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
else
user = userIO.getUserFromUsername(username);
if (user == null)
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "User not found.");
Document doc = getEntityAsDocument(entity);
NodeList fields = doc.getElementsByTagName("field");
for (int i = 0; i < fields.getLength(); i++) {
Element field = (Element) fields.item(i);
String name = field.getAttribute("name");
String value = field.getTextContent();
if ("firstname".equalsIgnoreCase(name))
user.setFirstName(value);
else if ("lastname".equalsIgnoreCase(name))
user.setLastName(value);
else if ("username".equalsIgnoreCase(name)) {
if (!username.equals(value)) {
/*
* They want to change the username... check if this
* user is active first; if they are disabled, we
* don't care what they do...
*/
if (user.getState() == User.ACTIVE) {
User existing = userIO.getUserFromUsername(value);
if (existing != null)
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
}
user.setUsername(value);
if (user.getEmail() == null || username.equals(user.getEmail()))
user.setEmail(value);
}
}
else if ("nickname".equalsIgnoreCase(name))
user.setNickname(value);
else if ("initials".equalsIgnoreCase(name))
user.setInitials(value);
else if ("affiliation".equalsIgnoreCase(name))
user.setAffiliation(value);
else if ("sisUser".equalsIgnoreCase(name) || "sis".equalsIgnoreCase(name))
user.setSisUser(Boolean.valueOf(value));
else if ("rapidListUser".equalsIgnoreCase(name))
user.setRapidlistUser(Boolean.valueOf(value));
else if ("quickgroup".equalsIgnoreCase(name)){
user.getPermissionGroups().clear();
for (String permName : value.split(",")) {
try {
PermissionGroup group = permissionIO.getPermissionGroup(permName);
if (group != null)
user.getPermissionGroups().add(group);
else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("The permission group " + permName + " does not exist.", MediaType.TEXT_PLAIN);
return;
}
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
else if ("state".equalsIgnoreCase(name)) {
Integer state = null;
try {
state = Integer.valueOf(value);
} catch (Exception e) {
TrivialExceptionHandler.ignore(this, e);
}
if (state == null || !(state.intValue() == User.ACTIVE || state.intValue() == User.DELETED)) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity("Invalid user state specified.", MediaType.TEXT_PLAIN);
return;
}
if (state.intValue() == User.ACTIVE && user.getState() == User.DELETED) {
/*
* Ensure this is legal!
*/
User existing = userIO.getUserFromUsername(user.getUsername());
if (existing != null)
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "An active user with this username already exists.");
}
user.setState(state);
}
else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "The property " + name + " is invalid.");
}
try {
if (userIO.saveUser(user))
response.setStatus(Status.SUCCESS_OK);
else
throw new ResourceException(Status.SERVER_ERROR_INTERNAL);
} catch (PersistentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
}
|
diff --git a/src/main/java/ru/javatalks/checkers/gui/Dialog.java b/src/main/java/ru/javatalks/checkers/gui/Dialog.java
index a38003a..adcc0c3 100644
--- a/src/main/java/ru/javatalks/checkers/gui/Dialog.java
+++ b/src/main/java/ru/javatalks/checkers/gui/Dialog.java
@@ -1,250 +1,250 @@
package ru.javatalks.checkers.gui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.javatalks.checkers.gui.actions.*;
import ru.javatalks.checkers.gui.language.L10nBundle;
import ru.javatalks.checkers.gui.language.LangMenuItems;
import ru.javatalks.checkers.gui.language.Language;
import ru.javatalks.checkers.logic.ChessBoardModel;
import ru.javatalks.checkers.model.Player;
import javax.annotation.PostConstruct;
import javax.swing.*;
import java.awt.*;
import static java.lang.System.exit;
/**
* This class provides GUI
*
* @author Kapellan
*/
@Component
public class Dialog {
@Autowired
private L10nBundle bundle;
@Autowired
private ChessBoardModel boardModel;
@Autowired
private ChessBoardPanel chessBoardPanel;
@Autowired
private CheckBoardMouseListener act;
@Autowired
private NewGameAction newGameAction;
@Autowired
private ExitAction exitAction;
@Autowired
private RulesAction rulesAction;
@Autowired
private AboutAction aboutAction;
@Autowired
private ChessBoardModel chessBoardModel;
@Autowired
private GameFlowController gameFlowController;
@Autowired
private StepLogger stepLogger;
private LangMenuItems itemLanguage;
private JTextArea tArea;
private JFrame frame;
private JMenuBar menuBar;
private JMenu menuGame;
private JMenu menuSettings;
private JMenu menuHelp;
private JMenuItem itemNewGame;
private JMenuItem itemExit;
private JMenuItem itemRules;
private JMenuItem itemAbout;
private JLabel labelComp;
private JLabel labelUser;
private JPanel resultPanel;
@PostConstruct
public void runDialog() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ignore) {
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initializeComponent();
}
});
}
private void initializeComponent() {
tArea = new JTextArea(26, 12);
frame = new JFrame();
menuBar = new JMenuBar();
menuGame = new JMenu();
menuSettings = new JMenu();
menuHelp = new JMenu();
labelComp = new JLabel();
labelUser = new JLabel();
JScrollPane scrollPane = new JScrollPane(tArea);
resultPanel = new JPanel();
JPanel mainPanel = new JPanel(new FlowLayout());
tArea.append(bundle.getString("stepUserText") + '\n');
chessBoardPanel.addMouseListener(act);
itemLanguage = new LangMenuItems(bundle, this);
menuSettings.add(itemLanguage);
itemNewGame = new JMenuItem(newGameAction);
itemExit = new JMenuItem(exitAction);
menuGame.add(itemNewGame);
menuGame.add(itemExit);
itemRules = new JMenuItem(rulesAction);
itemAbout = new JMenuItem(aboutAction);
menuHelp.add(itemRules);
menuHelp.add(itemAbout);
menuBar.add(menuGame);
menuBar.add(menuSettings);
menuBar.add(menuHelp);
tArea.setFont(new Font("Dialog", Font.PLAIN, 12));
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
tArea.setEditable(false);
labelUser.setText(bundle.getString("labelUserTitle") + boardModel.getUserCheckerNumber());
labelComp.setText(bundle.getString("labelCompTitle") + boardModel.getCompCheckerNumber());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelUser.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelComp.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
LayoutManager boxLayout = new BoxLayout(resultPanel, BoxLayout.Y_AXIS);
resultPanel.setLayout(boxLayout);
resultPanel.add(labelUser);
resultPanel.add(labelComp);
resultPanel.add(Box.createVerticalStrut(10));
resultPanel.add(scrollPane);
resultPanel.add(Box.createVerticalStrut(20));
mainPanel.add(chessBoardPanel);
mainPanel.add(resultPanel);
setLanguage(bundle.getCurrentLanguage());
frame.setFocusable(true);
frame.getRootPane().setOpaque(true);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(700, 500));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void setLanguage(Language lang) {
bundle.setLanguage(lang);
frame.setTitle(bundle.getString("frameTitle"));
menuGame.setText(bundle.getString("gameTitle"));
menuSettings.setText(bundle.getString("settingsTitle"));
itemLanguage.setText(bundle.getString("languageTitle"));
menuHelp.setText(bundle.getString("helpTitle"));
itemNewGame.setText(bundle.getString("newGameTitle"));
itemExit.setText(bundle.getString("exitTitle"));
itemRules.setText(bundle.getString("rulesTitle"));
itemAbout.setText(bundle.getString("aboutTitle"));
labelComp.setText(bundle.getString("labelCompTitle") + boardModel.getCompCheckerNumber());
labelUser.setText(bundle.getString("labelUserTitle") + boardModel.getUserCheckerNumber());
}
void checkGameStatus() {
labelUser.setText(bundle.getString("labelUserTitle") + boardModel.getUserCheckerNumber());
labelComp.setText(bundle.getString("labelCompTitle") + boardModel.getCompCheckerNumber());
String[] optionsDialog = {bundle.getString("dialogNewGame"), bundle.getString("dialogExit")};
if (!boardModel.hasCheckerOf(Player.OPPONENT)) {
notifyAboutGameEnd(optionsDialog, "userWon", "noCompCheckersText");
return;
}
if (!boardModel.hasCheckerOf(Player.USER)) {
notifyAboutGameEnd(optionsDialog, "userLost", "noUserCheckersText");
return;
}
if (!boardModel.canStep(Player.OPPONENT)) {
notifyAboutGameEnd(optionsDialog, "userWon", "compIsBlockedText");
return;
}
if (!boardModel.canStep(Player.USER)) {
notifyAboutGameEnd(optionsDialog, "userLost", "userIsBlockedText");
return;
}
}
private void notifyAboutGameEnd(String[] optionsDialog, String titleKey, String textKey) {
gameFlowController.stopThread();
int userChoice = JOptionPane.showOptionDialog(null,
bundle.getString(textKey),
bundle.getString(titleKey),
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, optionsDialog, optionsDialog[0]);
if (userChoice == JOptionPane.YES_OPTION) {
restartGame();
}
else {
exit(0);
}
}
public void restartGame() {
chessBoardModel.setInitialState();
stepLogger.clear();
}
/**
* Thread safe set log content
* @param text
*/
public void setText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tArea.setText(text);
}
});
}
}
| true | true |
private void initializeComponent() {
tArea = new JTextArea(26, 12);
frame = new JFrame();
menuBar = new JMenuBar();
menuGame = new JMenu();
menuSettings = new JMenu();
menuHelp = new JMenu();
labelComp = new JLabel();
labelUser = new JLabel();
JScrollPane scrollPane = new JScrollPane(tArea);
resultPanel = new JPanel();
JPanel mainPanel = new JPanel(new FlowLayout());
tArea.append(bundle.getString("stepUserText") + '\n');
chessBoardPanel.addMouseListener(act);
itemLanguage = new LangMenuItems(bundle, this);
menuSettings.add(itemLanguage);
itemNewGame = new JMenuItem(newGameAction);
itemExit = new JMenuItem(exitAction);
menuGame.add(itemNewGame);
menuGame.add(itemExit);
itemRules = new JMenuItem(rulesAction);
itemAbout = new JMenuItem(aboutAction);
menuHelp.add(itemRules);
menuHelp.add(itemAbout);
menuBar.add(menuGame);
menuBar.add(menuSettings);
menuBar.add(menuHelp);
tArea.setFont(new Font("Dialog", Font.PLAIN, 12));
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
tArea.setEditable(false);
labelUser.setText(bundle.getString("labelUserTitle") + boardModel.getUserCheckerNumber());
labelComp.setText(bundle.getString("labelCompTitle") + boardModel.getCompCheckerNumber());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelUser.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelComp.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
LayoutManager boxLayout = new BoxLayout(resultPanel, BoxLayout.Y_AXIS);
resultPanel.setLayout(boxLayout);
resultPanel.add(labelUser);
resultPanel.add(labelComp);
resultPanel.add(Box.createVerticalStrut(10));
resultPanel.add(scrollPane);
resultPanel.add(Box.createVerticalStrut(20));
mainPanel.add(chessBoardPanel);
mainPanel.add(resultPanel);
setLanguage(bundle.getCurrentLanguage());
frame.setFocusable(true);
frame.getRootPane().setOpaque(true);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(700, 500));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
|
private void initializeComponent() {
tArea = new JTextArea(26, 12);
frame = new JFrame();
menuBar = new JMenuBar();
menuGame = new JMenu();
menuSettings = new JMenu();
menuHelp = new JMenu();
labelComp = new JLabel();
labelUser = new JLabel();
JScrollPane scrollPane = new JScrollPane(tArea);
resultPanel = new JPanel();
JPanel mainPanel = new JPanel(new FlowLayout());
tArea.append(bundle.getString("stepUserText") + '\n');
chessBoardPanel.addMouseListener(act);
itemLanguage = new LangMenuItems(bundle, this);
menuSettings.add(itemLanguage);
itemNewGame = new JMenuItem(newGameAction);
itemExit = new JMenuItem(exitAction);
menuGame.add(itemNewGame);
menuGame.add(itemExit);
itemRules = new JMenuItem(rulesAction);
itemAbout = new JMenuItem(aboutAction);
menuHelp.add(itemRules);
menuHelp.add(itemAbout);
menuBar.add(menuGame);
menuBar.add(menuSettings);
menuBar.add(menuHelp);
tArea.setFont(new Font("Dialog", Font.PLAIN, 12));
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
tArea.setEditable(false);
labelUser.setText(bundle.getString("labelUserTitle") + boardModel.getUserCheckerNumber());
labelComp.setText(bundle.getString("labelCompTitle") + boardModel.getCompCheckerNumber());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelUser.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
labelComp.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
LayoutManager boxLayout = new BoxLayout(resultPanel, BoxLayout.Y_AXIS);
resultPanel.setLayout(boxLayout);
resultPanel.add(labelUser);
resultPanel.add(labelComp);
resultPanel.add(Box.createVerticalStrut(10));
resultPanel.add(scrollPane);
resultPanel.add(Box.createVerticalStrut(20));
mainPanel.add(chessBoardPanel);
mainPanel.add(resultPanel);
setLanguage(bundle.getCurrentLanguage());
frame.setFocusable(true);
frame.getRootPane().setOpaque(true);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(700, 500));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.